id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_good_236_0 | /* Apache 2.0 - Copyright 2007-2018 - pancake and dso
class.c rewrite: Adam Pridgen <dso@rice.edu || adam.pridgen@thecoverofnight.com>
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <r_types.h>
#include <r_util.h>
#include <r_bin.h>
#include <math.h>
#include <sdb.h>
#include "class.h"
#include "dsojson.h"
static PrintfCallback Eprintf =(PrintfCallback) printf;
#ifdef IFDBG
#undef IFDBG
#endif
#define DO_THE_DBG 0
#define IFDBG if (DO_THE_DBG)
#define IFINT if (0)
#define MAX_CPITEMS 8192
R_API char *U(r_bin_java_unmangle_method)(const char *flags, const char *name, const char *params, const char *r_value);
R_API int r_bin_java_is_fm_type_private(RBinJavaField *fm_type);
R_API int r_bin_java_is_fm_type_protected(RBinJavaField *fm_type);
R_API ut32 U(r_bin_java_swap_uint)(ut32 x);
// R_API const char * r_bin_java_get_this_class_name(RBinJavaObj *bin);
R_API void U(add_cp_objs_to_sdb)(RBinJavaObj * bin);
R_API void U(add_field_infos_to_sdb)(RBinJavaObj * bin);
R_API void U(add_method_infos_to_sdb)(RBinJavaObj * bin);
R_API RList *retrieve_all_access_string_and_value(RBinJavaAccessFlags *access_flags);
R_API char *retrieve_access_string(ut16 flags, RBinJavaAccessFlags *access_flags);
R_API ut16 calculate_access_value(const char *access_flags_str, RBinJavaAccessFlags *access_flags);
R_API int r_bin_java_new_bin(RBinJavaObj *bin, ut64 loadaddr, Sdb *kv, const ut8 *buf, ut64 len);
R_API int extract_type_value(const char *arg_str, char **output);
R_API int r_bin_java_check_reset_cp_obj(RBinJavaCPTypeObj *cp_obj, ut8 tag);
R_API ut8 *r_bin_java_cp_get_4bytes(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len);
R_API ut8 *r_bin_java_cp_get_8bytes(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len);
R_API ut8 *r_bin_java_cp_get_utf8(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len);
R_API RBinJavaCPTypeObj *r_bin_java_get_item_from_bin_cp_list(RBinJavaObj *bin, ut64 idx);
R_API RBinJavaCPTypeObj *r_bin_java_get_item_from_cp_item_list(RList *cp_list, ut64 idx);
// Allocs for objects
R_API RBinJavaCPTypeObj *r_bin_java_class_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_fieldref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_methodref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_interfacemethodref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_name_and_type_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_string_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_integer_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_float_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_long_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_double_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_utf8_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 offset);
R_API RBinJavaCPTypeObj *r_bin_java_do_nothing_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz);
R_API RBinJavaCPTypeObj *r_bin_java_clone_cp_item(RBinJavaCPTypeObj *obj);
R_API RBinJavaCPTypeObj *r_bin_java_clone_cp_idx(RBinJavaObj *bin, ut32 idx);
R_API RBinJavaCPTypeObj *r_bin_java_methodhandle_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz);
R_API RBinJavaCPTypeObj *r_bin_java_methodtype_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz);
R_API RBinJavaCPTypeObj *r_bin_java_invokedynamic_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz);
// Deallocs for type objects
R_API void r_bin_java_default_free(void /*RBinJavaCPTypeObj*/ *obj);
R_API void r_bin_java_obj_free(void /*RBinJavaCPTypeObj*/ *obj);
R_API void r_bin_java_utf8_info_free(void /*RBinJavaCPTypeObj*/ *obj);
R_API void r_bin_java_do_nothing_free(void /*RBinJavaCPTypeObj*/ *obj);
R_API void r_bin_java_fmtype_free(void /*RBinJavaField*/ *fm_type);
// handle freeing the lists
// handle the reading of the various field
R_API RBinJavaAttrInfo *r_bin_java_read_next_attr(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len);
R_API RBinJavaCPTypeObj *r_bin_java_read_next_constant_pool_item(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, ut64 len);
R_API RBinJavaAttrMetas *r_bin_java_get_attr_type_by_name(const char *name);
R_API RBinJavaCPTypeObj *r_bin_java_get_java_null_cp();
R_API ut64 r_bin_java_read_class_file2(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, ut64 len);
R_API RBinJavaAttrInfo *r_bin_java_get_attr_from_field(RBinJavaField *field, R_BIN_JAVA_ATTR_TYPE attr_type, ut32 pos);
R_API RBinJavaField *r_bin_java_read_next_field(RBinJavaObj *bin, const ut64 offset, const ut8 *buffer, const ut64 len);
R_API RBinJavaField *r_bin_java_read_next_method(RBinJavaObj *bin, const ut64 offset, const ut8 *buffer, const ut64 len);
R_API void r_bin_java_print_utf8_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_name_and_type_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_double_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_long_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_float_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_integer_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_string_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_classref_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_fieldref_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_methodref_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_interfacemethodref_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_unknown_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_null_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_unknown_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_methodhandle_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_methodtype_cp_summary(RBinJavaCPTypeObj *obj);
R_API void r_bin_java_print_invokedynamic_cp_summary(RBinJavaCPTypeObj *obj);
R_API RBinJavaCPTypeObj *r_bin_java_unknown_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz);
R_API RBinJavaInterfaceInfo *r_bin_java_interface_new(RBinJavaObj *bin, const ut8 *buf, ut64 sz);
R_API RBinJavaInterfaceInfo *r_bin_java_read_next_interface_item(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, ut64 len);
R_API void r_bin_java_interface_free(void /*RBinJavaInterfaceInfo*/ *obj);
R_API void r_bin_java_stack_frame_free(void /*RBinJavaStackMapFrame*/ *obj);
R_API void r_bin_java_stack_map_table_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_verification_info_free(void /*RBinJavaVerificationObj*/ *obj);
R_API void r_bin_java_print_stack_map_table_attr_summary(RBinJavaAttrInfo *obj);
R_API void r_bin_java_print_stack_map_frame_summary(RBinJavaStackMapFrame *obj);
R_API void r_bin_java_print_verification_info_summary(RBinJavaVerificationObj *obj);
R_API RBinJavaStackMapFrame *r_bin_java_build_stack_frame_from_local_variable_table(RBinJavaObj *bin, RBinJavaAttrInfo *attr);
R_API void U(r_bin_java_print_stack_map_append_frame_summary)(RBinJavaStackMapFrame * obj);
R_API void U(r_bin_java_stack_frame_default_free)(void /*RBinJavaStackMapFrame*/ *stack_frame);
R_API void U(r_bin_java_stack_frame_do_nothing_free)(void /*RBinJavaStackMapFrame*/ *stack_frame);
R_API void U(r_bin_java_stack_frame_do_nothing_new)(RBinJavaObj * bin, RBinJavaStackMapFrame * stack_frame, ut64 offset);
R_API RBinJavaStackMapFrame *r_bin_java_stack_map_frame_new(ut8 *buffer, ut64 sz, RBinJavaStackMapFrame *p_frame, ut64 buf_offset);
// R_API RBinJavaStackMapFrame* r_bin_java_stack_map_frame_new (ut8* buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaElementValue *r_bin_java_element_value_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
// R_API RBinJavaVerificationObj* r_bin_java_read_next_verification_info_new(ut8* buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaElementValuePair *r_bin_java_element_pair_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaElementValue *r_bin_java_element_value_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
// R_API RBinJavaBootStrapArgument* r_bin_java_bootstrap_method_argument_new(ut8* buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaBootStrapMethod *r_bin_java_bootstrap_method_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaAnnotationsArray *r_bin_java_annotation_array_new(ut8 *buffer, ut64 sz, ut64 buf_offset);
R_API RBinJavaElementValueMetas *r_bin_java_get_ev_meta_from_tag(ut8 tag);
R_API RBinJavaCPTypeMetas *U(r_bin_java_get_cp_meta_from_tag)(ut8 tag);
R_API void r_bin_java_inner_classes_attr_entry_free(void /*RBinJavaClassesAttribute*/ *attr);
R_API void r_bin_java_annotation_default_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_enclosing_methods_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_local_variable_type_table_attr_entry_free(void /*RBinJavaLocalVariableTypeAttribute*/ *lvattr);
R_API void r_bin_java_local_variable_type_table_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_signature_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_source_debug_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_element_value_free(void /*RBinJavaElementValue*/ *element_value);
R_API void r_bin_java_element_pair_free(void /*RBinJavaElementValuePair*/ *ev_pair);
R_API void r_bin_java_annotation_free(void /*RBinJavaAnnotation*/ *annotation);
R_API void r_bin_java_rtv_annotations_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_rti_annotations_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_annotation_array_free(void /*RBinJavaAnnotationsArray*/ *annotation_array);
R_API void r_bin_java_bootstrap_methods_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_bootstrap_method_free(void /*RBinJavaBootStrapMethod*/ *bsm);
R_API void r_bin_java_bootstrap_method_argument_free(void /*RBinJavaBootStrapArgument*/ *bsm_arg);
R_API void r_bin_java_rtvp_annotations_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_rtip_annotations_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_unknown_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_code_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_constant_value_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_deprecated_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_exceptions_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_inner_classes_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_line_number_table_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_local_variable_table_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_source_code_file_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_synthetic_attr_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_print_annotation_default_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_enclosing_methods_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_local_variable_type_attr_summary(RBinJavaLocalVariableTypeAttribute *lvattr);
R_API void r_bin_java_print_local_variable_type_table_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_signature_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_source_debug_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_element_value_summary(RBinJavaElementValue *element_value);
R_API void r_bin_java_print_annotation_summary(RBinJavaAnnotation *annotation);
R_API void r_bin_java_print_element_pair_summary(RBinJavaElementValuePair *ev_pair);
R_API void r_bin_java_print_bootstrap_methods_attr_summary(RBinJavaAttrInfo *attr);
// R_API void r_bin_java_bootstrap_method_summary(RBinJavaBootStrapMethod *bsm);
// R_API void r_bin_java_bootstrap_method_argument_summary(RBinJavaBootStrapArgument *bsm_arg);
R_API void r_bin_java_print_rtv_annotations_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_rti_annotations_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_annotation_array_summary(RBinJavaAnnotationsArray *annotation_array);
R_API void r_bin_java_print_rtvp_annotations_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_rtip_annotations_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_attribute_free(void /*RBinJavaAttrInfo*/ *attr);
R_API void r_bin_java_constant_pool(void /*RBinJavaCPTypeObj*/ *obj);
R_API void r_bin_java_print_field_summary(RBinJavaField *field);
// R_API void r_bin_java_print_interface_summary(RBinJavaField *field);
R_API void r_bin_java_print_method_summary(RBinJavaField *field);
R_API void r_bin_java_print_code_exceptions_attr_summary(RBinJavaExceptionEntry *exc_entry);
R_API void r_bin_java_print_code_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_constant_value_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_deprecated_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_exceptions_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_classes_attr_summary(RBinJavaClassesAttribute *icattr);
R_API void r_bin_java_print_inner_classes_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_line_number_table_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_local_variable_attr_summary(RBinJavaLocalVariableAttribute *lvattr);
R_API void r_bin_java_print_local_variable_table_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_source_code_file_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_synthetic_attr_summary(RBinJavaAttrInfo *attr);
R_API void r_bin_java_print_attr_summary(RBinJavaAttrInfo *attr);
R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64 sz, st64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_unknown_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_enclosing_methods_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_local_variable_type_table_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_signature_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_source_debug_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_rti_annotations_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_rtvp_annotations_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_rtip_annotations_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_code_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_deprecated_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_exceptions_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_local_variable_table_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_stack_map_table_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(ut8 *buf, ut64 sz, ut64 buf_offset);
R_API ut64 r_bin_java_unknown_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_annotation_default_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_enclosing_methods_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_local_variable_type_table_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_signature_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_source_debug_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_bootstrap_methods_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_rtv_annotations_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_rti_annotations_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_rtvp_annotations_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_rtip_annotations_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_code_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_constant_value_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_deprecated_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_exceptions_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_inner_classes_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_line_number_table_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_local_variable_table_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_source_code_file_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_stack_map_table_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_synthetic_attr_calc_size(RBinJavaAttrInfo *attr);
R_API ut64 r_bin_java_bootstrap_method_calc_size(RBinJavaBootStrapMethod *bsm);
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *ev_pair);
R_API ut64 r_bin_java_element_value_calc_size(RBinJavaElementValue *element_value);
R_API ut64 r_bin_java_unknown_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_class_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_fieldref_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_methodref_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_interfacemethodref_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_name_and_type_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_string_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_integer_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_float_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_long_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_double_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_utf8_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_do_nothing_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_methodhandle_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_methodtype_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API ut64 r_bin_java_invokedynamic_cp_calc_size(RBinJavaCPTypeObj *obj);
R_API RBinJavaStackMapFrame *r_bin_java_default_stack_frame();
R_API RList *r_bin_java_find_cp_const_by_val_float(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len);
R_API RList *r_bin_java_find_cp_const_by_val_double(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len);
R_API RList *r_bin_java_find_cp_const_by_val_int(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len);
R_API RList *r_bin_java_find_cp_const_by_val_long(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len);
R_API RList *r_bin_java_find_cp_const_by_val_utf8(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len);
R_API ut8 *r_bin_java_cp_append_classref_and_name(RBinJavaObj *bin, ut32 *out_sz, const char *classname, const ut32 classname_len);
R_API ut8 *U(r_bin_java_cp_append_ref_cname_fname_ftype)(RBinJavaObj * bin, ut32 * out_sz, ut8 tag, const char *cname, const ut32 c_len, const char *fname, const ut32 f_len, const char *tname, const ut32 t_len);
R_API ut8 *r_bin_java_cp_get_classref(RBinJavaObj *bin, ut32 *out_sz, const char *classname, const ut32 classname_len, const ut16 name_idx);
R_API ut8 *U(r_bin_java_cp_get_method_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 class_idx, ut16 name_and_type_idx);
R_API ut8 *U(r_bin_java_cp_get_field_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 class_idx, ut16 name_and_type_idx);
R_API ut8 *r_bin_java_cp_get_fm_ref(RBinJavaObj *bin, ut32 *out_sz, ut8 tag, ut16 class_idx, ut16 name_and_type_idx);
R_API ut8 *r_bin_java_cp_get_2_ut16(RBinJavaObj *bin, ut32 *out_sz, ut8 tag, ut16 ut16_one, ut16 ut16_two);
R_API ut8 *r_bin_java_cp_get_name_type(RBinJavaObj *bin, ut32 *out_sz, ut16 name_idx, ut16 type_idx);
static char *convert_string(const char *bytes, ut32 len) {
ut32 idx = 0, pos = 0;
ut32 str_sz = 32 * len + 1;
char *cpy_buffer = len > 0 ? malloc (str_sz) : NULL;
if (!cpy_buffer) {
return cpy_buffer;
}
// 4x is the increase from byte to \xHH where HH represents hexed byte
memset (cpy_buffer, 0, str_sz);
while (idx < len && pos < len) {
if (dso_json_char_needs_hexing (bytes[idx])) {
if (pos + 2 < len) {
free (cpy_buffer);
return NULL;
}
sprintf (cpy_buffer + pos, "\\x%02x", bytes[idx]);
pos += 4;
} else {
cpy_buffer[pos] = bytes[idx];
pos++;
}
idx++;
}
return cpy_buffer;
}
// taken from LLVM Code Byte Swap
// TODO: move into r_util
R_API ut32 U(r_bin_java_swap_uint)(ut32 x) {
const ut32 Byte0 = x & 0x000000FF;
const ut32 Byte1 = x & 0x0000FF00;
const ut32 Byte2 = x & 0x00FF0000;
const ut32 Byte3 = x & 0xFF000000;
return (Byte0 << 24) | (Byte1 << 8) | (Byte2 >> 8) | (Byte3 >> 24);
}
static bool R_BIN_JAVA_NULL_TYPE_INITTED = false;
// XXX - this is a global variable used while parsing the class file
// if multi-threaded class parsing is enabled, this variable needs to
// be guarded with a lock.
static RBinJavaObj *R_BIN_JAVA_GLOBAL_BIN = NULL;
static RBinJavaAccessFlags FIELD_ACCESS_FLAGS[] = {
{ "public", R_BIN_JAVA_FIELD_ACC_PUBLIC, 6 },
{ "private", R_BIN_JAVA_FIELD_ACC_PRIVATE, 7 },
{ "protected", R_BIN_JAVA_FIELD_ACC_PROTECTED, 9 },
{ "static", R_BIN_JAVA_FIELD_ACC_STATIC, 6 },
{ "final", R_BIN_JAVA_FIELD_ACC_FINAL, 5 },
{ "undefined.0x0020", 0x0020, 16 },
{ "volatile", R_BIN_JAVA_FIELD_ACC_VOLATILE, 8 },
{ "transient", R_BIN_JAVA_FIELD_ACC_TRANSIENT, 9 },
{ "undefined.0x0100", 0x0100, 16 },
{ "undefined.0x0200", 0x0200, 16 },
{ "undefined.0x0400", 0x0400, 16 },
{ "undefined.0x0800", 0x0800, 16 },
{ "synthetic", R_BIN_JAVA_FIELD_ACC_SYNTHETIC, 9 },
{ "undefined.0x2000", 0x2000, 16 },
{ "enum", R_BIN_JAVA_FIELD_ACC_ENUM, 16 },
{ "undefined.0x8000", 0x8000, 16 },
{ NULL, 0, 0 }
};
static RBinJavaAccessFlags METHOD_ACCESS_FLAGS[] = {
{ "public", R_BIN_JAVA_METHOD_ACC_PUBLIC, 6 },
{ "private", R_BIN_JAVA_METHOD_ACC_PRIVATE, 7 },
{ "protected", R_BIN_JAVA_METHOD_ACC_PROTECTED, 9 },
{ "static", R_BIN_JAVA_METHOD_ACC_STATIC, 6 },
{ "final", R_BIN_JAVA_METHOD_ACC_FINAL, 5 },
{ "synchronized", R_BIN_JAVA_METHOD_ACC_SYNCHRONIZED, 12 },
{ "bridge", R_BIN_JAVA_METHOD_ACC_BRIDGE, 6 },
{ "varargs", R_BIN_JAVA_METHOD_ACC_VARARGS, 7 },
{ "native", R_BIN_JAVA_METHOD_ACC_NATIVE, 6 },
{ "interface", R_BIN_JAVA_METHOD_ACC_INTERFACE, 9 },
{ "abstract", R_BIN_JAVA_METHOD_ACC_ABSTRACT, 8 },
{ "strict", R_BIN_JAVA_METHOD_ACC_STRICT, 6 },
{ "synthetic", R_BIN_JAVA_METHOD_ACC_SYNTHETIC, 9 },
{ "annotation", R_BIN_JAVA_METHOD_ACC_ANNOTATION, 10 },
{ "enum", R_BIN_JAVA_METHOD_ACC_ENUM, 4 },
{ "undefined.0x8000", 0x8000, 16 },
{ NULL, 0, 0 }
};
// XXX - Fix these there are some incorrect ongs
static RBinJavaAccessFlags CLASS_ACCESS_FLAGS[] = {
{ "public", R_BIN_JAVA_CLASS_ACC_PUBLIC, 6 },
{ "undefined.0x0002", 0x0002, 16 },
{ "undefined.0x0004", 0x0004, 16 },
{ "undefined.0x0008", 0x0008, 16 },
{ "final", R_BIN_JAVA_CLASS_ACC_FINAL, 5 },
{ "super", R_BIN_JAVA_CLASS_ACC_SUPER, 5 },
{ "undefined.0x0040", 0x0040, 16 },
{ "undefined.0x0080", 0x0080, 16 },
{ "undefined.0x0100", 0x0100, 16 },
{ "interface", R_BIN_JAVA_CLASS_ACC_INTERFACE, 9 },
{ "abstract", R_BIN_JAVA_CLASS_ACC_ABSTRACT, 8 },
{ "undefined.0x0800", 0x0800, 16 },
{ "synthetic", R_BIN_JAVA_CLASS_ACC_SYNTHETIC, 9 },
{ "annotation", R_BIN_JAVA_CLASS_ACC_ANNOTATION, 10 },
{ "enum", R_BIN_JAVA_CLASS_ACC_ENUM, 4 },
{ "undefined.0x8000", 0x8000, 16 },
{ NULL, 0, 0 }
};
static RBinJavaRefMetas R_BIN_JAVA_REF_METAS[] = {
{ "Unknown", R_BIN_JAVA_REF_UNKNOWN },
{ "GetField", R_BIN_JAVA_REF_GETFIELD },
{ "GetStatic", R_BIN_JAVA_REF_GETSTATIC },
{ "PutField", R_BIN_JAVA_REF_PUTFIELD },
{ "PutStatic", R_BIN_JAVA_REF_PUTSTATIC },
{ "InvokeVirtual", R_BIN_JAVA_REF_INVOKEVIRTUAL },
{ "InvokeStatic", R_BIN_JAVA_REF_INVOKESTATIC },
{ "InvokeSpecial", R_BIN_JAVA_REF_INVOKESPECIAL },
{ "NewInvokeSpecial", R_BIN_JAVA_REF_NEWINVOKESPECIAL },
{ "InvokeInterface", R_BIN_JAVA_REF_INVOKEINTERFACE }
};
static ut16 R_BIN_JAVA_ELEMENT_VALUE_METAS_SZ = 14;
static RBinJavaElementValueMetas R_BIN_JAVA_ELEMENT_VALUE_METAS[] = {
{ "Byte", R_BIN_JAVA_EV_TAG_BYTE, NULL },
{ "Char", R_BIN_JAVA_EV_TAG_CHAR, NULL },
{ "Double", R_BIN_JAVA_EV_TAG_DOUBLE, NULL },
{ "Float", R_BIN_JAVA_EV_TAG_FLOAT, NULL },
{ "Integer", R_BIN_JAVA_EV_TAG_INT, NULL },
{ "Long", R_BIN_JAVA_EV_TAG_LONG, NULL },
{ "Short", R_BIN_JAVA_EV_TAG_SHORT, NULL },
{ "Boolean", R_BIN_JAVA_EV_TAG_BOOLEAN, NULL },
{ "Array of ", R_BIN_JAVA_EV_TAG_ARRAY, NULL },
{ "String", R_BIN_JAVA_EV_TAG_STRING, NULL },
{ "Enum", R_BIN_JAVA_EV_TAG_ENUM, NULL },
{ "Class", R_BIN_JAVA_EV_TAG_CLASS, NULL },
{ "Annotation", R_BIN_JAVA_EV_TAG_ANNOTATION, NULL },
{ "Unknown", R_BIN_JAVA_EV_TAG_UNKNOWN, NULL },
};
static RBinJavaVerificationMetas R_BIN_JAVA_VERIFICATION_METAS[] = {
{ "Top", R_BIN_JAVA_STACKMAP_TOP },
{ "Integer", R_BIN_JAVA_STACKMAP_INTEGER },
{ "Float", R_BIN_JAVA_STACKMAP_FLOAT },
{ "Double", R_BIN_JAVA_STACKMAP_DOUBLE },
{ "Long", R_BIN_JAVA_STACKMAP_LONG },
{ "NULL", R_BIN_JAVA_STACKMAP_NULL },
{ "This", R_BIN_JAVA_STACKMAP_THIS },
{ "Object", R_BIN_JAVA_STACKMAP_OBJECT },
{ "Uninitialized", R_BIN_JAVA_STACKMAP_UNINIT },
{ "Unknown", R_BIN_JAVA_STACKMAP_UNKNOWN }
};
static RBinJavaStackMapFrameMetas R_BIN_JAVA_STACK_MAP_FRAME_METAS[] = {
{ "ImplicitStackFrame", R_BIN_JAVA_STACK_FRAME_IMPLICIT, NULL },
{ "Same", R_BIN_JAVA_STACK_FRAME_SAME, NULL },
{ "SameLocals1StackItem", R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1, NULL },
{ "Chop", R_BIN_JAVA_STACK_FRAME_CHOP, NULL },
{ "SameFrameExtended", R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED, NULL },
{ "Append", R_BIN_JAVA_STACK_FRAME_APPEND, NULL },
{ "FullFrame", R_BIN_JAVA_STACK_FRAME_FULL_FRAME, NULL },
{ "Reserved", R_BIN_JAVA_STACK_FRAME_RESERVED, NULL }
};
static RBinJavaCPTypeObjectAllocs R_BIN_ALLOCS_CONSTANTS[] = {
{ r_bin_java_do_nothing_new, r_bin_java_do_nothing_free, r_bin_java_print_null_cp_summary, r_bin_java_do_nothing_calc_size, r_bin_java_print_null_cp_stringify },
{ r_bin_java_utf8_cp_new, r_bin_java_utf8_info_free, r_bin_java_print_utf8_cp_summary, r_bin_java_utf8_cp_calc_size, r_bin_java_print_utf8_cp_stringify },
{ r_bin_java_unknown_cp_new, r_bin_java_default_free, r_bin_java_print_unknown_cp_summary, r_bin_java_unknown_cp_calc_size, r_bin_java_print_unknown_cp_stringify },
{ r_bin_java_integer_cp_new, r_bin_java_default_free, r_bin_java_print_integer_cp_summary, r_bin_java_integer_cp_calc_size, r_bin_java_print_integer_cp_stringify },
{ r_bin_java_float_cp_new, r_bin_java_default_free, r_bin_java_print_float_cp_summary, r_bin_java_float_cp_calc_size, r_bin_java_print_float_cp_stringify },
{ r_bin_java_long_cp_new, r_bin_java_default_free, r_bin_java_print_long_cp_summary, r_bin_java_long_cp_calc_size, r_bin_java_print_long_cp_stringify },
{ r_bin_java_double_cp_new, r_bin_java_default_free, r_bin_java_print_double_cp_summary, r_bin_java_double_cp_calc_size, r_bin_java_print_double_cp_stringify },
{ r_bin_java_class_cp_new, r_bin_java_default_free, r_bin_java_print_classref_cp_summary, r_bin_java_class_cp_calc_size, r_bin_java_print_classref_cp_stringify },
{ r_bin_java_string_cp_new, r_bin_java_default_free, r_bin_java_print_string_cp_summary, r_bin_java_string_cp_calc_size, r_bin_java_print_string_cp_stringify },
{ r_bin_java_fieldref_cp_new, r_bin_java_default_free, r_bin_java_print_fieldref_cp_summary, r_bin_java_fieldref_cp_calc_size, r_bin_java_print_fieldref_cp_stringify },
{ r_bin_java_methodref_cp_new, r_bin_java_default_free, r_bin_java_print_methodref_cp_summary, r_bin_java_methodref_cp_calc_size, r_bin_java_print_methodref_cp_stringify },
{ r_bin_java_interfacemethodref_cp_new, r_bin_java_default_free, r_bin_java_print_interfacemethodref_cp_summary, r_bin_java_interfacemethodref_cp_calc_size, r_bin_java_print_interfacemethodref_cp_stringify },
{ r_bin_java_name_and_type_cp_new, r_bin_java_default_free, r_bin_java_print_name_and_type_cp_summary, r_bin_java_name_and_type_cp_calc_size, r_bin_java_print_name_and_type_cp_stringify },
{ NULL, NULL, NULL, NULL, NULL },
{ NULL, NULL, NULL, NULL, NULL },
{ r_bin_java_methodhandle_cp_new, r_bin_java_default_free, r_bin_java_print_methodhandle_cp_summary, r_bin_java_methodhandle_cp_calc_size, r_bin_java_print_methodhandle_cp_stringify },
{ r_bin_java_methodtype_cp_new, r_bin_java_default_free, r_bin_java_print_methodtype_cp_summary, r_bin_java_methodtype_cp_calc_size, r_bin_java_print_methodtype_cp_stringify },
{ NULL, NULL, NULL, NULL, NULL },
{ r_bin_java_invokedynamic_cp_new, r_bin_java_default_free, r_bin_java_print_invokedynamic_cp_summary, r_bin_java_invokedynamic_cp_calc_size, r_bin_java_print_invokedynamic_cp_stringify },
};
static RBinJavaCPTypeObj R_BIN_JAVA_NULL_TYPE;
static ut8 R_BIN_JAVA_CP_METAS_SZ = 12;
static RBinJavaCPTypeMetas R_BIN_JAVA_CP_METAS[] = {
// Each field has a name pointer and a tag field
{ "NULL", R_BIN_JAVA_CP_NULL, 0, &R_BIN_ALLOCS_CONSTANTS[0] },
{ "Utf8", R_BIN_JAVA_CP_UTF8, 3, &R_BIN_ALLOCS_CONSTANTS[1] }, // 2 bytes = length, N bytes string (containts a pointer in the field)
{ "Unknown", R_BIN_JAVA_CP_UNKNOWN, 0, &R_BIN_ALLOCS_CONSTANTS[2] },
{ "Integer", R_BIN_JAVA_CP_INTEGER, 5, &R_BIN_ALLOCS_CONSTANTS[3] }, // 4 bytes
{ "Float", R_BIN_JAVA_CP_FLOAT, 5, &R_BIN_ALLOCS_CONSTANTS[4] }, // 4 bytes
{ "Long", R_BIN_JAVA_CP_LONG, 9, &R_BIN_ALLOCS_CONSTANTS[5] }, // 4 high 4 low
{ "Double", R_BIN_JAVA_CP_DOUBLE, 9, &R_BIN_ALLOCS_CONSTANTS[6] }, // 4 high 4 low
{ "Class", R_BIN_JAVA_CP_CLASS, 3, &R_BIN_ALLOCS_CONSTANTS[7] }, // 2 name_idx
{ "String", R_BIN_JAVA_CP_STRING, 3, &R_BIN_ALLOCS_CONSTANTS[8] }, // 2 string_idx
{ "FieldRef", R_BIN_JAVA_CP_FIELDREF, 5, &R_BIN_ALLOCS_CONSTANTS[9] }, // 2 class idx, 2 name/type_idx
{ "MethodRef", R_BIN_JAVA_CP_METHODREF, 5, &R_BIN_ALLOCS_CONSTANTS[10] }, // 2 class idx, 2 name/type_idx
{ "InterfaceMethodRef", R_BIN_JAVA_CP_INTERFACEMETHOD_REF, 5, &R_BIN_ALLOCS_CONSTANTS[11] }, // 2 class idx, 2 name/type_idx
{ "NameAndType", R_BIN_JAVA_CP_NAMEANDTYPE, 5, &R_BIN_ALLOCS_CONSTANTS[12] }, // 4 high 4 low
{ "Unknown", R_BIN_JAVA_CP_UNKNOWN, 0, &R_BIN_ALLOCS_CONSTANTS[2] },
{ "Unknown", R_BIN_JAVA_CP_UNKNOWN, 0, &R_BIN_ALLOCS_CONSTANTS[2] },
{ "MethodHandle", R_BIN_JAVA_CP_METHODHANDLE, 4, &R_BIN_ALLOCS_CONSTANTS[15] }, // 4 high 4 low
{ "MethodType", R_BIN_JAVA_CP_METHODTYPE, 3, &R_BIN_ALLOCS_CONSTANTS[16] }, // 4 high 4 low
{ "Unknown", R_BIN_JAVA_CP_UNKNOWN, 0, &R_BIN_ALLOCS_CONSTANTS[2] },
{ "InvokeDynamic", R_BIN_JAVA_CP_INVOKEDYNAMIC, 5, &R_BIN_ALLOCS_CONSTANTS[18] }, // 4 high 4 low
};
static RBinJavaAttrInfoObjectAllocs RBIN_JAVA_ATTRS_ALLOCS[] = {
{ r_bin_java_annotation_default_attr_new, r_bin_java_annotation_default_attr_free, r_bin_java_print_annotation_default_attr_summary, r_bin_java_annotation_default_attr_calc_size },
{ r_bin_java_bootstrap_methods_attr_new, r_bin_java_bootstrap_methods_attr_free, r_bin_java_print_bootstrap_methods_attr_summary, r_bin_java_bootstrap_methods_attr_calc_size },
{ r_bin_java_code_attr_new, r_bin_java_code_attr_free, r_bin_java_print_code_attr_summary, r_bin_java_code_attr_calc_size },
{ r_bin_java_constant_value_attr_new, r_bin_java_constant_value_attr_free, r_bin_java_print_constant_value_attr_summary, r_bin_java_constant_value_attr_calc_size },
{ r_bin_java_deprecated_attr_new, r_bin_java_deprecated_attr_free, r_bin_java_print_deprecated_attr_summary, r_bin_java_deprecated_attr_calc_size },
{ r_bin_java_enclosing_methods_attr_new, r_bin_java_enclosing_methods_attr_free, r_bin_java_print_enclosing_methods_attr_summary, r_bin_java_enclosing_methods_attr_calc_size },
{ r_bin_java_exceptions_attr_new, r_bin_java_exceptions_attr_free, r_bin_java_print_exceptions_attr_summary, r_bin_java_exceptions_attr_calc_size },
{ r_bin_java_inner_classes_attr_new, r_bin_java_inner_classes_attr_free, r_bin_java_print_inner_classes_attr_summary, r_bin_java_inner_classes_attr_calc_size },
{ r_bin_java_line_number_table_attr_new, r_bin_java_line_number_table_attr_free, r_bin_java_print_line_number_table_attr_summary, r_bin_java_line_number_table_attr_calc_size },
{ r_bin_java_local_variable_table_attr_new, r_bin_java_local_variable_table_attr_free, r_bin_java_print_local_variable_table_attr_summary, r_bin_java_local_variable_table_attr_calc_size },
{ r_bin_java_local_variable_type_table_attr_new, r_bin_java_local_variable_type_table_attr_free, r_bin_java_print_local_variable_type_table_attr_summary, r_bin_java_local_variable_type_table_attr_calc_size },
{ r_bin_java_rti_annotations_attr_new, r_bin_java_rti_annotations_attr_free, r_bin_java_print_rti_annotations_attr_summary, r_bin_java_rti_annotations_attr_calc_size },
{ r_bin_java_rtip_annotations_attr_new, r_bin_java_rtip_annotations_attr_free, r_bin_java_print_rtip_annotations_attr_summary, r_bin_java_rtip_annotations_attr_calc_size },
{ r_bin_java_rtv_annotations_attr_new, r_bin_java_rtv_annotations_attr_free, r_bin_java_print_rtv_annotations_attr_summary, r_bin_java_rtv_annotations_attr_calc_size },
{ r_bin_java_rtvp_annotations_attr_new, r_bin_java_rtvp_annotations_attr_free, r_bin_java_print_rtvp_annotations_attr_summary, r_bin_java_rtvp_annotations_attr_calc_size },
{ r_bin_java_signature_attr_new, r_bin_java_signature_attr_free, r_bin_java_print_signature_attr_summary, r_bin_java_signature_attr_calc_size },
{ r_bin_java_source_debug_attr_new, r_bin_java_source_debug_attr_free, r_bin_java_print_source_debug_attr_summary, r_bin_java_source_debug_attr_calc_size },
{ r_bin_java_source_code_file_attr_new, r_bin_java_source_code_file_attr_free, r_bin_java_print_source_code_file_attr_summary, r_bin_java_source_code_file_attr_calc_size },
{ r_bin_java_stack_map_table_attr_new, r_bin_java_stack_map_table_attr_free, r_bin_java_print_stack_map_table_attr_summary, r_bin_java_stack_map_table_attr_calc_size },
{ r_bin_java_synthetic_attr_new, r_bin_java_synthetic_attr_free, r_bin_java_print_synthetic_attr_summary, r_bin_java_synthetic_attr_calc_size },
{ r_bin_java_unknown_attr_new, r_bin_java_unknown_attr_free, r_bin_java_print_unknown_attr_summary, r_bin_java_unknown_attr_calc_size }
};
// R_API ut32 RBIN_JAVA_ATTRS_METAS_SZ = 21;
static ut32 RBIN_JAVA_ATTRS_METAS_SZ = 20;
static RBinJavaAttrMetas RBIN_JAVA_ATTRS_METAS[] = {
{ "AnnotationDefault", R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[0] },
{ "BootstrapMethods", R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[1] },
{ "Code", R_BIN_JAVA_ATTR_TYPE_CODE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[2] },
{ "ConstantValue", R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[3] },
{ "Deperecated", R_BIN_JAVA_ATTR_TYPE_DEPRECATED_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[4] },
{ "EnclosingMethod", R_BIN_JAVA_ATTR_TYPE_ENCLOSING_METHOD_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[5] },
{ "Exceptions", R_BIN_JAVA_ATTR_TYPE_EXCEPTIONS_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[6] },
{ "InnerClasses", R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[7] },
{ "LineNumberTable", R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[8] },
{ "LocalVariableTable", R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TABLE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[9] },
{ "LocalVariableTypeTable", R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TYPE_TABLE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[10] },
{ "RuntimeInvisibleAnnotations", R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[11] },
{ "RuntimeInvisibleParameterAnnotations", R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATION_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[12] },
{ "RuntimeVisibleAnnotations", R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[13] },
{ "RuntimeVisibleParameterAnnotations", R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_PARAMETER_ANNOTATION_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[14] },
{ "Signature", R_BIN_JAVA_ATTR_TYPE_SIGNATURE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[15] },
{ "SourceDebugExtension", R_BIN_JAVA_ATTR_TYPE_SOURCE_DEBUG_EXTENTSION_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[16] },
{ "SourceFile", R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[17] },
{ "StackMapTable", R_BIN_JAVA_ATTR_TYPE_STACK_MAP_TABLE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[18] },
// { "StackMap", R_BIN_JAVA_ATTR_TYPE_STACK_MAP_TABLE_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[18]},
{ "Synthetic", R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[19] },
{ "Unknown", R_BIN_JAVA_ATTR_TYPE_UNKNOWN_ATTR, &RBIN_JAVA_ATTRS_ALLOCS[20] }
};
R_API void r_bin_java_reset_bin_info(RBinJavaObj *bin) {
free (bin->cf2.flags_str);
free (bin->cf2.this_class_name);
r_list_free (bin->imports_list);
r_list_free (bin->methods_list);
r_list_free (bin->fields_list);
r_list_free (bin->attrs_list);
r_list_free (bin->cp_list);
r_list_free (bin->interfaces_list);
memset (bin, 0, sizeof (RBinJavaObj));
bin->cf2.flags_str = strdup ("unknown");
bin->cf2.this_class_name = strdup ("unknown");
bin->imports_list = r_list_newf (free);
bin->methods_list = r_list_newf (r_bin_java_fmtype_free);
bin->fields_list = r_list_newf (r_bin_java_fmtype_free);
bin->attrs_list = r_list_newf (r_bin_java_attribute_free);
bin->cp_list = r_list_newf (r_bin_java_constant_pool);
bin->interfaces_list = r_list_newf (r_bin_java_interface_free);
}
R_API char *r_bin_java_unmangle_method(const char *flags, const char *name, const char *params, const char *r_value) {
RList *the_list = params ? r_bin_java_extract_type_values (params) : r_list_new ();
RListIter *iter = NULL;
// second case removes leading space if no flags are given
const char *fmt = flags ? "%s %s %s (%s)" : "%s%s %s (%s)";
char *str = NULL, *f_val_str = NULL, *r_val_str = NULL, *prototype = NULL, *p_val_str = NULL;
ut32 params_idx = 0, params_len = 0, prototype_len = 0;
if (!extract_type_value (r_value, &r_val_str)) {
r_list_free (the_list);
return NULL;
}
if (!r_val_str) {
r_val_str = strdup ("UNKNOWN");
}
f_val_str = strdup (flags ? flags : "");
params_idx = 0;
r_list_foreach (the_list, iter, str) {
params_len += strlen (str);
if (params_idx > 0) {
params_len += 2;
}
params_idx++;
}
if (params_len > 0) {
ut32 offset = 0;
params_len += 1;
p_val_str = malloc (params_len);
params_idx = 0;
r_list_foreach (the_list, iter, str) {
if (offset != 0) {
offset += snprintf (p_val_str + offset, params_len - offset, ", %s", str);
} else {
offset += snprintf (p_val_str + offset, params_len - offset, "%s", str);
}
}
} else {
p_val_str = strdup ("");
}
prototype_len += (flags ? strlen (flags) + 1 : 0); // space vs no space
prototype_len += strlen (name) + 1; // name + space
prototype_len += strlen (r_val_str) + 1; // r_value + space
prototype_len += strlen (p_val_str) + 3; // space + l_paren + params + r_paren
prototype_len += 1; // null
prototype = malloc (prototype_len);
/// TODO enable this function and start using it to demangle strings
snprintf (prototype, prototype_len, fmt, f_val_str, r_val_str, name, p_val_str);
free (f_val_str);
free (r_val_str);
free (p_val_str);
r_list_free (the_list);
return prototype;
}
R_API char *r_bin_java_unmangle(const char *flags, const char *name, const char *descriptor) {
ut32 l_paren_pos = -1, r_paren_pos = -1;
char *result = NULL;
ut32 desc_len = descriptor && *descriptor ? strlen (descriptor) : 0,
name_len = name && *name ? strlen (name) : 0,
flags_len = flags && *flags ? strlen (flags) : 0,
i = 0;
if (desc_len == 0 || name == 0) {
return NULL;
}
for (i = 0; i < desc_len; i++) {
if (descriptor[i] == '(') {
l_paren_pos = i;
} else if (l_paren_pos != (ut32) - 1 && descriptor[i] == ')') {
r_paren_pos = i;
break;
}
}
// handle field case;
if (l_paren_pos == (ut32) - 1 && r_paren_pos == (ut32) - 1) {
char *unmangle_field_desc = NULL;
ut32 len = extract_type_value (descriptor, &unmangle_field_desc);
if (len == 0) {
eprintf ("Warning: attempting to unmangle invalid type descriptor.\n");
free (unmangle_field_desc);
return result;
}
if (flags_len > 0) {
len += (flags_len + name_len + 5); // space and null
result = malloc (len);
snprintf (result, len, "%s %s %s", flags, unmangle_field_desc, name);
} else {
len += (name_len + 5); // space and null
result = malloc (len);
snprintf (result, len, "%s %s", unmangle_field_desc, name);
}
free (unmangle_field_desc);
} else if (l_paren_pos != (ut32) - 1 &&
r_paren_pos != (ut32) - 1 &&
l_paren_pos < r_paren_pos) {
// params_len account for l_paren + 1 and null
ut32 params_len = r_paren_pos - (l_paren_pos + 1) != 0 ? r_paren_pos - (l_paren_pos + 1) + 1 : 0;
char *params = params_len ? malloc (params_len) : NULL;
const char *rvalue = descriptor + r_paren_pos + 1;
if (params) {
snprintf (params, params_len, "%s", descriptor + l_paren_pos + 1);
}
result = r_bin_java_unmangle_method (flags, name, params, rvalue);
free (params);
}
return result;
}
R_API DsoJsonObj *r_bin_java_get_bin_obj_json(RBinJavaObj *bin) {
DsoJsonObj *imports_list = r_bin_java_get_import_json_definitions (bin);
DsoJsonObj *fields_list = r_bin_java_get_field_json_definitions (bin);
DsoJsonObj *methods_list = r_bin_java_get_method_json_definitions (bin);
// interfaces_list = r_bin_java_get_interface_json_definitions (bin);
DsoJsonObj *class_dict = r_bin_java_get_class_info_json (bin);
char *res = dso_json_obj_to_str (methods_list);
// eprintf ("Resulting methods json: \n%s\n", res);
free (res);
dso_json_dict_insert_str_key_obj (class_dict, "methods", methods_list);
// dso_json_list_free (methods_list);
dso_json_obj_del (methods_list);
res = dso_json_obj_to_str (fields_list);
// eprintf ("Resulting fields json: \n%s\n", res);
free (res);
dso_json_dict_insert_str_key_obj (class_dict, "fields", fields_list);
// dso_json_list_free (fields_list);
dso_json_obj_del (fields_list);
res = dso_json_obj_to_str (imports_list);
// eprintf ("Resulting imports json: \n%s\n", res);
free (res);
dso_json_dict_insert_str_key_obj (class_dict, "imports", imports_list);
// dso_json_list_free (imports_list);
dso_json_obj_del (imports_list);
// res = dso_json_obj_to_str (interfaces_list);
// eprintf ("Resulting interfaces json: \n%s\n", res);
// free (res);
// dso_json_dict_insert_str_key_obj (class_dict, "interfaces", interfaces_list);
res = dso_json_obj_to_str (class_dict);
// eprintf ("Resulting class info json: \n%s\n", res);
free (res);
// dso_json_obj_del (class_dict);
return class_dict;
}
R_API DsoJsonObj *r_bin_java_get_import_json_definitions(RBinJavaObj *bin) {
RList *the_list;
DsoJsonObj *json_list = dso_json_list_new ();
RListIter *iter = NULL;
char *new_str;
if (!bin || !(the_list = r_bin_java_get_lib_names (bin))) {
return json_list;
}
r_list_foreach (the_list, iter, new_str) {
char *tmp = new_str;
// eprintf ("Processing string: %s\n", new_str);
while (*tmp) {
if (*tmp == '/') {
*tmp = '.';
}
tmp++;
}
// eprintf ("adding string: %s\n", new_str);
dso_json_list_append_str (json_list, new_str);
}
r_list_free (the_list);
return json_list;
}
R_API DsoJsonObj *r_bin_java_get_class_info_json(RBinJavaObj *bin) {
RList *classes = r_bin_java_get_classes (bin);
DsoJsonObj *interfaces_list = dso_json_list_new ();
DsoJsonObj *class_info_dict = dso_json_dict_new ();
RBinClass *class_ = r_list_get_n (classes, 0);
if (class_) {
int dummy = 0;
RListIter *iter;
RBinClass *class_v = NULL;
// add access flags like in methods
bool is_public = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_PUBLIC) != 0);
bool is_final = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_FINAL) != 0);
bool is_super = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_SUPER) != 0);
bool is_interface = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_INTERFACE) != 0);
bool is_abstract = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_ABSTRACT) != 0);
bool is_synthetic = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_SYNTHETIC) != 0);
bool is_annotation = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_ANNOTATION) != 0);
bool is_enum = ((class_->visibility & R_BIN_JAVA_CLASS_ACC_ENUM) != 0);
dso_json_dict_insert_str_key_num (class_info_dict, "access_flags", class_->visibility);
dso_json_dict_insert_str_key_num (class_info_dict, "is_public", is_public);
dso_json_dict_insert_str_key_num (class_info_dict, "is_final", is_final);
dso_json_dict_insert_str_key_num (class_info_dict, "is_super", is_super);
dso_json_dict_insert_str_key_num (class_info_dict, "is_interface", is_interface);
dso_json_dict_insert_str_key_num (class_info_dict, "is_abstract", is_abstract);
dso_json_dict_insert_str_key_num (class_info_dict, "is_synthetic", is_synthetic);
dso_json_dict_insert_str_key_num (class_info_dict, "is_annotation", is_annotation);
dso_json_dict_insert_str_key_num (class_info_dict, "is_enum", is_enum);
dso_json_dict_insert_str_key_str (class_info_dict, "name", class_->name);
if (!class_->super) {
DsoJsonObj *str = dso_json_str_new ();
dso_json_dict_insert_str_key_obj (class_info_dict, "super", str);
dso_json_str_free (str);
} else {
dso_json_dict_insert_str_key_str (class_info_dict, "super", class_->super);
}
r_list_foreach (classes, iter, class_v) {
if (!dummy) {
dummy++;
continue;
}
// enumerate all interface classes and append them to the interfaces
if ((class_v->visibility & R_BIN_JAVA_CLASS_ACC_INTERFACE) != 0) {
dso_json_list_append_str (interfaces_list, class_v->name);
}
}
}
dso_json_dict_insert_str_key_obj (class_info_dict, "interfaces", interfaces_list);
r_list_free (classes);
// dso_json_list_free (interfaces_list);
dso_json_obj_del (interfaces_list);
return class_info_dict;
}
R_API DsoJsonObj *r_bin_java_get_interface_json_definitions(RBinJavaObj *bin) {
RList *the_list;
DsoJsonObj *json_list = dso_json_list_new ();
RListIter *iter = NULL;
char *new_str;
if (!bin || !(the_list = r_bin_java_get_interface_names (bin))) {
return json_list;
}
r_list_foreach (the_list, iter, new_str) {
char *tmp = new_str;
// eprintf ("Processing string: %s\n", new_str);
while (*tmp) {
if (*tmp == '/') {
*tmp = '.';
}
tmp++;
}
// eprintf ("adding string: %s\n", new_str);
dso_json_list_append_str (json_list, new_str);
}
r_list_free (the_list);
return json_list;
}
R_API DsoJsonObj *r_bin_java_get_method_json_definitions(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RListIter *iter = NULL;
DsoJsonObj *json_list = dso_json_list_new ();
if (!bin) {
return json_list;
}
r_list_foreach (bin->methods_list, iter, fm_type) {
DsoJsonObj *method_proto = r_bin_java_get_method_json_definition (bin, fm_type);
// eprintf ("Method json: %s\n", method_proto);
dso_json_list_append (json_list, method_proto);
}
return json_list;
}
R_API DsoJsonObj *r_bin_java_get_field_json_definitions(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RListIter *iter = NULL;
DsoJsonObj *json_list = dso_json_list_new ();
if (!bin) {
return json_list;
}
r_list_foreach (bin->fields_list, iter, fm_type) {
DsoJsonObj *field_proto = r_bin_java_get_field_json_definition (bin, fm_type);
// eprintf ("Field json: %s\n", field_proto);
dso_json_list_append (json_list, field_proto);
}
return json_list;
}
R_API char *r_bin_java_create_method_fq_str(const char *klass, const char *name, const char *signature) {
if (!klass) {
klass = "null_class";
}
if (!name) {
name = "null_name";
}
if (!signature) {
signature = "null_signature";
}
return r_str_newf ("%s.%s.%s", klass, name, signature);
}
R_API char *r_bin_java_create_field_fq_str(const char *klass, const char *name, const char *signature) {
if (!klass) {
klass = "null_class";
}
if (!name) {
name = "null_name";
}
if (!signature) {
signature = "null_signature";
}
return r_str_newf ("%s %s.%s", signature, klass, name);
}
R_API DsoJsonObj *r_bin_java_get_fm_type_definition_json(RBinJavaObj *bin, RBinJavaField *fm_type, int is_method) {
ut64 addr = UT64_MAX;
char *prototype = NULL, *fq_name = NULL;
bool is_native = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_NATIVE) != 0);
bool is_static = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_STATIC) != 0);
bool is_synthetic = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_SYNTHETIC) != 0);
bool is_private = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_PRIVATE) != 0);
bool is_public = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_PUBLIC) != 0);
bool is_protected = ((fm_type->flags & R_BIN_JAVA_METHOD_ACC_PROTECTED) != 0);
bool is_super = ((fm_type->flags & R_BIN_JAVA_CLASS_ACC_SUPER) != 0);
DsoJsonObj *fm_type_dict = dso_json_dict_new ();
dso_json_dict_insert_str_key_num (fm_type_dict, "access_flags", fm_type->flags);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_method", is_method);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_native", is_native);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_synthetic", is_synthetic);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_private", is_private);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_public", is_public);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_static", is_static);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_protected", is_protected);
dso_json_dict_insert_str_key_num (fm_type_dict, "is_super", is_super);
addr = r_bin_java_get_method_code_offset (fm_type);
if (addr == 0) {
addr = fm_type->file_offset;
}
addr += bin->loadaddr;
dso_json_dict_insert_str_key_num (fm_type_dict, "addr", addr);
dso_json_dict_insert_str_key_num (fm_type_dict, "offset", fm_type->file_offset + bin->loadaddr);
dso_json_dict_insert_str_key_str (fm_type_dict, "class_name", fm_type->class_name);
dso_json_dict_insert_str_key_str (fm_type_dict, "signature", fm_type->descriptor);
dso_json_dict_insert_str_key_str (fm_type_dict, "name", fm_type->name);
if (is_method) {
fq_name = r_bin_java_create_method_fq_str (fm_type->class_name, fm_type->name, fm_type->descriptor);
} else {
fq_name = r_bin_java_create_field_fq_str (fm_type->class_name, fm_type->name, fm_type->descriptor);
}
dso_json_dict_insert_str_key_str (fm_type_dict, "fq_name", fq_name);
prototype = r_bin_java_unmangle (fm_type->flags_str, fm_type->name, fm_type->descriptor);
dso_json_dict_insert_str_key_str (fm_type_dict, "prototype", prototype);
free (prototype);
free (fq_name);
return fm_type_dict;
}
R_API char *r_bin_java_get_method_definition(RBinJavaField *fm_type) {
return r_bin_java_unmangle (fm_type->flags_str, fm_type->name, fm_type->descriptor);
}
R_API char *r_bin_java_get_field_definition(RBinJavaField *fm_type) {
return r_bin_java_unmangle (fm_type->flags_str, fm_type->name, fm_type->descriptor);
}
R_API DsoJsonObj *r_bin_java_get_method_json_definition(RBinJavaObj *bin, RBinJavaField *fm_type) {
return r_bin_java_get_fm_type_definition_json (bin, fm_type, 1);
}
R_API DsoJsonObj *r_bin_java_get_field_json_definition(RBinJavaObj *bin, RBinJavaField *fm_type) {
return r_bin_java_get_fm_type_definition_json (bin, fm_type, 0);
}
R_API int r_bin_java_extract_reference_name(const char *input_str, char **ref_str, ut8 array_cnt) {
char *new_str = NULL;
ut32 str_len = array_cnt ? (array_cnt + 1) * 2 : 0;
const char *str_pos = input_str;
int consumed = 0, len = 0;
if (!str_pos || *str_pos != 'L' || !*str_pos) {
return -1;
}
consumed++;
str_pos++;
while (*str_pos && *str_pos != ';') {
str_pos++;
len++;
consumed++;
}
str_pos = input_str + 1;
free (*ref_str);
str_len += len;
*ref_str = malloc (str_len + 1);
new_str = *ref_str;
memcpy (new_str, input_str + 1, str_len);
new_str[str_len] = 0;
while (*new_str) {
if (*new_str == '/') {
*new_str = '.';
}
new_str++;
}
return len + 2;
}
R_API void UNUSED_FUNCTION(r_bin_java_print_prototypes)(RBinJavaObj * bin) {
RList *the_list = r_bin_java_get_method_definitions (bin);
RListIter *iter;
char *str;
r_list_foreach (the_list, iter, str) {
eprintf ("%s;\n", str);
}
r_list_free (the_list);
}
R_API char *get_type_value_str(const char *arg_str, ut8 array_cnt) {
ut32 str_len = array_cnt ? (array_cnt + 1) * 2 + strlen (arg_str) : strlen (arg_str);
char *str = malloc (str_len + 1);
ut32 bytes_written = snprintf (str, str_len + 1, "%s", arg_str);
while (array_cnt > 0) {
bytes_written = snprintf (str + bytes_written, str_len - bytes_written, "[]");
array_cnt--;
}
return str;
}
R_API int extract_type_value(const char *arg_str, char **output) {
ut8 found_one = 0, array_cnt = 0;
ut32 len = 0, consumed = 0;
char *str = NULL;
if (!arg_str || !output) {
return 0;
}
if (output && *output && *output != NULL) {
free (*output);
*output = NULL;
}
while (arg_str && *arg_str && !found_one) {
len = 0;
// handle the end of an object
switch (*arg_str) {
case 'V':
len = 1;
str = get_type_value_str ("void", array_cnt);
break;
case 'J':
len = 1;
str = get_type_value_str ("long", array_cnt);
array_cnt = 0;
break;
case 'I':
len = 1;
str = get_type_value_str ("int", array_cnt);
array_cnt = 0;
break;
case 'D':
len = 1;
str = get_type_value_str ("double", array_cnt);
array_cnt = 0;
break;
case 'F':
len = 1;
str = get_type_value_str ("float", array_cnt);
array_cnt = 0;
break;
case 'B':
len = 1;
str = get_type_value_str ("byte", array_cnt);
array_cnt = 0;
break;
case 'C':
len = 1;
str = get_type_value_str ("char", array_cnt);
array_cnt = 0;
break;
case 'Z':
len = 1;
str = get_type_value_str ("boolean", array_cnt);
array_cnt = 0;
break;
case 'S':
len = 1;
str = get_type_value_str ("short", array_cnt);
array_cnt = 0;
break;
case '[': len = 1; array_cnt++; break;
case 'L':
len = r_bin_java_extract_reference_name (arg_str, &str, array_cnt);
array_cnt = 0;
break;
case '(': len = 1; str = strdup ("("); break;
case ')': len = 1; str = strdup (")"); break;
default:
return 0;
}
if (len < 1) {
break;
}
consumed += len;
arg_str += len;
if (str) {
*output = str;
break;
}
}
return consumed;
}
R_API RList *r_bin_java_extract_type_values(const char *arg_str) {
RList *list_args = r_list_new ();
if (!list_args) {
return NULL;
}
char *str = NULL;
const char *str_cur_pos = NULL;
ut32 len = 0;
if (!arg_str) {
return list_args;
}
str_cur_pos = arg_str;
list_args->free = free;
while (str_cur_pos && *str_cur_pos) {
// handle the end of an object
len = extract_type_value (str_cur_pos, &str);
if (len < 1) {
r_list_free (list_args);
return NULL;
}
str_cur_pos += len;
r_list_append (list_args, str);
str = NULL;
}
return list_args;
}
R_API int r_bin_java_is_fm_type_private(RBinJavaField *fm_type) {
if (fm_type && fm_type->type == R_BIN_JAVA_FIELD_TYPE_METHOD) {
return fm_type->flags & R_BIN_JAVA_METHOD_ACC_PRIVATE;
}
if (fm_type && fm_type->type == R_BIN_JAVA_FIELD_TYPE_FIELD) {
return fm_type->flags & R_BIN_JAVA_FIELD_ACC_PRIVATE;
}
return 0;
}
R_API int r_bin_java_is_fm_type_protected(RBinJavaField *fm_type) {
if (fm_type && fm_type->type == R_BIN_JAVA_FIELD_TYPE_METHOD) {
return fm_type->flags & R_BIN_JAVA_METHOD_ACC_PROTECTED;
}
if (fm_type && fm_type->type == R_BIN_JAVA_FIELD_TYPE_FIELD) {
return fm_type->flags & R_BIN_JAVA_FIELD_ACC_PROTECTED;
}
return 0;
}
R_API RList *r_bin_java_get_args(RBinJavaField *fm_type) {
RList *the_list = r_bin_java_extract_type_values (fm_type->descriptor);
RList *arg_list = r_list_new ();
ut8 in_args = 0;
RListIter *desc_iter;
char *str;
r_list_foreach (the_list, desc_iter, str) {
if (str && *str == '(') {
in_args = 1;
continue;
}
if (str && *str == ')') {
break;
}
if (in_args) {
r_list_append (arg_list, strdup (str));
}
}
r_list_free (the_list);
return arg_list;
}
R_API RList *r_bin_java_get_ret(RBinJavaField *fm_type) {
RList *the_list = r_bin_java_extract_type_values (fm_type->descriptor);
RList *ret_list = r_list_new ();
ut8 in_ret = 0;
RListIter *desc_iter;
char *str;
r_list_foreach (the_list, desc_iter, str) {
if (str && *str != ')') {
in_ret = 0;
}
if (in_ret) {
r_list_append (ret_list, strdup (str));
}
}
r_list_free (the_list);
return ret_list;
}
R_API char *r_bin_java_get_this_class_name(RBinJavaObj *bin) {
return (bin->cf2.this_class_name ? strdup (bin->cf2.this_class_name) : strdup ("unknown"));
}
R_API ut16 calculate_access_value(const char *access_flags_str, RBinJavaAccessFlags *access_flags) {
ut16 result = 0;
ut16 size = strlen (access_flags_str) + 1;
char *p_flags, *my_flags = malloc (size);
RBinJavaAccessFlags *iter = NULL;
if (size < 5 || !my_flags) {
free (my_flags);
return result;
}
memcpy (my_flags, access_flags_str, size);
p_flags = strtok (my_flags, " ");
while (p_flags && access_flags) {
int idx = 0;
do {
iter = &access_flags[idx];
if (!iter || !iter->str) {
continue;
}
if (iter->len > 0 && iter->len != 16) {
if (!strncmp (iter->str, p_flags, iter->len)) {
result |= iter->value;
}
}
idx++;
} while (access_flags[idx].str != NULL);
p_flags = strtok (NULL, " ");
}
free (my_flags);
return result;
}
R_API RList *retrieve_all_access_string_and_value(RBinJavaAccessFlags *access_flags) {
const char *fmt = "%s = 0x%04x";
RList *result = r_list_new ();
if (!result) {
return NULL;
}
result->free = free;
int i = 0;
for (i = 0; access_flags[i].str != NULL; i++) {
char *str = malloc (50);
if (!str) {
r_list_free (result);
return NULL;
}
snprintf (str, 49, fmt, access_flags[i].str, access_flags[i].value);
r_list_append (result, str);
}
return result;
}
R_API char *retrieve_access_string(ut16 flags, RBinJavaAccessFlags *access_flags) {
char *outbuffer = NULL, *cur_pos = NULL;
ut16 i;
ut16 max_str_len = 0;
for (i = 0; access_flags[i].str != NULL; i++) {
if (flags & access_flags[i].value) {
max_str_len += (strlen (access_flags[i].str) + 1);
if (max_str_len < strlen (access_flags[i].str)) {
return NULL;
}
}
}
max_str_len++;
outbuffer = (char *) malloc (max_str_len);
if (outbuffer) {
memset (outbuffer, 0, max_str_len);
cur_pos = outbuffer;
for (i = 0; access_flags[i].str != NULL; i++) {
if (flags & access_flags[i].value) {
ut8 len = strlen (access_flags[i].str);
const char *the_string = access_flags[i].str;
memcpy (cur_pos, the_string, len);
memcpy (cur_pos + len, " ", 1);
cur_pos += len + 1;
}
}
if (cur_pos != outbuffer) {
*(cur_pos - 1) = 0;
}
}
return outbuffer;
}
R_API char *retrieve_method_access_string(ut16 flags) {
return retrieve_access_string (flags, METHOD_ACCESS_FLAGS);
}
R_API char *retrieve_field_access_string(ut16 flags) {
return retrieve_access_string (flags, FIELD_ACCESS_FLAGS);
}
R_API char *retrieve_class_method_access_string(ut16 flags) {
return retrieve_access_string (flags, CLASS_ACCESS_FLAGS);
}
R_API char *r_bin_java_build_obj_key(RBinJavaObj *bin) {
char *jvcname = NULL;
char *cname = r_bin_java_get_this_class_name (bin);
ut32 class_name_len = cname ? strlen (cname) : strlen ("_unknown_");
jvcname = malloc (class_name_len + 8 + 30);
if (cname) {
snprintf (jvcname, class_name_len + 30, "%d.%s.class", bin->id, cname);
free (cname);
} else {
snprintf (jvcname, class_name_len + 30, "%d._unknown_.class", bin->id);
}
return jvcname;
}
R_API int sdb_iterate_build_list(void *user, const char *k, const char *v) {
RList *bin_objs_list = (RList *) user;
size_t value = (size_t) sdb_atoi (v);
RBinJavaObj *bin_obj = NULL;
IFDBG eprintf("Found %s == %"PFMT64x " bin_objs db\n", k, (ut64) value);
if (value != 0 && value != (size_t) -1) {
bin_obj = (RBinJavaObj *) value;
r_list_append (bin_objs_list, bin_obj);
}
return true;
}
R_API RBinJavaCPTypeObj *r_bin_java_get_java_null_cp() {
if (R_BIN_JAVA_NULL_TYPE_INITTED) {
return &R_BIN_JAVA_NULL_TYPE;
}
memset (&R_BIN_JAVA_NULL_TYPE, 0, sizeof (R_BIN_JAVA_NULL_TYPE));
R_BIN_JAVA_NULL_TYPE.metas = R_NEW0 (RBinJavaMetaInfo);
if (!R_BIN_JAVA_NULL_TYPE.metas) {
return NULL;
}
memset (R_BIN_JAVA_NULL_TYPE.metas, 0, sizeof (RBinJavaMetaInfo));
R_BIN_JAVA_NULL_TYPE.metas->type_info = &R_BIN_JAVA_CP_METAS[0];
R_BIN_JAVA_NULL_TYPE.metas->ord = 0;
R_BIN_JAVA_NULL_TYPE.file_offset = 0;
R_BIN_JAVA_NULL_TYPE_INITTED = true;
return &R_BIN_JAVA_NULL_TYPE;
}
R_API RBinJavaElementValueMetas *r_bin_java_get_ev_meta_from_tag(ut8 tag) {
ut16 i = 0;
RBinJavaElementValueMetas *res = &R_BIN_JAVA_ELEMENT_VALUE_METAS[13];
for (i = 0; i < R_BIN_JAVA_ELEMENT_VALUE_METAS_SZ; i++) {
if (tag == R_BIN_JAVA_ELEMENT_VALUE_METAS[i].tag) {
res = &R_BIN_JAVA_ELEMENT_VALUE_METAS[i];
break;
}
}
return res;
}
R_API ut8 r_bin_java_quick_check(ut8 expected_tag, ut8 actual_tag, ut32 actual_len, const char *name) {
ut8 res = 0;
if (expected_tag > R_BIN_JAVA_CP_METAS_SZ) {
eprintf ("Invalid tag '%d' expected 0x%02x for %s.\n", actual_tag, expected_tag, name);
res = 1;
} else if (expected_tag != actual_tag) {
eprintf ("Invalid tag '%d' expected 0x%02x for %s.\n", actual_tag, expected_tag, name);
res = 1;
} else if (actual_len < R_BIN_JAVA_CP_METAS[expected_tag].len) {
eprintf ("Unable to parse '%d' expected sz=0x%02x got 0x%02x for %s.\n",
actual_tag, R_BIN_JAVA_CP_METAS[expected_tag].len, actual_len, name);
res = 2;
}
return res;
}
R_API ut64 r_bin_java_raw_to_long(const ut8 *raw, ut64 offset) {
return R_BIN_JAVA_LONG (raw, offset);
}
// yanked from careercup, because i am lazy:
// 1) dont want to figure out how make radare use math library
// 2) dont feel like figuring it out when google does it in O(1).
R_API double my_pow(ut64 base, int exp) {
ut8 flag = 0;
ut64 res = 1;
if (exp < 0) {
flag = 1;
exp *= -1;
}
while (exp) {
if (exp & 1) {
res *= base;
}
exp >>= 1;
base *= base;
IFDBG eprintf("Result: %"PFMT64d ", base: %"PFMT64d ", exp: %d\n", res, base, exp);
}
if (flag == 0) {
return 1.0 * res;
}
return (1.0 / res);
}
R_API double r_bin_java_raw_to_double(const ut8 *raw, ut64 offset) {
ut64 bits = R_BIN_JAVA_LONG (raw, offset);
int s = ((bits >> 63) == 0) ? 1 : -1;
int e = (int) ((bits >> 52) & 0x7ffL);
long m = (e == 0) ?
(bits & 0xfffffffffffffLL) << 1 :
(bits & 0xfffffffffffffLL) | 0x10000000000000LL;
double res = 0.0;
IFDBG eprintf("Convert Long to Double: %08"PFMT64x "\n", bits);
if (bits == 0x7ff0000000000000LL) {
return INFINITY;
}
if (bits == 0xfff0000000000000LL) {
return -INFINITY;
}
if (0x7ff0000000000001LL <= bits && bits <= 0x7fffffffffffffffLL) {
return NAN;
}
if (0xfff0000000000001LL <= bits && bits <= 0xffffffffffffffffLL) {
return NAN;
}
res = s * m * my_pow (2, e - 1075);// XXXX TODO Get double to work correctly here
IFDBG eprintf(" High-bytes = %02x %02x %02x %02x\n", raw[0], raw[1], raw[2], raw[3]);
IFDBG eprintf(" Low-bytes = %02x %02x %02x %02x\n", raw[4], raw[5], raw[6], raw[7]);
IFDBG eprintf("Convert Long to Double s: %d, m: 0x%08lx, e: 0x%08x, res: %f\n", s, m, e, res);
return res;
}
R_API RBinJavaField *r_bin_java_read_next_method(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
ut32 i, idx;
const ut8 *f_buf = buf + offset;
ut64 adv = 0;
RBinJavaCPTypeObj *item = NULL;
RBinJavaField *method;
if (bin == NULL) {
return NULL;
}
if (offset + 8 >= len) {
return NULL;
}
method = (RBinJavaField *) R_NEW0 (RBinJavaField);
if (method == NULL) {
eprintf ("Unable to allocate memory for method information\n");
return NULL;
}
method->metas = (RBinJavaMetaInfo *) R_NEW0 (RBinJavaMetaInfo);
if (method->metas == NULL) {
eprintf ("Unable to allocate memory for meta information\n");
free (method);
return NULL;
}
method->file_offset = offset;
method->flags = R_BIN_JAVA_USHORT (f_buf, 0);
method->flags_str = retrieve_method_access_string (method->flags);
// need to subtract 1 for the idx
method->name_idx = R_BIN_JAVA_USHORT (f_buf, 2);
method->descriptor_idx = R_BIN_JAVA_USHORT (f_buf, 4);
method->attr_count = R_BIN_JAVA_USHORT (f_buf, 6);
method->attributes = r_list_newf (r_bin_java_attribute_free);
method->type = R_BIN_JAVA_FIELD_TYPE_METHOD;
method->metas->ord = bin->method_idx;
adv += 8;
idx = method->name_idx;
item = r_bin_java_get_item_from_bin_cp_list (bin, idx);
method->name = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) (method->name_idx));
IFDBG eprintf("Method name_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, method->name);
if (method->name == NULL) {
method->name = (char *) malloc (21);
snprintf ((char *) method->name, 20, "sym.method_%08x", method->metas->ord);
IFDBG eprintf("r_bin_java_read_next_method: Unable to find the name for 0x%02x index.\n", method->name_idx);
}
idx = method->descriptor_idx;
item = r_bin_java_get_item_from_bin_cp_list (bin, idx);
method->descriptor = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) method->descriptor_idx);
IFDBG eprintf("Method descriptor_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, method->descriptor);
if (method->descriptor == NULL) {
method->descriptor = r_str_dup (NULL, "NULL");
IFDBG eprintf("r_bin_java_read_next_method: Unable to find the descriptor for 0x%02x index.\n", method->descriptor_idx);
}
IFDBG eprintf("Looking for a NameAndType CP with name_idx: %d descriptor_idx: %d\n", method->name_idx, method->descriptor_idx);
method->field_ref_cp_obj = r_bin_java_find_cp_ref_info_from_name_and_type (bin, method->name_idx, method->descriptor_idx);
if (method->field_ref_cp_obj) {
IFDBG eprintf("Found the obj.\n");
item = r_bin_java_get_item_from_bin_cp_list (bin, method->field_ref_cp_obj->info.cp_method.class_idx);
IFDBG eprintf("Method class reference value: %d, which is: ord: %d, name: %s\n", method->field_ref_cp_obj->info.cp_method.class_idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name);
method->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, item);
IFDBG eprintf("Method requesting ref_cp_obj the following which is: ord: %d, name: %s\n", method->field_ref_cp_obj->metas->ord, ((RBinJavaCPTypeMetas *)method->field_ref_cp_obj->metas->type_info)->name);
IFDBG eprintf("MethodRef class name resolves to: %s\n", method->class_name);
if (method->class_name == NULL) {
method->class_name = r_str_dup (NULL, "NULL");
}
} else {
// XXX - default to this class?
method->field_ref_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, bin->cf2.this_class);
method->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, method->field_ref_cp_obj);
}
IFDBG eprintf("Parsing %s(%s)\n", method->name, method->descriptor);
if (method->attr_count > 0) {
method->attr_offset = adv + offset;
RBinJavaAttrInfo *attr = NULL;
for (i = 0; i < method->attr_count; i++) {
attr = r_bin_java_read_next_attr (bin, adv + offset, buf, len);
if (!attr) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Method Attribute: %d.\n", i);
break;
}
if ((r_bin_java_get_attr_type_by_name (attr->name))->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR) {
// This is necessary for determing the appropriate number of bytes when readin
// uoffset, ustack, ulocalvar values
bin->cur_method_code_length = attr->info.code_attr.code_length;
bin->offset_sz = 2;// (attr->info.code_attr.code_length > 65535) ? 4 : 2;
bin->ustack_sz = 2;// (attr->info.code_attr.max_stack > 65535) ? 4 : 2;
bin->ulocalvar_sz = 2;// (attr->info.code_attr.max_locals > 65535) ? 4 : 2;
}
IFDBG eprintf("Parsing @ 0x%"PFMT64x " (%s) = 0x%"PFMT64x " bytes\n", attr->file_offset, attr->name, attr->size);
r_list_append (method->attributes, attr);
adv += attr->size;
if (adv + offset >= len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Method Attribute: %d.\n", i);
break;
}
}
}
method->size = adv;
// reset after parsing the method attributes
IFDBG eprintf("Parsing @ 0x%"PFMT64x " %s(%s) = 0x%"PFMT64x " bytes\n", method->file_offset, method->name, method->descriptor, method->size);
return method;
}
R_API RBinJavaField *r_bin_java_read_next_field(RBinJavaObj *bin, const ut64 offset, const ut8 *buffer, const ut64 len) {
RBinJavaAttrInfo *attr;
ut32 i, idx;
ut8 buf[8];
RBinJavaCPTypeObj *item = NULL;
const ut8 *f_buf = buffer + offset;
ut64 adv = 0;
RBinJavaField *field;
if (bin == NULL) {
return NULL;
}
if (offset + 8 >= len) {
return NULL;
}
field = (RBinJavaField *) R_NEW0 (RBinJavaField);
if (field == NULL) {
eprintf ("Unable to allocate memory for field information\n");
return NULL;
}
field->metas = (RBinJavaMetaInfo *) R_NEW0 (RBinJavaMetaInfo);
if (field->metas == NULL) {
eprintf ("Unable to allocate memory for meta information\n");
free (field);
return NULL;
}
memcpy (buf, f_buf, 8);
field->file_offset = offset;
field->flags = R_BIN_JAVA_USHORT (buf, 0);
field->flags_str = retrieve_field_access_string (field->flags);
field->name_idx = R_BIN_JAVA_USHORT (buf, 2);
field->descriptor_idx = R_BIN_JAVA_USHORT (buf, 4);
field->attr_count = R_BIN_JAVA_USHORT (buf, 6);
field->attributes = r_list_newf (r_bin_java_attribute_free);
field->type = R_BIN_JAVA_FIELD_TYPE_FIELD;
adv += 8;
field->metas->ord = bin->field_idx;
idx = field->name_idx;
item = r_bin_java_get_item_from_bin_cp_list (bin, idx);
field->name = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) (field->name_idx));
IFDBG eprintf("Field name_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, field->name);
if (field->name == NULL) {
field->name = (char *) malloc (21);
snprintf ((char *) field->name, 20, "sym.field_%08x", field->metas->ord);
IFDBG eprintf("r_bin_java_read_next_field: Unable to find the name for 0x%02x index.\n", field->name_idx);
}
idx = field->descriptor_idx;
item = r_bin_java_get_item_from_bin_cp_list (bin, idx);
field->descriptor = r_bin_java_get_utf8_from_bin_cp_list (bin, (ut32) field->descriptor_idx);
IFDBG eprintf("Field descriptor_idx: %d, which is: ord: %d, name: %s, value: %s\n", idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name, field->descriptor);
if (field->descriptor == NULL) {
field->descriptor = r_str_dup (NULL, "NULL");
IFDBG eprintf("r_bin_java_read_next_field: Unable to find the descriptor for 0x%02x index.\n", field->descriptor_idx);
}
IFDBG eprintf("Looking for a NameAndType CP with name_idx: %d descriptor_idx: %d\n", field->name_idx, field->descriptor_idx);
field->field_ref_cp_obj = r_bin_java_find_cp_ref_info_from_name_and_type (bin, field->name_idx, field->descriptor_idx);
if (field->field_ref_cp_obj) {
IFDBG eprintf("Found the obj.\n");
item = r_bin_java_get_item_from_bin_cp_list (bin, field->field_ref_cp_obj->info.cp_field.class_idx);
IFDBG eprintf("Field class reference value: %d, which is: ord: %d, name: %s\n", field->field_ref_cp_obj->info.cp_field.class_idx, item->metas->ord, ((RBinJavaCPTypeMetas *)item->metas->type_info)->name);
field->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, item);
IFDBG eprintf("Field requesting ref_cp_obj the following which is: ord: %d, name: %s\n", field->field_ref_cp_obj->metas->ord, ((RBinJavaCPTypeMetas *)field->field_ref_cp_obj->metas->type_info)->name);
IFDBG eprintf("FieldRef class name resolves to: %s\n", field->class_name);
if (field->class_name == NULL) {
field->class_name = r_str_dup (NULL, "NULL");
}
} else {
// XXX - default to this class?
field->field_ref_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, bin->cf2.this_class);
field->class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, field->field_ref_cp_obj);
}
IFDBG eprintf("Parsing %s(%s)", field->name, field->descriptor);
if (field->attr_count > 0) {
field->attr_offset = adv + offset;
for (i = 0; i < field->attr_count && offset + adv < len; i++) {
attr = r_bin_java_read_next_attr (bin, offset + adv, buffer, len);
if (!attr) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Field Attribute: %d.\n", i);
return NULL;
}
if ((r_bin_java_get_attr_type_by_name (attr->name))->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR) {
// This is necessary for determing the appropriate number of bytes when readin
// uoffset, ustack, ulocalvar values
bin->cur_method_code_length = attr->info.code_attr.code_length;
bin->offset_sz = 2;// (attr->info.code_attr.code_length > 65535) ? 4 : 2;
bin->ustack_sz = 2;// (attr->info.code_attr.max_stack > 65535) ? 4 : 2;
bin->ulocalvar_sz = 2;// (attr->info.code_attr.max_locals > 65535) ? 4 : 2;
}
r_list_append (field->attributes, attr);
adv += attr->size;
if (adv + offset >= len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Field Attribute: %d.\n", i);
return NULL;
}
}
}
field->size = adv;
return field;
}
R_API RBinJavaCPTypeObj *r_bin_java_clone_cp_idx(RBinJavaObj *bin, ut32 idx) {
RBinJavaCPTypeObj *obj = NULL;
if (bin) {
obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
}
return r_bin_java_clone_cp_item (obj);
}
R_API RBinJavaCPTypeObj *r_bin_java_clone_cp_item(RBinJavaCPTypeObj *obj) {
RBinJavaCPTypeObj *clone_obj = NULL;
if (obj == NULL) {
return clone_obj;
}
clone_obj = R_NEW0 (RBinJavaCPTypeObj);
if (clone_obj) {
memcpy (clone_obj, obj, sizeof (RBinJavaCPTypeObj));
clone_obj->metas = (RBinJavaMetaInfo *) R_NEW0 (RBinJavaMetaInfo);
clone_obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[clone_obj->tag];
clone_obj->name = strdup (obj->name? obj->name: "unk");
if (obj->tag == R_BIN_JAVA_CP_UTF8) {
clone_obj->info.cp_utf8.bytes = (ut8 *) malloc (obj->info.cp_utf8.length + 1);
if (clone_obj->info.cp_utf8.bytes) {
memcpy (clone_obj->info.cp_utf8.bytes, obj->info.cp_utf8.bytes, clone_obj->info.cp_utf8.length);
} else {
// TODO: eprintf allocation error
}
}
}
return clone_obj;
}
R_API RBinJavaCPTypeObj *r_bin_java_read_next_constant_pool_item(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, ut64 len) {
RBinJavaCPTypeMetas *java_constant_info = NULL;
ut8 tag = 0;
ut64 buf_sz = 0;
ut8 *cp_buf = NULL;
ut32 str_len = 0;
RBinJavaCPTypeObj *java_obj = NULL;
tag = buf[offset];
if (tag > R_BIN_JAVA_CP_METAS_SZ) {
eprintf ("Invalid tag '%d' at offset 0x%08"PFMT64x "\n", tag, (ut64) offset);
return NULL;
#if 0
java_obj = r_bin_java_unknown_cp_new (bin, &tag, 1);
if (java_obj != NULL && java_obj->metas != NULL) {
java_obj->file_offset = offset;
java_obj->loadaddr = bin->loadaddr;
}
return NULL; // early error to avoid future overflows
// return java_obj;
#endif
}
java_constant_info = &R_BIN_JAVA_CP_METAS[tag];
if (java_constant_info->tag == 0 || java_constant_info->tag == 2) {
return java_obj;
}
buf_sz += java_constant_info->len;
if (java_constant_info->tag == 1) {
if (offset + 32 < len) {
str_len = R_BIN_JAVA_USHORT (buf, offset + 1);
buf_sz += str_len;
} else {
return NULL;
}
}
cp_buf = calloc (buf_sz, 1);
if (!cp_buf) {
return java_obj;
}
if (offset + buf_sz < len) {
memcpy (cp_buf, (ut8 *) buf + offset, buf_sz);
IFDBG eprintf("Parsed the tag '%d':%s and create object from offset 0x%08"PFMT64x ".\n", tag, R_BIN_JAVA_CP_METAS[tag].name, offset);
java_obj = (*java_constant_info->allocs->new_obj)(bin, cp_buf, buf_sz);
if (java_obj != NULL && java_obj->metas != NULL) {
java_obj->file_offset = offset;
// IFDBG eprintf ("java_obj->file_offset = 0x%08"PFMT64x".\n",java_obj->file_offset);
} else if (!java_obj) {
eprintf ("Unable to parse the tag '%d' and create valid object.\n", tag);
} else if (!java_obj->metas) {
eprintf ("Unable to parse the tag '%d' and create valid object.\n", tag);
} else {
eprintf ("Failed to set the java_obj->metas-file_offset for '%d' offset is(0x%08"PFMT64x ").\n", tag, offset);
}
}
free (cp_buf);
return java_obj;
}
R_API RBinJavaInterfaceInfo *r_bin_java_read_next_interface_item(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
ut8 idx[2] = {
0
};
RBinJavaInterfaceInfo *ifobj;
const ut8 *if_buf = buf + offset;
if (offset + 2 >= len) {
return NULL;
}
memcpy (&idx, if_buf, 2);
ifobj = r_bin_java_interface_new (bin, if_buf, len - offset);
if (ifobj) {
ifobj->file_offset = offset;
}
return ifobj;
}
// R_API void addrow (RBinJavaObj *bin, int addr, int line) {
// int n = bin->lines.count++;
//// XXX. possible memleak
// bin->lines.addr = realloc (bin->lines.addr, sizeof (int)*n+1);
// bin->lines.addr[n] = addr;
// bin->lines.line = realloc (bin->lines.line, sizeof (int)*n+1);
// bin->lines.line[n] = line;
// }
// R_API struct r_bin_java_cp_item_t* r_bin_java_get_item_from_cp_CP(RBinJavaObj *bin, int i) {
// return (i<0||i>bin->cf.cp_count)? &cp_null_item: &bin->cp_items[i];
// }
R_API char *r_bin_java_get_utf8_from_bin_cp_list(RBinJavaObj *bin, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new char* for caller to free.
*/
if (bin == NULL) {
return NULL;
}
return r_bin_java_get_utf8_from_cp_item_list (bin->cp_list, idx);
}
R_API ut32 r_bin_java_get_utf8_len_from_bin_cp_list(RBinJavaObj *bin, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new char* for caller to free.
*/
if (bin == NULL) {
return 0;
}
return r_bin_java_get_utf8_len_from_cp_item_list (bin->cp_list, idx);
}
R_API char *r_bin_java_get_name_from_bin_cp_list(RBinJavaObj *bin, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new char* for caller to free.
*/
if (bin == NULL) {
return NULL;
}
return r_bin_java_get_name_from_cp_item_list (bin->cp_list, idx);
}
R_API char *r_bin_java_get_desc_from_bin_cp_list(RBinJavaObj *bin, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new char* for caller to free.
*/
if (bin == NULL) {
return NULL;
}
return r_bin_java_get_desc_from_cp_item_list (bin->cp_list, idx);
}
R_API RBinJavaCPTypeObj *r_bin_java_get_item_from_bin_cp_list(RBinJavaObj *bin, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: RBinJavaObj* (user does NOT free).
*/
if (bin == NULL) {
return NULL;
}
if (idx > bin->cp_count || idx == 0) {
return r_bin_java_get_java_null_cp ();
}
return r_bin_java_get_item_from_cp_item_list (bin->cp_list, idx);
}
R_API char *r_bin_java_get_item_name_from_bin_cp_list(RBinJavaObj *bin, RBinJavaCPTypeObj *obj) {
char *res = NULL;
/*
Given a constant poool object Class, FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@param cp_list: RList of RBinJavaCPTypeObj *
@param obj object to look up the name for
@rvalue char* (user frees) or NULL
*/
if (bin && obj) {
res = r_bin_java_get_item_name_from_cp_item_list (
bin->cp_list, obj, MAX_CPITEMS);
}
return res;
}
R_API char *r_bin_java_get_item_desc_from_bin_cp_list(RBinJavaObj *bin, RBinJavaCPTypeObj *obj) {
/*
Given a constant poool object Class, FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@param cp_list: RList of RBinJavaCPTypeObj *
@param obj object to look up the name for
@rvalue char* (user frees) or NULL
*/
if (bin == NULL) {
return NULL;
}
return r_bin_java_get_item_desc_from_cp_item_list (bin->cp_list, obj, MAX_CPITEMS);
}
R_API char *r_bin_java_get_utf8_from_cp_item_list(RList *cp_list, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new char* for caller to free.
*/
char *value = NULL;
RListIter *iter;
RBinJavaCPTypeObj *item = NULL;
if (cp_list == NULL) {
return NULL;
}
item = (RBinJavaCPTypeObj *) r_list_get_n (cp_list, idx);
if (item && item->tag == R_BIN_JAVA_CP_UTF8 && item->metas->ord == idx) {
value = convert_string ((const char *) item->info.cp_utf8.bytes, item->info.cp_utf8.length);
}
if (value == NULL) {
r_list_foreach (cp_list, iter, item) {
if (item && (item->tag == R_BIN_JAVA_CP_UTF8) && item->metas->ord == idx) {
value = convert_string ((const char *) item->info.cp_utf8.bytes, item->info.cp_utf8.length);
break;
}
}
}
return value;
}
R_API ut32 r_bin_java_get_utf8_len_from_cp_item_list(RList *cp_list, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
If the idx not found by directly going to the list index,
the list will be walked and then the IDX will be checked.
rvalue: new ut32 .
*/
ut32 value = -1;
RListIter *iter;
RBinJavaCPTypeObj *item = NULL;
if (cp_list == NULL) {
return 0;
}
item = (RBinJavaCPTypeObj *) r_list_get_n (cp_list, idx);
if (item && (item->tag == R_BIN_JAVA_CP_UTF8) && item->metas->ord == idx) {
value = item->info.cp_utf8.length;
}
if (value == -1) {
r_list_foreach (cp_list, iter, item) {
if (item && (item->tag == R_BIN_JAVA_CP_UTF8) && item->metas->ord == idx) {
value = item->info.cp_utf8.length;
break;
}
}
}
return value;
}
R_API RBinJavaCPTypeObj *r_bin_java_get_item_from_cp_item_list(RList *cp_list, ut64 idx) {
/*
Search through the Constant Pool list for the given CP Index.
rvalue: RBinJavaObj *
*/
RBinJavaCPTypeObj *item = NULL;
if (cp_list == NULL) {
return NULL;
}
item = (RBinJavaCPTypeObj *) r_list_get_n (cp_list, idx);
return item;
}
R_API char *r_bin_java_get_item_name_from_cp_item_list(RList *cp_list, RBinJavaCPTypeObj *obj, int depth) {
/*
Given a constant poool object Class, FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@param cp_list: RList of RBinJavaCPTypeObj *
@param obj object to look up the name for
@rvalue ut8* (user frees) or NULL
*/
if (obj == NULL || cp_list == NULL || depth < 0) {
return NULL;
}
switch (obj->tag) {
case R_BIN_JAVA_CP_NAMEANDTYPE:
return r_bin_java_get_utf8_from_cp_item_list (
cp_list, obj->info.cp_name_and_type.name_idx);
case R_BIN_JAVA_CP_CLASS:
return r_bin_java_get_utf8_from_cp_item_list (
cp_list, obj->info.cp_class.name_idx);
// XXX - Probably not good form, but they are the same memory structure
case R_BIN_JAVA_CP_FIELDREF:
case R_BIN_JAVA_CP_INTERFACEMETHOD_REF:
case R_BIN_JAVA_CP_METHODREF:
obj = r_bin_java_get_item_from_cp_item_list (
cp_list, obj->info.cp_method.name_and_type_idx);
return r_bin_java_get_item_name_from_cp_item_list (
cp_list, obj, depth - 1);
default:
return NULL;
case 0:
IFDBG eprintf("Invalid 0 tag in the constant pool\n");
return NULL;
}
return NULL;
}
R_API char *r_bin_java_get_name_from_cp_item_list(RList *cp_list, ut64 idx) {
/*
Given a constant poool object Class, FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@param cp_list: RList of RBinJavaCPTypeObj *
@param obj object to look up the name for
@rvalue ut8* (user frees) or NULL
*/
RBinJavaCPTypeObj *obj = r_bin_java_get_item_from_cp_item_list (
cp_list, idx);
if (obj && cp_list) {
return r_bin_java_get_item_name_from_cp_item_list (
cp_list, obj, MAX_CPITEMS);
}
return NULL;
}
R_API char *r_bin_java_get_item_desc_from_cp_item_list(RList *cp_list, RBinJavaCPTypeObj *obj, int depth) {
/*
Given a constant poool object FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@rvalue ut8* (user frees) or NULL
*/
if (!obj || !cp_list || depth < 0) {
return NULL;
}
switch (obj->tag) {
case R_BIN_JAVA_CP_NAMEANDTYPE:
return r_bin_java_get_utf8_from_cp_item_list (cp_list,
obj->info.cp_name_and_type.descriptor_idx);
// XXX - Probably not good form, but they are the same memory structure
case R_BIN_JAVA_CP_FIELDREF:
case R_BIN_JAVA_CP_INTERFACEMETHOD_REF:
case R_BIN_JAVA_CP_METHODREF:
obj = r_bin_java_get_item_from_cp_item_list (cp_list,
obj->info.cp_method.name_and_type_idx);
return r_bin_java_get_item_desc_from_cp_item_list (
cp_list, obj, depth - 1);
default:
return NULL;
}
return NULL;
}
R_API char *r_bin_java_get_desc_from_cp_item_list(RList *cp_list, ut64 idx) {
/*
Given a constant poool object FieldRef, MethodRef, or InterfaceMethodRef
return the actual descriptor string.
@rvalue ut8* (user frees) or NULL
*/
RBinJavaCPTypeObj *obj = r_bin_java_get_item_from_cp_item_list (cp_list, idx);
if (cp_list == NULL) {
return NULL;
}
return r_bin_java_get_item_desc_from_cp_item_list (cp_list, obj, MAX_CPITEMS);
}
R_API RBinJavaAttrInfo *r_bin_java_get_method_code_attribute(const RBinJavaField *method) {
/*
Search through a methods attributes and return the code attr.
rvalue: RBinJavaAttrInfo* if found otherwise NULL.
*/
RBinJavaAttrInfo *res = NULL, *attr = NULL;
RListIter *iter;
if (method) {
r_list_foreach (method->attributes, iter, attr) {
if (attr && (attr->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR)) {
res = attr;
break;
}
}
}
return res;
}
R_API RBinJavaAttrInfo *r_bin_java_get_attr_from_field(RBinJavaField *field, R_BIN_JAVA_ATTR_TYPE attr_type, ut32 pos) {
/*
Search through the Attribute list for the given type starting at position pos.
rvalue: NULL or the first occurrence of attr_type after pos
*/
RBinJavaAttrInfo *attr = NULL, *item;
RListIter *iter;
ut32 i = 0;
if (field) {
r_list_foreach (field->attributes, iter, item) {
// Note the increment happens after the comparison
if ((i++) >= pos) {
if (item && (item->type == attr_type)) {
attr = item;
break;
}
}
}
}
return attr;
}
R_API ut8 *r_bin_java_get_attr_buf(RBinJavaObj *bin, ut64 sz, const ut64 offset, const ut8 *buf, const ut64 len) {
ut8 *attr_buf = NULL;
int pending = len - offset;
const ut8 *a_buf = offset + buf;
attr_buf = (ut8 *) calloc (pending + 1, 1);
if (attr_buf == NULL) {
eprintf ("Unable to allocate enough bytes (0x%04"PFMT64x
") to read in the attribute.\n", sz);
return attr_buf;
}
memcpy (attr_buf, a_buf, pending); // sz+1);
return attr_buf;
}
R_API RBinJavaAttrInfo *r_bin_java_default_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
// NOTE: this function receives the buffer offset in the original buffer,
// but the buffer is already point to that particular offset.
// XXX - all the code that relies on this function should probably be modified
// so that the original buffer pointer is passed in and then the buffer+buf_offset
// points to the correct location.
RBinJavaAttrInfo *attr = R_NEW0 (RBinJavaAttrInfo);
if (!attr) {
return NULL;
}
RBinJavaAttrMetas *type_info = NULL;
attr->metas = R_NEW0 (RBinJavaMetaInfo);
if (attr->metas == NULL) {
free (attr);
return NULL;
}
attr->file_offset = buf_offset;
attr->name_idx = R_BIN_JAVA_USHORT (buffer, 0);
attr->length = R_BIN_JAVA_UINT (buffer, 2);
attr->size = R_BIN_JAVA_UINT (buffer, 2) + 6;
attr->name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->name_idx);
if (attr->name == NULL) {
// Something bad has happened
attr->name = r_str_dup (NULL, "NULL");
eprintf ("r_bin_java_default_attr_new: Unable to find the name for %d index.\n", attr->name_idx);
}
type_info = r_bin_java_get_attr_type_by_name (attr->name);
attr->metas->ord = (R_BIN_JAVA_GLOBAL_BIN->attr_idx++);
attr->metas->type_info = (void *) type_info;
// IFDBG eprintf (" Addrs for type_info [tag=%d]: 0x%08"PFMT64x"\n", type_val, &attr->metas->type_info);
return attr;
}
R_API RBinJavaAttrMetas *r_bin_java_get_attr_type_by_name(const char *name) {
// TODO: use sdb/hashtable here
int i;
for (i = 0; i < RBIN_JAVA_ATTRS_METAS_SZ; i++) {
if (!strcmp ((const char *) name, RBIN_JAVA_ATTRS_METAS[i].name)) {
return &RBIN_JAVA_ATTRS_METAS[i];
}
}
return &RBIN_JAVA_ATTRS_METAS[R_BIN_JAVA_ATTR_TYPE_UNKNOWN_ATTR];
}
R_API RBinJavaAttrInfo *r_bin_java_read_next_attr(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 buf_len) {
RBinJavaAttrInfo *attr = NULL;
ut32 sz = 0;
ut8 *buffer = NULL;
const ut8 *a_buf = offset + buf;
ut8 attr_idx_len = 6;
if (offset + 6 > buf_len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile in Attribute offset "
"(0x%"PFMT64x ") > len of remaining bytes (0x%"PFMT64x ").\n", offset, buf_len);
return NULL;
}
// ut16 attr_idx, ut32 length of attr.
sz = R_BIN_JAVA_UINT (a_buf, 2) + attr_idx_len; // r_bin_java_read_int (bin, buf_offset+2) + attr_idx_len;
if (sz + offset > buf_len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile in Attribute len "
"(0x%x) + offset (0x%"PFMT64x ") exceeds length of buffer (0x%"PFMT64x ").\n",
sz, offset, buf_len);
return NULL;
}
// when reading the attr bytes, need to also
// include the initial 6 bytes, which
// are not included in the attribute length
// ,
// sz, buf_offset, buf_offset+sz);
buffer = r_bin_java_get_attr_buf (bin, sz, offset, buf, buf_len);
// printf ("%d %d %d\n", sz, buf_len, offset);
if (offset < buf_len) {
attr = r_bin_java_read_next_attr_from_buffer (buffer, buf_len - offset, offset);
free (buffer);
if (!attr) {
return NULL;
}
attr->size = sz;
} else {
eprintf ("IS OOB\n");
}
return attr;
}
R_API RBinJavaAttrInfo *r_bin_java_read_next_attr_from_buffer(ut8 *buffer, st64 sz, st64 buf_offset) {
RBinJavaAttrInfo *attr = NULL;
char *name = NULL;
ut64 offset = 0;
ut16 name_idx;
st64 nsz;
RBinJavaAttrMetas *type_info = NULL;
if (!buffer || ((int) sz) < 4 || buf_offset < 0) {
eprintf ("r_bin_Java_read_next_attr_from_buffer: invalid buffer size %d\n", (int) sz);
return NULL;
}
name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
nsz = R_BIN_JAVA_UINT (buffer, offset);
offset += 4;
name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, name_idx);
if (!name) {
name = strdup ("unknown");
}
IFDBG eprintf("r_bin_java_read_next_attr: name_idx = %d is %s\n", name_idx, name);
type_info = r_bin_java_get_attr_type_by_name (name);
if (type_info) {
IFDBG eprintf("Typeinfo: %s, was %s\n", type_info->name, name);
// printf ("SZ %d %d %d\n", nsz, sz, buf_offset);
if (nsz > sz) {
free (name);
return NULL;
}
if ((attr = type_info->allocs->new_obj (buffer, nsz, buf_offset))) {
attr->metas->ord = (R_BIN_JAVA_GLOBAL_BIN->attr_idx++);
}
} else {
eprintf ("r_bin_java_read_next_attr_from_buffer: Cannot find type_info for %s\n", name);
}
free (name);
return attr;
}
R_API ut64 r_bin_java_read_class_file2(RBinJavaObj *bin, const ut64 offset, const ut8 *obuf, ut64 len) {
const ut8 *cf2_buf = obuf + offset;
RBinJavaCPTypeObj *this_class_cp_obj = NULL;
IFDBG eprintf("\n0x%"PFMT64x " Offset before reading the cf2 structure\n", offset);
/*
Reading the following fields:
ut16 access_flags;
ut16 this_class;
ut16 super_class;
*/
if (cf2_buf + 6 > obuf + len) {
return 0;
}
bin->cf2.cf2_size = 6;
bin->cf2.access_flags = R_BIN_JAVA_USHORT (cf2_buf, 0);
bin->cf2.this_class = R_BIN_JAVA_USHORT (cf2_buf, 2);
bin->cf2.super_class = R_BIN_JAVA_USHORT (cf2_buf, 4);
free (bin->cf2.flags_str);
free (bin->cf2.this_class_name);
bin->cf2.flags_str = retrieve_class_method_access_string (bin->cf2.access_flags);
this_class_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, bin->cf2.this_class);
bin->cf2.this_class_name = r_bin_java_get_item_name_from_bin_cp_list (bin, this_class_cp_obj);
IFDBG eprintf("This class flags are: %s\n", bin->cf2.flags_str);
return bin->cf2.cf2_size;
}
R_API ut64 r_bin_java_parse_cp_pool(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
int ord = 0;
ut64 adv = 0;
RBinJavaCPTypeObj *obj = NULL;
const ut8 *cp_buf = buf + offset;
r_list_free (bin->cp_list);
bin->cp_list = r_list_newf (r_bin_java_constant_pool);
bin->cp_offset = offset;
memcpy ((char *) &bin->cp_count, cp_buf, 2);
bin->cp_count = R_BIN_JAVA_USHORT (cp_buf, 0) - 1;
adv += 2;
IFDBG eprintf("ConstantPoolCount %d\n", bin->cp_count);
r_list_append (bin->cp_list, r_bin_java_get_java_null_cp ());
for (ord = 1, bin->cp_idx = 0; bin->cp_idx < bin->cp_count && adv < len; ord++, bin->cp_idx++) {
obj = r_bin_java_read_next_constant_pool_item (bin, offset + adv, buf, len);
if (obj) {
// IFDBG eprintf ("SUCCESS Read ConstantPoolItem %d\n", i);
obj->metas->ord = ord;
obj->idx = ord;
r_list_append (bin->cp_list, obj);
if (obj->tag == R_BIN_JAVA_CP_LONG || obj->tag == R_BIN_JAVA_CP_DOUBLE) {
// i++;
ord++;
bin->cp_idx++;
r_list_append (bin->cp_list, &R_BIN_JAVA_NULL_TYPE);
}
IFDBG ((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->print_summary (obj);
adv += ((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->calc_size (obj);
if (offset + adv > len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Constant Pool Object: %d.\n", ord);
break;
}
} else {
IFDBG eprintf("Failed to read ConstantPoolItem %d\n", bin->cp_idx);
break;
}
}
// Update the imports
r_bin_java_set_imports (bin);
bin->cp_size = adv;
return bin->cp_size;
}
R_API ut64 r_bin_java_parse_interfaces(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
int i = 0;
ut64 adv = 0;
RBinJavaInterfaceInfo *interfaces_obj;
const ut8 *if_buf = buf + offset;
bin->cp_offset = offset;
bin->interfaces_offset = offset;
r_list_free (bin->interfaces_list);
bin->interfaces_list = r_list_newf (r_bin_java_interface_free);
if (offset + 2 > len) {
bin->interfaces_size = 0;
return 0;
}
bin->interfaces_count = R_BIN_JAVA_USHORT (if_buf, 0);
adv += 2;
IFDBG eprintf("Interfaces count: %d\n", bin->interfaces_count);
if (bin->interfaces_count > 0) {
for (i = 0; i < bin->interfaces_count; i++) {
interfaces_obj = r_bin_java_read_next_interface_item (bin, offset + adv, buf, len);
if (interfaces_obj) {
r_list_append (bin->interfaces_list, interfaces_obj);
adv += interfaces_obj->size;
if (offset + adv > len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Interface: %d.\n", i);
break;
}
} else {
break;
}
}
}
bin->interfaces_size = adv;
return adv;
}
R_API ut64 r_bin_java_parse_fields(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
int i = 0;
ut64 adv = 0;
RBinJavaField *field;
const ut8 *fm_buf = buf + offset;
r_list_free (bin->fields_list);
bin->fields_list = r_list_newf (r_bin_java_fmtype_free);
bin->fields_offset = offset;
if (offset + 2 >= len) {
return UT64_MAX;
}
bin->fields_count = R_BIN_JAVA_USHORT (fm_buf, 0);
adv += 2;
IFDBG eprintf("Fields count: %d 0x%"PFMT64x "\n", bin->fields_count, bin->fields_offset);
if (bin->fields_count > 0) {
for (i = 0; i < bin->fields_count; i++, bin->field_idx++) {
field = r_bin_java_read_next_field (bin, offset + adv, buf, len);
if (field) {
adv += field->size;
r_list_append (bin->fields_list, field);
IFDBG r_bin_java_print_field_summary(field);
if (adv + offset > len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Field: %d.\n", i);
break;
}
} else {
IFDBG eprintf("Failed to read Field %d\n", i);
}
}
}
bin->fields_size = adv;
return adv;
}
R_API ut64 r_bin_java_parse_attrs(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
int i = 0;
ut64 adv = 0;
const ut8 *a_buf = buf + offset;
if (offset + 2 >= len) {
// Check if we can read that USHORT
return UT64_MAX;
}
r_list_free (bin->attrs_list);
bin->attrs_list = r_list_newf (r_bin_java_attribute_free);
bin->attrs_offset = offset;
bin->attrs_count = R_BIN_JAVA_USHORT (a_buf, adv);
adv += 2;
if (bin->attrs_count > 0) {
for (i = 0; i < bin->attrs_count; i++, bin->attr_idx++) {
RBinJavaAttrInfo *attr = r_bin_java_read_next_attr (bin, offset + adv, buf, len);
if (!attr) {
// eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attribute: %d.\n", i);
break;
}
r_list_append (bin->attrs_list, attr);
adv += attr->size;
if (adv + offset >= len) {
// eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attribute: %d.\n", i);
break;
}
}
}
bin->attrs_size = adv;
return adv;
}
R_API ut64 r_bin_java_parse_methods(RBinJavaObj *bin, const ut64 offset, const ut8 *buf, const ut64 len) {
int i = 0;
ut64 adv = 0;
RBinJavaField *method;
const ut8 *fm_buf = buf + offset;
r_list_free (bin->methods_list);
bin->methods_list = r_list_newf (r_bin_java_fmtype_free);
if (offset + 2 >= len) {
return 0LL;
}
bin->methods_offset = offset;
bin->methods_count = R_BIN_JAVA_USHORT (fm_buf, 0);
adv += 2;
IFDBG eprintf("Methods count: %d 0x%"PFMT64x "\n", bin->methods_count, bin->methods_offset);
bin->main = NULL;
bin->entrypoint = NULL;
bin->main_code_attr = NULL;
bin->entrypoint_code_attr = NULL;
for (i = 0; i < bin->methods_count; i++, bin->method_idx++) {
method = r_bin_java_read_next_method (bin, offset + adv, buf, len);
if (method) {
adv += method->size;
r_list_append (bin->methods_list, method);
}
// Update Main, Init, or Class Init
if (method && !strcmp ((const char *) method->name, "main")) {
bin->main = method;
// get main code attr
bin->main_code_attr = r_bin_java_get_attr_from_field (method, R_BIN_JAVA_ATTR_TYPE_CODE_ATTR, 0);
} else if (method && (!strcmp ((const char *) method->name, "<init>") || !strcmp ((const char *) method->name, "init"))) {
IFDBG eprintf("FOund an init function.\n");
bin->entrypoint = method;
bin->entrypoint_code_attr = r_bin_java_get_attr_from_field (method, R_BIN_JAVA_ATTR_TYPE_CODE_ATTR, 0);
} else if (method && (!strcmp ((const char *) method->name, "<cinit>") || !strcmp ((const char *) method->name, "cinit"))) {
bin->cf2.this_class_entrypoint = method;
bin->cf2.this_class_entrypoint_code_attr = r_bin_java_get_attr_from_field (method, R_BIN_JAVA_ATTR_TYPE_CODE_ATTR, 0);
}
if (adv + offset > len) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Method: %d.\n", i);
break;
}
IFDBG r_bin_java_print_field_summary(method);
}
bin->methods_size = adv;
return adv;
}
R_API int r_bin_java_new_bin(RBinJavaObj *bin, ut64 loadaddr, Sdb *kv, const ut8 *buf, ut64 len) {
R_BIN_JAVA_GLOBAL_BIN = bin;
bin->lines.count = 0;
bin->loadaddr = loadaddr;
r_bin_java_get_java_null_cp ();
bin->id = r_num_rand (UT32_MAX);
bin->kv = kv ? kv : sdb_new (NULL, NULL, 0);
bin->AllJavaBinObjs = NULL;
return r_bin_java_load_bin (bin, buf, len);
}
R_API int r_bin_java_load_bin(RBinJavaObj *bin, const ut8 *buf, ut64 buf_sz) {
ut64 adv = 0;
R_BIN_JAVA_GLOBAL_BIN = bin;
if (!bin) {
return false;
}
r_bin_java_reset_bin_info (bin);
memcpy ((ut8 *) &bin->cf, buf, 10);
if (memcmp (bin->cf.cafebabe, "\xCA\xFE\xBA\xBE", 4)) {
eprintf ("r_bin_java_new_bin: Invalid header (%02x %02x %02x %02x)\n",
bin->cf.cafebabe[0], bin->cf.cafebabe[1],
bin->cf.cafebabe[2], bin->cf.cafebabe[3]);
return false;
}
if (bin->cf.major[0] == bin->cf.major[1] && bin->cf.major[0] == 0) {
eprintf ("Java CLASS with MACH0 header?\n");
return false;
}
adv += 8;
// -2 so that the cp_count will be parsed
adv += r_bin_java_parse_cp_pool (bin, adv, buf, buf_sz);
if (adv > buf_sz) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Constant Pool.\n");
return true;
}
adv += r_bin_java_read_class_file2 (bin, adv, buf, buf_sz);
if (adv > buf_sz) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after class file info.\n");
return true;
}
IFDBG eprintf("This class: %d %s\n", bin->cf2.this_class, bin->cf2.this_class_name);
IFDBG eprintf("0x%"PFMT64x " Access flags: 0x%04x\n", adv, bin->cf2.access_flags);
adv += r_bin_java_parse_interfaces (bin, adv, buf, buf_sz);
if (adv > buf_sz) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Interfaces.\n");
return true;
}
adv += r_bin_java_parse_fields (bin, adv, buf, buf_sz);
if (adv > buf_sz) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Fields.\n");
return true;
}
adv += r_bin_java_parse_methods (bin, adv, buf, buf_sz);
if (adv > buf_sz) {
eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Methods.\n");
return true;
}
adv += r_bin_java_parse_attrs (bin, adv, buf, buf_sz);
bin->calc_size = adv;
// if (adv > buf_sz) {
// eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attributes.\n");
// return true;
// }
// add_cp_objs_to_sdb(bin);
// add_method_infos_to_sdb(bin);
// add_field_infos_to_sdb(bin);
return true;
}
R_API char *r_bin_java_get_version(RBinJavaObj *bin) {
return r_str_newf ("0x%02x%02x 0x%02x%02x",
bin->cf.major[1], bin->cf.major[0],
bin->cf.minor[1], bin->cf.minor[0]);
}
R_API RList *r_bin_java_get_entrypoints(RBinJavaObj *bin) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaField *fm_type;
RList *ret = r_list_newf (free);
if (!ret) {
return NULL;
}
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
if (!strcmp (fm_type->name, "main")
|| !strcmp (fm_type->name, "<init>")
|| !strcmp (fm_type->name, "<clinit>")
|| strstr (fm_type->flags_str, "static")) {
RBinAddr *addr = R_NEW0 (RBinAddr);
if (addr) {
addr->vaddr = addr->paddr = \
r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr;
addr->haddr = fm_type->file_offset;
r_list_append (ret, addr);
}
}
}
return ret;
}
R_API RBinJavaField *r_bin_java_get_method_code_attribute_with_addr(RBinJavaObj *bin, ut64 addr) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaField *fm_type, *res = NULL;
if (bin == NULL && R_BIN_JAVA_GLOBAL_BIN) {
bin = R_BIN_JAVA_GLOBAL_BIN;
} else if (bin == NULL) {
eprintf ("Attempting to analyse function when the R_BIN_JAVA_GLOBAL_BIN has not been set.\n");
return NULL;
}
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
ut64 offset = r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr,
size = r_bin_java_get_method_code_size (fm_type);
if (addr >= offset && addr <= size + offset) {
res = fm_type;
}
}
return res;
}
R_API RBinAddr *r_bin_java_get_entrypoint(RBinJavaObj *bin, int sym) {
RBinAddr *ret = NULL;
ret = R_NEW0 (RBinAddr);
if (!ret) {
return NULL;
}
ret->paddr = UT64_MAX;
switch (sym) {
case R_BIN_SYM_ENTRY:
case R_BIN_SYM_INIT:
ret->paddr = r_bin_java_find_method_offset (bin, "<init>");
if (ret->paddr == UT64_MAX) {
ret->paddr = r_bin_java_find_method_offset (bin, "<cinit>");
}
break;
case R_BIN_SYM_FINI:
ret->paddr = UT64_MAX;
break;
case R_BIN_SYM_MAIN:
ret->paddr = r_bin_java_find_method_offset (bin, "main");
break;
default:
ret->paddr = -1;
}
if (ret->paddr != -1) {
ret->paddr += bin->loadaddr;
}
return ret;
}
R_API ut64 r_bin_java_get_method_code_size(RBinJavaField *fm_type) {
RListIter *attr_iter = NULL, *attr_iter_tmp = NULL;
RBinJavaAttrInfo *attr = NULL;
ut64 sz = 0;
r_list_foreach_safe (fm_type->attributes, attr_iter, attr_iter_tmp, attr) {
if (attr->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR) {
sz = attr->info.code_attr.code_length;
break;
}
}
return sz;
}
R_API ut64 r_bin_java_find_method_offset(RBinJavaObj *bin, const char *method_name) {
RListIter *attr_iter = NULL, *attr_iter_tmp = NULL;
RBinJavaField *method = NULL;
ut64 offset = -1;
r_list_foreach_safe (bin->methods_list, attr_iter, attr_iter_tmp, method) {
if (method && !strcmp ((const char *) method->name, method_name)) {
offset = r_bin_java_get_method_code_offset (method) + bin->loadaddr;
break;
}
}
return offset;
}
R_API ut64 r_bin_java_get_method_code_offset(RBinJavaField *fm_type) {
RListIter *attr_iter = NULL, *attr_iter_tmp = NULL;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
r_list_foreach_safe (fm_type->attributes, attr_iter, attr_iter_tmp, attr) {
if (attr->type == R_BIN_JAVA_ATTR_TYPE_CODE_ATTR) {
offset = attr->info.code_attr.code_offset;
break;
}
}
return offset;
}
R_API RBinField *r_bin_java_allocate_rbinfield() {
RBinField *t = (RBinField *) malloc (sizeof (RBinField));
if (t) {
memset (t, 0, sizeof (RBinField));
}
return t;
}
R_API RBinField *r_bin_java_create_new_rbinfield_from_field(RBinJavaField *fm_type, ut64 baddr) {
RBinField *field = r_bin_java_allocate_rbinfield ();
if (field) {
field->name = strdup (fm_type->name);
field->paddr = fm_type->file_offset + baddr;
field->visibility = fm_type->flags;
}
return field;
}
R_API RBinSymbol *r_bin_java_create_new_symbol_from_field(RBinJavaField *fm_type, ut64 baddr) {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
if (fm_type == NULL || fm_type->field_ref_cp_obj == NULL || fm_type->field_ref_cp_obj == &R_BIN_JAVA_NULL_TYPE) {
free (sym);
sym = NULL;
}
if (sym) {
sym->name = strdup (fm_type->name);
// strncpy (sym->type, fm_type->descriptor, R_BIN_SIZEOF_STRINGS);
if (fm_type->type == R_BIN_JAVA_FIELD_TYPE_METHOD) {
sym->type = r_str_const (R_BIN_TYPE_FUNC_STR);
sym->paddr = r_bin_java_get_method_code_offset (fm_type);
sym->vaddr = r_bin_java_get_method_code_offset (fm_type) + baddr;
sym->size = r_bin_java_get_method_code_size (fm_type);
} else {
sym->type = r_str_const ("FIELD");
sym->paddr = fm_type->file_offset;// r_bin_java_get_method_code_offset (fm_type);
sym->vaddr = fm_type->file_offset + baddr;
sym->size = fm_type->size;
}
if (r_bin_java_is_fm_type_protected (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_LOCAL_STR);
} else if (r_bin_java_is_fm_type_private (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_LOCAL_STR);
} else if (r_bin_java_is_fm_type_protected (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_GLOBAL_STR);
}
sym->forwarder = r_str_const ("NONE");
if (fm_type->class_name) {
sym->classname = strdup (fm_type->class_name);
} else {
sym->classname = strdup ("UNKNOWN"); // dupped names?
}
sym->ordinal = fm_type->metas->ord;
sym->visibility = fm_type->flags;
if (fm_type->flags_str) {
sym->visibility_str = strdup (fm_type->flags_str);
}
}
return sym;
}
R_API RBinSymbol *r_bin_java_create_new_symbol_from_fm_type_meta(RBinJavaField *fm_type, ut64 baddr) {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
if (!sym || !fm_type || !fm_type->field_ref_cp_obj || fm_type->field_ref_cp_obj == &R_BIN_JAVA_NULL_TYPE) {
free (sym);
return NULL;
}
// ut32 new_name_len = strlen (fm_type->name) + strlen ("_meta") + 1;
// char *new_name = malloc (new_name_len);
sym->name = r_str_newf ("meta_%s", fm_type->name);
if (fm_type->type == R_BIN_JAVA_FIELD_TYPE_METHOD) {
sym->type = r_str_const ("FUNC_META");
} else {
sym->type = r_str_const ("FIELD_META");
}
if (r_bin_java_is_fm_type_protected (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_LOCAL_STR);
} else if (r_bin_java_is_fm_type_private (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_LOCAL_STR);
} else if (r_bin_java_is_fm_type_protected (fm_type)) {
sym->bind = r_str_const (R_BIN_BIND_GLOBAL_STR);
}
sym->forwarder = r_str_const ("NONE");
if (fm_type->class_name) {
sym->classname = strdup (fm_type->class_name);
} else {
sym->classname = strdup ("UNKNOWN");
}
sym->paddr = fm_type->file_offset;// r_bin_java_get_method_code_offset (fm_type);
sym->vaddr = fm_type->file_offset + baddr;
sym->ordinal = fm_type->metas->ord;
sym->size = fm_type->size;
sym->visibility = fm_type->flags;
if (fm_type->flags_str) {
sym->visibility_str = strdup (fm_type->flags_str);
}
return sym;
}
R_API RBinSymbol *r_bin_java_create_new_symbol_from_ref(RBinJavaCPTypeObj *obj, ut64 baddr) {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
if (!sym) {
return NULL;
}
char *class_name, *name, *type_name;
if (obj == NULL || (obj->tag != R_BIN_JAVA_CP_METHODREF &&
obj->tag != R_BIN_JAVA_CP_INTERFACEMETHOD_REF &&
obj->tag != R_BIN_JAVA_CP_FIELDREF)) {
free (sym);
sym = NULL;
return sym;
}
if (sym) {
class_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN,
obj->info.cp_method.class_idx);
name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN,
obj->info.cp_method.name_and_type_idx);
type_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN,
obj->info.cp_method.name_and_type_idx);
if (name) {
sym->name = name;
name = NULL;
}
if (type_name) {
sym->type = r_str_const (type_name);
R_FREE (type_name);
}
if (class_name) {
sym->classname = strdup (class_name);
}
sym->paddr = obj->file_offset + baddr;
sym->vaddr = obj->file_offset + baddr;
sym->ordinal = obj->metas->ord;
sym->size = 0;
}
return sym;
}
R_API RList *r_bin_java_get_sections(RBinJavaObj *bin) {
RBinSection *section = NULL;
RList *sections = r_list_newf (free);
ut64 baddr = bin->loadaddr;
RBinJavaField *fm_type;
RListIter *iter = NULL;
if (bin->cp_count > 0) {
section = R_NEW0 (RBinSection);
if (section) {
strcpy (section->name, "constant_pool");
section->size = bin->cp_size;
section->paddr = bin->cp_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
}
section = NULL;
}
if (bin->fields_count > 0) {
section = R_NEW0 (RBinSection);
if (section) {
strcpy (section->name, "fields");
section->size = bin->fields_size;
section->paddr = bin->fields_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
section = NULL;
r_list_foreach (bin->fields_list, iter, fm_type) {
if (fm_type->attr_offset == 0) {
continue;
}
section = R_NEW0 (RBinSection);
if (section) {
snprintf (section->name, R_BIN_SIZEOF_STRINGS, "attrs.%s", fm_type->name);
section->size = fm_type->size - (fm_type->file_offset - fm_type->attr_offset);
section->paddr = fm_type->attr_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
}
}
}
}
if (bin->methods_count > 0) {
section = R_NEW0 (RBinSection);
if (section) {
strcpy (section->name, "methods");
section->size = bin->methods_size;
section->paddr = bin->methods_offset + baddr;
section->srwx = R_BIN_SCN_READABLE | R_BIN_SCN_EXECUTABLE;
section->add = true;
r_list_append (sections, section);
section = NULL;
r_list_foreach (bin->methods_list, iter, fm_type) {
if (fm_type->attr_offset == 0) {
continue;
}
section = R_NEW0 (RBinSection);
if (section) {
snprintf (section->name, R_BIN_SIZEOF_STRINGS, "attrs.%s", fm_type->name);
section->size = fm_type->size - (fm_type->file_offset - fm_type->attr_offset);
section->paddr = fm_type->attr_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
}
}
}
}
if (bin->interfaces_count > 0) {
section = R_NEW0 (RBinSection);
if (section) {
strcpy (section->name, "interfaces");
section->size = bin->interfaces_size;
section->paddr = bin->interfaces_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
}
section = NULL;
}
if (bin->attrs_count > 0) {
section = R_NEW0 (RBinSection);
if (section) {
strcpy (section->name, "attributes");
section->size = bin->attrs_size;
section->paddr = bin->attrs_offset + baddr;
section->srwx = R_BIN_SCN_READABLE;
section->add = true;
r_list_append (sections, section);
}
section = NULL;
}
return sections;
}
R_API RList *r_bin_java_enum_class_methods(RBinJavaObj *bin, ut16 class_idx) {
RList *methods = r_list_newf (free);
RListIter *iter;
RBinJavaField *field;
r_list_foreach (bin->methods_list, iter, field) {
if (field->field_ref_cp_obj && 0) {
if ((field && field->field_ref_cp_obj->metas->ord == class_idx)) {
RBinSymbol *sym = r_bin_java_create_new_symbol_from_ref (
field->field_ref_cp_obj, bin->loadaddr);
if (sym) {
r_list_append (methods, sym);
}
}
} else {
RBinSymbol *sym = R_NEW0 (RBinSymbol);
sym->name = strdup (field->name);
// func defintion
// sym->paddr = field->file_offset + bin->loadaddr;
// code implementation
sym->paddr = r_bin_java_get_method_code_offset (field);
sym->vaddr = sym->paddr; // + bin->loadaddr;
r_list_append (methods, sym);
}
}
return methods;
}
R_API RList *r_bin_java_enum_class_fields(RBinJavaObj *bin, ut16 class_idx) {
RList *fields = r_list_newf (free);
RListIter *iter;
RBinJavaField *fm_type;
RBinField *field = NULL;
r_list_foreach (bin->fields_list, iter, fm_type) {
if (fm_type) {
if (fm_type && fm_type->field_ref_cp_obj
&& fm_type->field_ref_cp_obj->metas->ord == class_idx) {
field = r_bin_java_create_new_rbinfield_from_field (fm_type, bin->loadaddr);
if (field) {
r_list_append (fields, field);
}
}
}
}
return fields;
}
R_API int is_class_interface(RBinJavaObj *bin, RBinJavaCPTypeObj *cp_obj) {
RBinJavaInterfaceInfo *ifobj;
RListIter *iter;
int res = false;
r_list_foreach (bin->interfaces_list, iter, ifobj) {
if (ifobj) {
res = cp_obj == ifobj->cp_class;
if (res) {
break;
}
}
}
return res;
}
/*
R_API RList * r_bin_java_get_interface_classes(RBinJavaObj * bin) {
RList *interfaces_names = r_list_new();
RListIter *iter;
RBinJavaInterfaceInfo *ifobj;
r_list_foreach(bin->interfaces_list, iter, iinfo) {
RBinClass *class_ = R_NEW0 (RBinClass);
RBinJavaCPTypeObj *cp_obj = ;
if (ifobj && ifobj->name) {
ut8 * name = strdup(ifobj->name);
r_list_append(interfaces_names, name);
}
}
return interfaces_names;
}
*/
R_API RList *r_bin_java_get_lib_names(RBinJavaObj *bin) {
RList *lib_names = r_list_newf (free);
RListIter *iter;
RBinJavaCPTypeObj *cp_obj = NULL;
if (!bin) {
return lib_names;
}
r_list_foreach (bin->cp_list, iter, cp_obj) {
if (cp_obj && cp_obj->tag == R_BIN_JAVA_CP_CLASS &&
(bin->cf2.this_class != cp_obj->info.cp_class.name_idx || !is_class_interface (bin, cp_obj))) {
char *name = r_bin_java_get_item_name_from_bin_cp_list (bin, cp_obj);
r_list_append (lib_names, name);
}
}
return lib_names;
}
R_API void r_bin_java_classes_free(void /*RBinClass*/ *k) {
RBinClass *klass = k;
if (klass) {
r_list_free (klass->methods);
r_list_free (klass->fields);
free (klass->name);
free (klass->super);
free (klass->visibility_str);
free (klass);
}
}
R_API RList *r_bin_java_get_classes(RBinJavaObj *bin) {
RList *classes = r_list_newf (r_bin_java_classes_free);
RListIter *iter;
RBinJavaCPTypeObj *cp_obj = NULL;
RBinJavaCPTypeObj *this_class_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, bin->cf2.this_class);
ut32 idx = 0;
RBinClass *k = R_NEW0 (RBinClass);
if (!k) {
r_list_free (classes);
return NULL;
}
k->visibility = bin->cf2.access_flags;
if (bin->cf2.flags_str) {
k->visibility_str = strdup (bin->cf2.flags_str);
}
k->methods = r_bin_java_enum_class_methods (bin, bin->cf2.this_class);
k->fields = r_bin_java_enum_class_fields (bin, bin->cf2.this_class);
k->name = r_bin_java_get_this_class_name (bin);
k->super = r_bin_java_get_name_from_bin_cp_list (bin, bin->cf2.super_class);
k->index = (idx++);
r_list_append (classes, k);
r_list_foreach (bin->cp_list, iter, cp_obj) {
if (cp_obj && cp_obj->tag == R_BIN_JAVA_CP_CLASS
&& (this_class_cp_obj != cp_obj && is_class_interface (bin, cp_obj))) {
k = R_NEW0 (RBinClass);
if (!k) {
break;
}
k->methods = r_bin_java_enum_class_methods (bin, cp_obj->info.cp_class.name_idx);
k->fields = r_bin_java_enum_class_fields (bin, cp_obj->info.cp_class.name_idx);
k->index = idx;
k->name = r_bin_java_get_item_name_from_bin_cp_list (bin, cp_obj);
r_list_append (classes, k);
idx++;
}
}
return classes;
}
R_API RBinSymbol *r_bin_java_create_new_symbol_from_invoke_dynamic(RBinJavaCPTypeObj *obj, ut64 baddr) {
if (!obj || (obj->tag != R_BIN_JAVA_CP_INVOKEDYNAMIC)) {
return NULL;
}
return r_bin_java_create_new_symbol_from_cp_idx (obj->info.cp_invoke_dynamic.name_and_type_index, baddr);
}
R_API RBinSymbol *r_bin_java_create_new_symbol_from_cp_idx(ut32 cp_idx, ut64 baddr) {
RBinSymbol *sym = NULL;
RBinJavaCPTypeObj *obj = r_bin_java_get_item_from_bin_cp_list (
R_BIN_JAVA_GLOBAL_BIN, cp_idx);
if (obj) {
switch (obj->tag) {
case R_BIN_JAVA_CP_METHODREF:
case R_BIN_JAVA_CP_FIELDREF:
case R_BIN_JAVA_CP_INTERFACEMETHOD_REF:
sym = r_bin_java_create_new_symbol_from_ref (obj, baddr);
break;
case R_BIN_JAVA_CP_INVOKEDYNAMIC:
sym = r_bin_java_create_new_symbol_from_invoke_dynamic (obj, baddr);
break;
default:
break;
}
}
return sym;
}
R_API RList *U(r_bin_java_get_fields)(RBinJavaObj * bin) {
RListIter *iter = NULL, *iter_tmp = NULL;
RList *fields = r_list_new ();
RBinJavaField *fm_type;
RBinField *field;
r_list_foreach_safe (bin->fields_list, iter, iter_tmp, fm_type) {
field = r_bin_java_create_new_rbinfield_from_field (fm_type, bin->loadaddr);
if (field) {
r_list_append (fields, field);
}
}
return fields;
}
R_API void r_bin_add_import(RBinJavaObj *bin, RBinJavaCPTypeObj *obj, const char *type) {
RBinImport *imp = R_NEW0 (RBinImport);
char *class_name = r_bin_java_get_name_from_bin_cp_list (bin, obj->info.cp_method.class_idx);
char *name = r_bin_java_get_name_from_bin_cp_list (bin, obj->info.cp_method.name_and_type_idx);
char *descriptor = r_bin_java_get_desc_from_bin_cp_list (bin, obj->info.cp_method.name_and_type_idx);
class_name = class_name ? class_name : strdup ("INVALID CLASS NAME INDEX");
name = name ? name : strdup ("InvalidNameIndex");
descriptor = descriptor ? descriptor : strdup ("INVALID DESCRIPTOR INDEX");
imp->classname = class_name;
imp->name = name;
imp->bind = r_str_const ("NONE");
imp->type = r_str_const (type);
imp->descriptor = descriptor;
imp->ordinal = obj->idx;
r_list_append (bin->imports_list, imp);
}
R_API void r_bin_java_set_imports(RBinJavaObj *bin) {
RListIter *iter = NULL;
RBinJavaCPTypeObj *obj = NULL;
r_list_free (bin->imports_list);
bin->imports_list = r_list_newf (free);
r_list_foreach (bin->cp_list, iter, obj) {
const char *type = NULL;
switch (obj->tag) {
case R_BIN_JAVA_CP_METHODREF: type = "METHOD"; break;
case R_BIN_JAVA_CP_INTERFACEMETHOD_REF: type = "FIELD"; break;
case R_BIN_JAVA_CP_FIELDREF: type = "INTERFACE_METHOD"; break;
default: type = NULL; break;
}
if (type) {
r_bin_add_import (bin, obj, type);
}
}
}
R_API RList *r_bin_java_get_imports(RBinJavaObj *bin) {
RList *ret = r_list_newf (free);
RBinImport *import = NULL;
RListIter *iter;
r_list_foreach (bin->imports_list, iter, import) {
RBinImport *n_import = R_NEW0 (RBinImport);
if (!n_import) {
r_list_free (ret);
return NULL;
}
memcpy (n_import, import, sizeof (RBinImport));
r_list_append (ret, n_import);
}
return ret;
}
R_API RList *r_bin_java_get_symbols(RBinJavaObj *bin) {
RListIter *iter = NULL, *iter_tmp = NULL;
RList *imports, *symbols = r_list_newf (free);
RBinSymbol *sym = NULL;
RBinImport *imp;
RBinJavaField *fm_type;
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
sym = r_bin_java_create_new_symbol_from_field (fm_type, bin->loadaddr);
if (sym) {
r_list_append (symbols, (void *) sym);
}
sym = r_bin_java_create_new_symbol_from_fm_type_meta (fm_type, bin->loadaddr);
if (sym) {
r_list_append (symbols, (void *) sym);
}
}
r_list_foreach_safe (bin->fields_list, iter, iter_tmp, fm_type) {
sym = r_bin_java_create_new_symbol_from_field (fm_type, bin->loadaddr);
if (sym) {
r_list_append (symbols, (void *) sym);
}
sym = r_bin_java_create_new_symbol_from_fm_type_meta (fm_type, bin->loadaddr);
if (sym) {
r_list_append (symbols, (void *) sym);
}
}
bin->lang = "java";
imports = r_bin_java_get_imports (bin);
r_list_foreach (imports, iter, imp) {
sym = R_NEW0 (RBinSymbol);
if (!sym) {
break;
}
if (imp->classname && !strncmp (imp->classname, "kotlin/jvm", 10)) {
bin->lang = "kotlin";
}
sym->name = r_str_newf ("imp.%s", imp->name);
if (!sym->name) {
free (sym);
break;
}
sym->type = r_str_const ("import");
if (!sym->type) {
free (sym);
break;
}
sym->vaddr = sym->paddr = imp->ordinal;
sym->ordinal = imp->ordinal;
r_list_append (symbols, (void *) sym);
}
r_list_free (imports);
return symbols;
}
R_API RList *r_bin_java_get_strings(RBinJavaObj *bin) {
RList *strings = r_list_newf (free);
RBinString *str = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaCPTypeObj *cp_obj = NULL;
r_list_foreach_safe (bin->cp_list, iter, iter_tmp, cp_obj) {
if (cp_obj && cp_obj->tag == R_BIN_JAVA_CP_UTF8) {
str = (RBinString *) R_NEW0 (RBinString);
if (str) {
str->paddr = cp_obj->file_offset + bin->loadaddr;
str->ordinal = cp_obj->metas->ord;
str->size = cp_obj->info.cp_utf8.length + 3;
str->length = cp_obj->info.cp_utf8.length;
if (str->size > 0) {
str->string = r_str_ndup ((const char *)
cp_obj->info.cp_utf8.bytes,
R_BIN_JAVA_MAXSTR);
}
r_list_append (strings, (void *) str);
}
}
}
return strings;
}
R_API void *r_bin_java_free(RBinJavaObj *bin) {
char *bin_obj_key = NULL;
if (!bin) {
return NULL;
}
// Delete the bin object from the data base.
bin_obj_key = r_bin_java_build_obj_key (bin);
// if (bin->AllJavaBinObjs && sdb_exists (bin->AllJavaBinObjs, bin_obj_key)) {
// sdb_unset (bin->AllJavaBinObjs, bin_obj_key, 0);
// }
free (bin_obj_key);
r_list_free (bin->imports_list);
// XXX - Need to remove all keys belonging to this class from
// the share meta information sdb.
// TODO e.g. iterate over bin->kv and delete all obj, func, etc. keys
// sdb_free (bin->kv);
// free up the constant pool list
r_list_free (bin->cp_list);
// free up the fields list
r_list_free (bin->fields_list);
// free up methods list
r_list_free (bin->methods_list);
// free up interfaces list
r_list_free (bin->interfaces_list);
r_list_free (bin->attrs_list);
// TODO: XXX if a class list of all inner classes
// are formed then this will need to be updated
free (bin->cf2.flags_str);
free (bin->cf2.this_class_name);
if (bin == R_BIN_JAVA_GLOBAL_BIN) {
R_BIN_JAVA_GLOBAL_BIN = NULL;
}
free (bin->file);
free (bin);
return NULL;
}
R_API RBinJavaObj *r_bin_java_new_buf(RBuffer *buf, ut64 loadaddr, Sdb *kv) {
RBinJavaObj *bin = R_NEW0 (RBinJavaObj);
if (!bin) {
return NULL;
}
if (!r_bin_java_new_bin (bin, loadaddr, kv, buf->buf, buf->length)) {
return r_bin_java_free (bin);
}
return bin;
}
R_API void r_bin_java_attribute_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
IFDBG eprintf("Deleting attr %s, %p\n", attr->name, attr);
((RBinJavaAttrMetas *) attr->metas->type_info)->allocs->delete_obj (attr);
// free (attr->metas);
// free (attr);
}
}
R_API void r_bin_java_constant_pool(void /*RBinJavaCPTypeObj*/ *o) {
RBinJavaCPTypeObj *obj = o;
if (obj != &R_BIN_JAVA_NULL_TYPE) {
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
}
}
R_API void r_bin_java_fmtype_free(void /*RBinJavaField*/ *f) {
RBinJavaField *fm_type = f;
if (!fm_type) {
return;
}
free (fm_type->descriptor);
free (fm_type->name);
free (fm_type->flags_str);
free (fm_type->class_name);
free (fm_type->metas);
r_list_free (fm_type->attributes);
free (fm_type);
}
// Start Free the various attribute types
R_API void r_bin_java_unknown_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_local_variable_table_attr_entry_free(void /*RBinJavaLocalVariableAttribute*/ *a) {
RBinJavaLocalVariableAttribute *lvattr = a;
if (lvattr) {
free (lvattr->descriptor);
free (lvattr->name);
free (lvattr);
}
}
R_API void r_bin_java_local_variable_table_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.local_variable_table_attr.local_variable_table);
free (attr);
}
}
R_API void r_bin_java_local_variable_type_table_attr_entry_free(void /*RBinJavaLocalVariableTypeAttribute*/ *a) {
RBinJavaLocalVariableTypeAttribute *attr = a;
if (attr) {
free (attr->name);
free (attr->signature);
free (attr);
}
}
R_API void r_bin_java_local_variable_type_table_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.local_variable_type_table_attr.local_variable_table);
free (attr);
}
}
R_API void r_bin_java_deprecated_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_enclosing_methods_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr->info.enclosing_method_attr.class_name);
free (attr->info.enclosing_method_attr.method_name);
free (attr->info.enclosing_method_attr.method_descriptor);
free (attr);
}
}
R_API void r_bin_java_synthetic_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_constant_value_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_line_number_table_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.line_number_table_attr.line_number_table);
free (attr);
}
}
R_API void r_bin_java_code_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
// XXX - Intentional memory leak here. When one of the
// Code attributes is parsed, the code (the r_bin_java)
// is not properly parsing the class file
r_bin_java_stack_frame_free (attr->info.code_attr.implicit_frame);
r_list_free (attr->info.code_attr.attributes);
free (attr->info.code_attr.code);
r_list_free (attr->info.code_attr.exception_table);
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_exceptions_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr->info.exceptions_attr.exception_idx_table);
free (attr);
}
}
R_API void r_bin_java_inner_classes_attr_entry_free(void /*RBinJavaClassesAttribute*/ *a) {
RBinJavaClassesAttribute *attr = a;
if (attr) {
free (attr->name);
free (attr->flags_str);
free (attr);
}
}
R_API void r_bin_java_inner_classes_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.inner_classes_attr.classes);
free (attr);
}
}
R_API void r_bin_java_signature_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr->info.signature_attr.signature);
free (attr);
}
}
R_API void r_bin_java_source_debug_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr->info.debug_extensions.debug_extension);
free (attr);
}
}
R_API void r_bin_java_source_code_file_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_stack_map_table_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.stack_map_table_attr.stack_map_frame_entries);
free (attr);
}
}
R_API void r_bin_java_stack_frame_free(void /*RBinJavaStackMapFrame*/ *o) {
RBinJavaStackMapFrame *obj = o;
if (obj) {
r_list_free (obj->local_items);
r_list_free (obj->stack_items);
free (obj->metas);
free (obj);
}
}
R_API void r_bin_java_verification_info_free(void /*RBinJavaVerificationObj*/ *o) {
RBinJavaVerificationObj *obj = o;
// eprintf ("Freeing verification object\n");
if (obj) {
free (obj->name);
free (obj);
}
}
R_API void r_bin_java_interface_free(void /*RBinJavaInterfaceInfo*/ *o) {
RBinJavaInterfaceInfo *obj = o;
if (obj) {
free (obj->name);
free (obj);
}
}
// End Free the various attribute types
// Start the various attibute types new
R_API ut64 r_bin_java_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? ((RBinJavaAttrMetas *) attr->metas->type_info)->allocs->calc_size (attr) : 0;
}
R_API ut64 r_bin_java_unknown_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? 6 : 0;
}
R_API RBinJavaAttrInfo *r_bin_java_unknown_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
return r_bin_java_default_attr_new (buffer, sz, buf_offset);
}
R_API ut64 r_bin_java_code_attr_calc_size(RBinJavaAttrInfo *attr) {
RListIter *iter;
// RListIter *iter_tmp;
ut64 size = 0;
if (attr) {
// attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
size += 6;
// attr->info.code_attr.max_stack = R_BIN_JAVA_USHORT (buffer, 0);
size += 2;
// attr->info.code_attr.max_locals = R_BIN_JAVA_USHORT (buffer, 2);
size += 2;
// attr->info.code_attr.code_length = R_BIN_JAVA_UINT (buffer, 4);
size += 2;
if (attr->info.code_attr.code) {
size += attr->info.code_attr.code_length;
}
// attr->info.code_attr.exception_table_length = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// RBinJavaExceptionEntry *exc_entry;
// r_list_foreach_safe (attr->info.code_attr.exception_table, iter, iter_tmp, exc_entry) {
r_list_foreach_iter (attr->info.code_attr.exception_table, iter) {
// exc_entry->start_pc = R_BIN_JAVA_USHORT (buffer,offset);
size += 2;
// exc_entry->end_pc = R_BIN_JAVA_USHORT (buffer,offset);
size += 2;
// exc_entry->handler_pc = R_BIN_JAVA_USHORT (buffer,offset);
size += 2;
// exc_entry->catch_type = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
// attr->info.code_attr.attributes_count = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// RBinJavaAttrInfo *_attr;
if (attr->info.code_attr.attributes_count > 0) {
// r_list_foreach_safe (attr->info.code_attr.attributes, iter, iter_tmp, _attr) {
r_list_foreach_iter (attr->info.code_attr.attributes, iter) {
size += r_bin_java_attr_calc_size (attr);
}
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_code_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaAttrInfo *attr = NULL, *_attr = NULL;
ut32 k = 0, curpos;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
if (sz < 16 || sz > buf_offset) {// sz > buf_offset) {
free (attr);
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_CODE_ATTR;
attr->info.code_attr.max_stack = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.code_attr.max_locals = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.code_attr.code_length = R_BIN_JAVA_UINT (buffer, offset);
offset += 4;
// BUG: possible unsigned integer overflow here
attr->info.code_attr.code_offset = buf_offset + offset;
attr->info.code_attr.code = (ut8 *) malloc (attr->info.code_attr.code_length);
if (attr->info.code_attr.code == NULL) {
eprintf ("Handling Code Attributes: Unable to allocate memory "
"(%u bytes) for a code.\n", attr->info.code_attr.code_length);
return attr;
}
R_BIN_JAVA_GLOBAL_BIN->current_code_attr = attr;
{
int len = attr->info.code_attr.code_length;
memset (attr->info.code_attr.code, 0, len);
if (offset + len >= sz) {
len = sz;
return attr;
}
memcpy (attr->info.code_attr.code, buffer + offset, len);
offset += len;
}
attr->info.code_attr.exception_table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.code_attr.exception_table = r_list_newf (free);
for (k = 0; k < attr->info.code_attr.exception_table_length; k++) {
curpos = buf_offset + offset;
if (curpos + 8 > sz) {
return attr;
}
RBinJavaExceptionEntry *e = R_NEW0 (RBinJavaExceptionEntry);
if (!e) {
free (attr);
return NULL;
}
e->file_offset = curpos;
e->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
e->end_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
e->handler_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
e->catch_type = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
r_list_append (attr->info.code_attr.exception_table, e);
e->size = 8;
}
attr->info.code_attr.attributes_count = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// IFDBG eprintf (" code Attributes_count: %d\n", attr->info.code_attr.attributes_count);
// XXX - attr->info.code_attr.attributes is not freed because one of the code attributes is improperly parsed.
attr->info.code_attr.attributes = r_list_newf (r_bin_java_attribute_free);
if (attr->info.code_attr.attributes_count > 0) {
for (k = 0; k < attr->info.code_attr.attributes_count; k++) {
int size = (offset < sz) ? sz - offset : 0;
if (size > sz || size <= 0) {
break;
}
_attr = r_bin_java_read_next_attr_from_buffer (buffer + offset, size, buf_offset + offset);
if (!_attr) {
eprintf ("[X] r_bin_java_code_attr_new: Error unable to parse remainder of classfile after Method's Code Attribute: %d.\n", k);
break;
}
IFDBG eprintf("Parsing @ 0x%"PFMT64x " (%s) = 0x%"PFMT64x " bytes, %p\n", _attr->file_offset, _attr->name, _attr->size, _attr);
offset += _attr->size;
r_list_append (attr->info.code_attr.attributes, _attr);
if (_attr->type == R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TABLE_ATTR) {
IFDBG eprintf("Parsed the LocalVariableTable, preparing the implicit mthod frame.\n");
// r_bin_java_print_attr_summary(_attr);
attr->info.code_attr.implicit_frame = r_bin_java_build_stack_frame_from_local_variable_table (R_BIN_JAVA_GLOBAL_BIN, _attr);
attr->info.code_attr.implicit_frame->file_offset = buf_offset;
IFDBG r_bin_java_print_stack_map_frame_summary(attr->info.code_attr.implicit_frame);
// r_list_append (attr->info.code_attr.attributes, attr->info.code_attr.implicit_frame);
}
// if (offset > sz) {
// eprintf ("[X] r_bin_java: Error unable to parse remainder of classfile after Attribute: %d.\n", k);
// break;
// }
}
}
if (attr->info.code_attr.implicit_frame == NULL) {
// build a default implicit_frame
attr->info.code_attr.implicit_frame = r_bin_java_default_stack_frame ();
// r_list_append (attr->info.code_attr.attributes, attr->info.code_attr.implicit_frame);
}
attr->size = offset;
return attr;
}
R_API RBinJavaAttrInfo *r_bin_java_constant_value_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_CONST_VALUE_ATTR;
attr->info.constant_value_attr.constantvalue_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
}
// IFDBG r_bin_java_print_constant_value_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_constant_value_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? 8 : 0;
}
R_API RBinJavaAttrInfo *r_bin_java_deprecated_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_DEPRECATED_ATTR;
attr->size = offset;
}
// IFDBG r_bin_java_print_deprecated_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_deprecated_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? 6 : 0;
}
R_API RBinJavaAttrInfo *r_bin_java_signature_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SIGNATURE_ATTR;
// attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
// offset += 2;
attr->info.signature_attr.signature_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.signature_attr.signature = r_bin_java_get_utf8_from_bin_cp_list (
R_BIN_JAVA_GLOBAL_BIN, attr->info.signature_attr.signature_idx);
if (!attr->info.signature_attr.signature) {
eprintf ("r_bin_java_signature_attr_new: Unable to resolve the "
"Signature UTF8 String Index: 0x%02x\n", attr->info.signature_attr.signature_idx);
}
attr->size = offset;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_signature_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr == NULL) {
// TODO eprintf allocation fail
return size;
}
size += 6;
// attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// attr->info.signature_attr.signature_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_enclosing_methods_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_ENCLOSING_METHOD_ATTR;
attr->info.enclosing_method_attr.class_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.enclosing_method_attr.method_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.enclosing_method_attr.class_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.class_idx);
if (attr->info.enclosing_method_attr.class_name == NULL) {
eprintf ("Could not resolve enclosing class name for the enclosed method.\n");
}
attr->info.enclosing_method_attr.method_name = r_bin_java_get_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);
if (attr->info.enclosing_method_attr.class_name == NULL) {
eprintf ("Could not resolve method descriptor for the enclosed method.\n");
}
attr->info.enclosing_method_attr.method_descriptor = r_bin_java_get_desc_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, attr->info.enclosing_method_attr.method_idx);
if (attr->info.enclosing_method_attr.method_name == NULL) {
eprintf ("Could not resolve method name for the enclosed method.\n");
}
attr->size = offset;
return attr;
}
R_API ut64 r_bin_java_enclosing_methods_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr) {
size += 6;
// attr->info.enclosing_method_attr.class_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// attr->info.enclosing_method_attr.method_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_exceptions_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0, offset = 0;
ut64 size;
RBinJavaAttrInfo *attr = NULL;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr == NULL) {
// TODO eprintf
return attr;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;
attr->info.exceptions_attr.number_of_exceptions = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
size = sizeof (ut16) * attr->info.exceptions_attr.number_of_exceptions;
if (size < attr->info.exceptions_attr.number_of_exceptions) {
free (attr);
return NULL;
}
attr->info.exceptions_attr.exception_idx_table = (ut16 *) malloc (size);
if (!attr->info.exceptions_attr.exception_idx_table) {
free (attr);
return NULL;
}
for (i = 0; i < attr->info.exceptions_attr.number_of_exceptions; i++) {
attr->info.exceptions_attr.exception_idx_table[i] = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
}
attr->size = offset;
// IFDBG r_bin_java_print_exceptions_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_exceptions_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0, i = 0;
if (attr) {
size += 6;
for (i = 0; i < attr->info.exceptions_attr.number_of_exceptions; i++) {
// attr->info.exceptions_attr.exception_idx_table[i] = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_inner_classes_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaClassesAttribute *icattr;
RBinJavaAttrInfo *attr = NULL;
RBinJavaCPTypeObj *obj;
ut32 i = 0;
ut64 offset = 0, curpos;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr == NULL) {
// TODO eprintf
return attr;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_INNER_CLASSES_ATTR;
attr->info.inner_classes_attr.number_of_classes = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.inner_classes_attr.classes = r_list_newf (r_bin_java_inner_classes_attr_entry_free);
for (i = 0; i < attr->info.inner_classes_attr.number_of_classes; i++) {
curpos = buf_offset + offset;
if (offset + 8 > sz) {
eprintf ("Invalid amount of inner classes\n");
break;
}
icattr = R_NEW0 (RBinJavaClassesAttribute);
if (!icattr) {
break;
}
icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
icattr->flags_str = retrieve_class_method_access_string (icattr->inner_class_access_flags);
icattr->file_offset = curpos;
icattr->size = 8;
obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_name_idx);
if (obj == NULL) {
eprintf ("BINCPLIS IS HULL %d\n", icattr->inner_name_idx);
}
icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);
if (!icattr->name) {
obj = r_bin_java_get_item_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, icattr->inner_class_info_idx);
if (!obj) {
eprintf ("BINCPLIST IS NULL %d\n", icattr->inner_class_info_idx);
}
icattr->name = r_bin_java_get_item_name_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, obj);
if (!icattr->name) {
icattr->name = r_str_dup (NULL, "NULL");
eprintf ("r_bin_java_inner_classes_attr: Unable to find the name for %d index.\n", icattr->inner_name_idx);
break;
}
}
IFDBG eprintf("r_bin_java_inner_classes_attr: Inner class name %d is %s.\n", icattr->inner_name_idx, icattr->name);
r_list_append (attr->info.inner_classes_attr.classes, (void *) icattr);
}
attr->size = offset;
// IFDBG r_bin_java_print_inner_classes_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_inner_class_attr_calc_size(RBinJavaClassesAttribute *icattr) {
ut64 size = 0;
if (icattr) {
// icattr->inner_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// icattr->outer_class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// icattr->inner_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// icattr->inner_class_access_flags = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
return size;
}
R_API ut64 r_bin_java_inner_classes_attr_calc_size(RBinJavaAttrInfo *attr) {
RBinJavaClassesAttribute *icattr = NULL;
RListIter *iter;
ut64 size = 6;
if (!attr) {
return 0;
}
r_list_foreach (attr->info.inner_classes_attr.classes, iter, icattr) {
size += r_bin_java_inner_class_attr_calc_size (icattr);
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_line_number_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 curpos, offset = 0;
RBinJavaLineNumberAttribute *lnattr;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_LINE_NUMBER_TABLE_ATTR;
attr->info.line_number_table_attr.line_number_table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.line_number_table_attr.line_number_table = r_list_newf (free);
ut32 linenum_len = attr->info.line_number_table_attr.line_number_table_length;
RList *linenum_list = attr->info.line_number_table_attr.line_number_table;
if (linenum_len > sz) {
free (attr);
return NULL;
}
for (i = 0; i < linenum_len; i++) {
curpos = buf_offset + offset;
// printf ("%llx %llx \n", curpos, sz);
// XXX if (curpos + 8 >= sz) break;
lnattr = R_NEW0 (RBinJavaLineNumberAttribute);
if (!lnattr) {
break;
}
if (offset + 8 >= sz) {
break;
}
lnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lnattr->file_offset = curpos;
lnattr->size = 4;
r_list_append (linenum_list, lnattr);
}
attr->size = offset;
return attr;
}
R_API ut64 r_bin_java_line_number_table_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 6;
// RBinJavaLineNumberAttribute *lnattr;
RListIter *iter;
// RListIter *iter_tmp;
if (!attr) {
return 0LL;
}
// r_list_foreach_safe (attr->info.line_number_table_attr.line_number_table, iter, iter_tmp, lnattr) {
r_list_foreach_iter (attr->info.line_number_table_attr.line_number_table, iter) {
// lnattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lnattr->line_number = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_source_debug_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 6;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_DEBUG_EXTENTSION_ATTR;
if (attr->length == 0) {
eprintf ("r_bin_java_source_debug_attr_new: Attempting to allocate 0 bytes for debug_extension.\n");
attr->info.debug_extensions.debug_extension = NULL;
return attr;
} else if ((attr->length + offset) > sz) {
eprintf ("r_bin_java_source_debug_attr_new: Expected %d byte(s) got %"
PFMT64d " bytes for debug_extension.\n", attr->length, (offset + sz));
}
attr->info.debug_extensions.debug_extension = (ut8 *) malloc (attr->length);
if (attr->info.debug_extensions.debug_extension && (attr->length > (sz - offset))) {
memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, sz - offset);
} else if (attr->info.debug_extensions.debug_extension) {
memcpy (attr->info.debug_extensions.debug_extension, buffer + offset, attr->length);
} else {
eprintf ("r_bin_java_source_debug_attr_new: Unable to allocate the data for the debug_extension.\n");
}
offset += attr->length;
attr->size = offset;
return attr;
}
R_API ut64 r_bin_java_source_debug_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 6;
if (!attr) {
return 0LL;
}
if (attr->info.debug_extensions.debug_extension) {
size += attr->length;
}
return size;
}
R_API ut64 r_bin_java_local_variable_table_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
// ut64 offset = 0;
RListIter *iter;
// RBinJavaLocalVariableAttribute *lvattr;
if (!attr) {
return 0LL;
}
size += 6;
// attr->info.local_variable_table_attr.table_length = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// r_list_foreach (attr->info.local_variable_table_attr.local_variable_table, iter, lvattr) {
r_list_foreach_iter (attr->info.local_variable_table_attr.local_variable_table, iter) {
// lvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->length = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->name_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->descriptor_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->index = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_local_variable_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaLocalVariableAttribute *lvattr;
ut64 curpos = 0, offset = 6;
RBinJavaAttrInfo *attr;
ut32 i = 0;
if (!buffer || sz < 1) {
return NULL;
}
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TABLE_ATTR;
attr->info.local_variable_table_attr.table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.local_variable_table_attr.local_variable_table =\
r_list_newf (r_bin_java_local_variable_table_attr_entry_free);
for (i = 0; i < attr->info.local_variable_table_attr.table_length; i++) {
if (offset + 10 > sz) {
break;
}
curpos = buf_offset + offset;
lvattr = R_NEW0 (RBinJavaLocalVariableAttribute);
lvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->descriptor_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->index = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->file_offset = curpos;
lvattr->name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, lvattr->name_idx);
lvattr->size = 10;
if (!lvattr->name) {
lvattr->name = strdup ("NULL");
eprintf ("r_bin_java_local_variable_table_attr_new: Unable to find the name for %d index.\n", lvattr->name_idx);
}
lvattr->descriptor = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, lvattr->descriptor_idx);
if (!lvattr->descriptor) {
lvattr->descriptor = strdup ("NULL");
eprintf ("r_bin_java_local_variable_table_attr_new: Unable to find the descriptor for %d index.\n", lvattr->descriptor_idx);
}
r_list_append (attr->info.local_variable_table_attr.local_variable_table, lvattr);
}
attr->size = offset;
// IFDBG r_bin_java_print_local_variable_table_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_local_variable_type_table_attr_calc_size(RBinJavaAttrInfo *attr) {
// RBinJavaLocalVariableTypeAttribute *lvattr;
RListIter *iter;
ut64 size = 0;
if (attr) {
RList *list = attr->info.local_variable_type_table_attr.local_variable_table;
size += 6;
// attr->info.local_variable_type_table_attr.table_length = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// r_list_foreach (list, iter, lvattr) {
r_list_foreach_iter (list, iter) {
// lvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->length = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->name_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->signature_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// lvattr->index = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_local_variable_type_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaLocalVariableTypeAttribute *lvattr;
ut64 offset = 6;
ut32 i = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, 0);
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TYPE_TABLE_ATTR;
attr->info.local_variable_type_table_attr.table_length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.local_variable_type_table_attr.local_variable_table = r_list_newf (r_bin_java_local_variable_type_table_attr_entry_free);
for (i = 0; i < attr->info.local_variable_type_table_attr.table_length; i++) {
ut64 curpos = buf_offset + offset;
lvattr = R_NEW0 (RBinJavaLocalVariableTypeAttribute);
if (!lvattr) {
perror ("calloc");
break;
}
lvattr->start_pc = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->length = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->signature_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->index = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
lvattr->file_offset = curpos;
lvattr->name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, lvattr->name_idx);
lvattr->size = 10;
if (!lvattr->name) {
lvattr->name = strdup ("NULL");
eprintf ("r_bin_java_local_variable_type_table_attr_new: Unable to find the name for %d index.\n", lvattr->name_idx);
}
lvattr->signature = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, lvattr->signature_idx);
if (!lvattr->signature) {
lvattr->signature = strdup ("NULL");
eprintf ("r_bin_java_local_variable_type_table_attr_new: Unable to find the descriptor for %d index.\n", lvattr->signature_idx);
}
r_list_append (attr->info.local_variable_type_table_attr.local_variable_table, lvattr);
}
// IFDBG r_bin_java_print_local_variable_type_table_attr_summary(attr);
attr->size = offset;
return attr;
}
R_API RBinJavaAttrInfo *r_bin_java_source_code_file_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
if (!sz) {
return NULL;
}
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (!attr) {
return NULL;
}
attr->type = R_BIN_JAVA_ATTR_TYPE_SOURCE_FILE_ATTR;
// if (buffer + offset > buffer + sz) return NULL;
attr->info.source_file_attr.sourcefile_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->size = offset;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
return attr;
}
R_API ut64 r_bin_java_source_code_file_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? 8 : 0;
}
R_API RBinJavaAttrInfo *r_bin_java_synthetic_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
if (!attr) {
return NULL;
}
offset += 6;
attr->type = R_BIN_JAVA_ATTR_TYPE_SYNTHETIC_ATTR;
attr->size = offset;
return attr;
}
R_API ut64 r_bin_java_synthetic_attr_calc_size(RBinJavaAttrInfo *attr) {
return attr ? 12 : 6;
}
R_API RBinJavaInterfaceInfo *r_bin_java_interface_new(RBinJavaObj *bin, const ut8 *buffer, ut64 sz) {
RBinJavaInterfaceInfo *ifobj = NULL;
ifobj = R_NEW0 (RBinJavaInterfaceInfo);
IFDBG eprintf("Parsing RBinJavaInterfaceInfo\n");
if (ifobj) {
if (buffer) {
ifobj->class_info_idx = R_BIN_JAVA_USHORT (buffer, 0);
ifobj->cp_class = r_bin_java_get_item_from_bin_cp_list (bin, ifobj->class_info_idx);
if (ifobj->cp_class) {
ifobj->name = r_bin_java_get_item_name_from_bin_cp_list (bin, ifobj->cp_class);
} else {
ifobj->name = r_str_dup (NULL, "NULL");
}
ifobj->size = 2;
} else {
ifobj->class_info_idx = 0;
ifobj->name = r_str_dup (NULL, "NULL");
}
}
return ifobj;
}
R_API RBinJavaVerificationObj *r_bin_java_verification_info_from_type(RBinJavaObj *bin, R_BIN_JAVA_STACKMAP_TYPE type, ut32 value) {
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (!se) {
return NULL;
}
se->tag = type;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = (ut16) value;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
/*if (bin->offset_sz == 4) {
se->info.uninit_offset = value;
} else {
se->info.uninit_offset = (ut16) value;
}*/
se->info.uninit_offset = (ut16) value;
}
return se;
}
R_API RBinJavaVerificationObj *r_bin_java_read_from_buffer_verification_info_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaVerificationObj *se = R_NEW0 (RBinJavaVerificationObj);
if (!se) {
return NULL;
}
se->file_offset = buf_offset;
se->tag = buffer[offset];
offset += 1;
if (se->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
se->info.obj_val_cp_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
} else if (se->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
se->info.uninit_offset = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
}
if (R_BIN_JAVA_STACKMAP_UNINIT < se->tag) {
r_bin_java_verification_info_free (se);
return NULL;
}
se->size = offset;
return se;
}
R_API ut64 rbin_java_verification_info_calc_size(RBinJavaVerificationObj *se) {
ut64 sz = 1;
if (!se) {
return 0;
}
// r_buf_read_at (bin->b, offset, (ut8*)(&se->tag), 1)
switch (se->tag) {
case R_BIN_JAVA_STACKMAP_OBJECT:
// r_buf_read_at (bin->b, offset+1, (ut8*)buf, 2)
sz += 2;
break;
case R_BIN_JAVA_STACKMAP_UNINIT:
// r_buf_read_at (bin->b, offset+1, (ut8*)buf, 2)
sz += 2;
break;
}
return sz;
}
R_API RBinJavaStackMapFrameMetas *r_bin_java_determine_stack_frame_type(ut8 tag) {
ut8 type_value = 0;
if (tag < 64) {
type_value = R_BIN_JAVA_STACK_FRAME_SAME;
} else if (63 < tag && tag < 128) {
type_value = R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1;
} else if (247 < tag && tag < 251) {
type_value = R_BIN_JAVA_STACK_FRAME_CHOP;
} else if (tag == 251) {
type_value = R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED;
} else if (251 < tag && tag < 255) {
type_value = R_BIN_JAVA_STACK_FRAME_APPEND;
} else if (tag == 255) {
type_value = R_BIN_JAVA_STACK_FRAME_FULL_FRAME;
} else {
type_value = R_BIN_JAVA_STACK_FRAME_RESERVED;
}
return &R_BIN_JAVA_STACK_MAP_FRAME_METAS[type_value];
}
R_API ut64 r_bin_java_stack_map_frame_calc_size(RBinJavaStackMapFrame *sf) {
ut64 size = 0;
RListIter *iter, *iter_tmp;
RBinJavaVerificationObj *se;
if (sf) {
// sf->tag = buffer[offset];
size += 1;
switch (sf->type) {
case R_BIN_JAVA_STACK_FRAME_SAME:
// Nothing to read
break;
case R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1:
r_list_foreach_safe (sf->stack_items, iter, iter_tmp, se) {
size += rbin_java_verification_info_calc_size (se);
}
break;
case R_BIN_JAVA_STACK_FRAME_CHOP:
// sf->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
break;
case R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED:
// sf->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (sf->stack_items, iter, iter_tmp, se) {
size += rbin_java_verification_info_calc_size (se);
}
break;
case R_BIN_JAVA_STACK_FRAME_APPEND:
// sf->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (sf->stack_items, iter, iter_tmp, se) {
size += rbin_java_verification_info_calc_size (se);
}
break;
case R_BIN_JAVA_STACK_FRAME_FULL_FRAME:
// sf->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// sf->number_of_locals = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (sf->local_items, iter, iter_tmp, se) {
size += rbin_java_verification_info_calc_size (se);
}
// sf->number_of_stack_items = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (sf->stack_items, iter, iter_tmp, se) {
size += rbin_java_verification_info_calc_size (se);
}
break;
default:
eprintf ("Unknown type\n");
break;
}
}
return size;
}
R_API RBinJavaStackMapFrame *r_bin_java_stack_map_frame_new(ut8 *buffer, ut64 sz, RBinJavaStackMapFrame *p_frame, ut64 buf_offset) {
RBinJavaStackMapFrame *stack_frame = r_bin_java_default_stack_frame ();
RBinJavaVerificationObj *se = NULL;
ut64 offset = 0;
if (!stack_frame) {
return NULL;
}
stack_frame->tag = buffer[offset];
offset += 1;
stack_frame->metas->type_info = (void *) r_bin_java_determine_stack_frame_type (stack_frame->tag);
stack_frame->type = ((RBinJavaStackMapFrameMetas *) stack_frame->metas->type_info)->type;
stack_frame->file_offset = buf_offset;
stack_frame->p_stack_frame = p_frame;
switch (stack_frame->type) {
case R_BIN_JAVA_STACK_FRAME_SAME:
// Maybe? 1. Copy the previous frames locals and set the locals count.
// copy_type_info_to_stack_frame_list_up_to_idx (p_frame->local_items, stack_frame->local_items, idx);
if (p_frame) {
stack_frame->number_of_locals = p_frame->number_of_locals;
} else {
IFINT eprintf("><?><\n");
IFDBG eprintf("Unable to set previous stackframe with the number of locals (current info.code_attr.implicit_frame was probably not set :/)");
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: TODO Stack Frame Same Locals Condition is untested, so there may be issues.\n");
break;
case R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1:
// 1. Read the stack type
stack_frame->number_of_stack_items = 1;
if (offset > sz) {
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
se = r_bin_java_read_from_buffer_verification_info_new (buffer + offset, sz - offset, buf_offset + offset);
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsed R_BIN_JAVA_STACK_FRAME_SAME_LOCALS_1.\n");
if (se) {
offset += se->size;
} else {
eprintf ("r_bin_java_stack_map_frame_new: Unable to parse the Stack Items for the stack frame.\n");
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
r_list_append (stack_frame->stack_items, (void *) se);
// Maybe? 3. Copy the previous frames locals and set the locals count.
// copy_type_info_to_stack_frame_list_up_to_idx (p_frame->local_items, stack_frame->local_items, idx);
if (p_frame) {
stack_frame->number_of_locals = p_frame->number_of_locals;
} else {
IFDBG eprintf("Unable to set previous stackframe with the number of locals (current info.code_attr.implicit_frame was probably not set :/)");
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: TODO Stack Frame Same Locals 1 Stack Element Condition is untested, so there may be issues.\n");
break;
case R_BIN_JAVA_STACK_FRAME_CHOP:
// 1. Calculate the max index we want to copy from the list of the
// previous frames locals
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsing R_BIN_JAVA_STACK_FRAME_CHOP.\n");
// ut16 k = 251 - stack_frame->tag;
/*,
idx = p_frame->number_of_locals - k;
*/
// 2. read the uoffset value
stack_frame->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// Maybe? 3. Copy the previous frames locals and set the locals count.
// copy_type_info_to_stack_frame_list_up_to_idx (p_frame->local_items, stack_frame->local_items, idx);
if (p_frame) {
stack_frame->number_of_locals = p_frame->number_of_locals;
} else {
IFINT eprintf("><?><\n");
IFDBG eprintf("Unable to set previous stackframe with the number of locals (current info.code_attr.implicit_frame was probably not set :/)");
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: TODO Stack Frame Chop Condition is untested, so there may be issues.\n");
break;
case R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED:
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsing R_BIN_JAVA_STACK_FRAME_SAME_FRAME_EXTENDED.\n");
// 1. Read the uoffset
stack_frame->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// 2. Read the stack element type
stack_frame->number_of_stack_items = 1;
se = r_bin_java_read_from_buffer_verification_info_new (buffer + offset, sz - offset, buf_offset + offset);
if (se) {
offset += se->size;
} else {
eprintf ("r_bin_java_stack_map_frame_new: Unable to parse the Stack Items for the stack frame.\n");
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
r_list_append (stack_frame->stack_items, (void *) se);
// Maybe? 3. Copy the previous frames locals to the current locals
// copy_type_info_to_stack_frame_list_up_to_idx (p_frame->local_items, stack_frame->local_items, idx);
if (p_frame) {
stack_frame->number_of_locals = p_frame->number_of_locals;
} else {
IFINT eprintf("><?><\n");
IFDBG eprintf("Unable to set previous stackframe with the number of locals (current info.code_attr.implicit_frame was probably not set :/)");
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: TODO Stack Frame Same Locals Frame Stack 1 Extended Condition is untested, so there may be issues.\n");
break;
case R_BIN_JAVA_STACK_FRAME_APPEND:
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsing R_BIN_JAVA_STACK_FRAME_APPEND.\n");
// 1. Calculate the max index we want to copy from the list of the
// previous frames locals
ut16 k = stack_frame->tag - 251,
i = 0;
// 2. Read the uoffset
stack_frame->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// Maybe? 3. Copy the previous frames locals to the current locals
// copy_type_info_to_stack_frame_list_up_to_idx (p_frame->local_items, stack_frame->local_items, idx);
// 4. Read off the rest of the appended locals types
for (i = 0; i < k; i++) {
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsing verifying the k'th frame: %d of %d.\n", i, k);
se = r_bin_java_read_from_buffer_verification_info_new (buffer + offset, sz - offset, buf_offset + offset);
IFDBG eprintf("r_bin_java_stack_map_frame_new: Completed Parsing\n");
if (se) {
offset += se->size;
} else {
eprintf ("r_bin_java_stack_map_frame_new: Unable to parse the locals for the stack frame.\n");
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
r_list_append (stack_frame->local_items, (void *) se);
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: Breaking out of loop");
IFDBG eprintf("p_frame: %p\n", p_frame);
if (p_frame) {
stack_frame->number_of_locals = p_frame->number_of_locals + k;
} else {
IFINT eprintf("><?><\n");
IFDBG eprintf("Unable to set previous stackframe with the number of locals (current info.code_attr.implicit_frame was probably not set :/)");
}
IFDBG eprintf("r_bin_java_stack_map_frame_new: TODO Stack Frame Same Locals Frame Stack 1 Extended Condition is untested, so there may be issues.\n");
break;
case R_BIN_JAVA_STACK_FRAME_FULL_FRAME:
IFDBG eprintf("r_bin_java_stack_map_frame_new: Parsing R_BIN_JAVA_STACK_FRAME_FULL_FRAME.\n");
stack_frame->offset_delta = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// IFDBG eprintf ("r_bin_java_stack_map_frame_new: Code Size > 65535, read(%d byte(s)), offset = 0x%08x.\n", var_sz, stack_frame->offset_delta);
// Read the number of variables based on the max # local variable
stack_frame->number_of_locals = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// IFDBG eprintf ("r_bin_java_stack_map_frame_new: Max ulocalvar > 65535, read(%d byte(s)), number_of_locals = 0x%08x.\n", var_sz, stack_frame->number_of_locals);
IFDBG r_bin_java_print_stack_map_frame_summary(stack_frame);
// read the number of locals off the stack
for (i = 0; i < stack_frame->number_of_locals; i++) {
se = r_bin_java_read_from_buffer_verification_info_new (buffer + offset, sz - offset, buf_offset + offset);
if (se) {
offset += se->size;
// r_list_append (stack_frame->local_items, (void *) se);
} else {
eprintf ("r_bin_java_stack_map_frame_new: Unable to parse the locals for the stack frame.\n");
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
r_list_append (stack_frame->local_items, (void *) se);
}
// Read the number of stack items based on the max size of stack
stack_frame->number_of_stack_items = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// IFDBG eprintf ("r_bin_java_stack_map_frame_new: Max ustack items > 65535, read(%d byte(s)), number_of_locals = 0x%08x.\n", var_sz, stack_frame->number_of_stack_items);
// read the stack items
for (i = 0; i < stack_frame->number_of_stack_items; i++) {
se = r_bin_java_read_from_buffer_verification_info_new (buffer + offset, sz - offset, buf_offset + offset);
if (se) {
offset += se->size;
// r_list_append (stack_frame->stack_items, (void *) se);
} else {
eprintf ("r_bin_java_stack_map_frame_new: Unable to parse the stack items for the stack frame.\n");
r_bin_java_stack_frame_free (stack_frame);
return NULL;
}
r_list_append (stack_frame->local_items, (void *) se);
}
break;
default:
eprintf ("java: Unknown type\n");
break;
}
// IFDBG eprintf ("Created a stack frame at offset(0x%08"PFMT64x") of size: %d\n", buf_offset, stack_frame->size);//r_bin_java_print_stack_map_frame_summary(stack_frame);
stack_frame->size = offset;
// IFDBG r_bin_java_print_stack_map_frame_summary(stack_frame);
return stack_frame;
}
R_API ut16 r_bin_java_find_cp_class_ref_from_name_idx(RBinJavaObj *bin, ut16 name_idx) {
ut16 pos, len = (ut16) r_list_length (bin->cp_list);
RBinJavaCPTypeObj *item;
for (pos = 0; pos < len; pos++) {
item = (RBinJavaCPTypeObj *) r_list_get_n (bin->cp_list, pos);
if (item && item->tag == R_BIN_JAVA_CP_CLASS && item->info.cp_class.name_idx == name_idx) {
break;
}
}
return (pos != len) ? pos : 0;
}
R_API RBinJavaStackMapFrame *r_bin_java_default_stack_frame() {
RBinJavaStackMapFrame *sf = R_NEW0 (RBinJavaStackMapFrame);
if (!sf) {
return NULL;
}
sf->metas = R_NEW0 (RBinJavaMetaInfo);
if (!sf->metas) {
free (sf);
return NULL;
}
sf->metas->type_info = (void *) &R_BIN_JAVA_STACK_MAP_FRAME_METAS[R_BIN_JAVA_STACK_FRAME_IMPLICIT];
sf->type = ((RBinJavaStackMapFrameMetas *) sf->metas->type_info)->type;
sf->local_items = r_list_newf (r_bin_java_verification_info_free);
sf->stack_items = r_list_newf (r_bin_java_verification_info_free);
sf->number_of_stack_items = 0;
sf->number_of_locals = 0;
return sf;
}
R_API RBinJavaStackMapFrame *r_bin_java_build_stack_frame_from_local_variable_table(RBinJavaObj *bin, RBinJavaAttrInfo *attr) {
RBinJavaStackMapFrame *sf = r_bin_java_default_stack_frame ();
RBinJavaLocalVariableAttribute *lvattr = NULL;
RBinJavaVerificationObj *type_item;
RListIter *iter = NULL;
ut32 value_cnt = 0;
ut8 value;
if (!sf || !bin || !attr || attr->type != R_BIN_JAVA_ATTR_TYPE_LOCAL_VARIABLE_TABLE_ATTR) {
eprintf ("Attempting to create a stack_map frame from a bad attribute.\n");
return sf;
}
sf->number_of_locals = attr->info.local_variable_table_attr.table_length;
r_list_foreach (attr->info.local_variable_table_attr.local_variable_table, iter, lvattr) {
ut32 pos = 0;
// knock the array Types
while (lvattr->descriptor[pos] == '[') {
pos++;
}
value = lvattr->descriptor[pos];
// IFDBG eprintf ("Found the following type value: %c at pos %d in %s\n", value, pos, lvattr->descriptor);
switch (value) {
case 'I':
case 'Z':
case 'S':
case 'B':
case 'C':
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_INTEGER, 0);
break;
case 'F':
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_FLOAT, 0);
break;
case 'D':
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_DOUBLE, 0);
break;
case 'J':
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_LONG, 0);
break;
case 'L':
// TODO: FIXME write something that will iterate over the CP Pool and find the
// CONSTANT_Class_info referencing this
{
ut16 idx = r_bin_java_find_cp_class_ref_from_name_idx (bin, lvattr->name_idx);
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_OBJECT, idx);
}
break;
default:
eprintf ("r_bin_java_build_stack_frame_from_local_variable_table: "
"not sure how to handle: name: %s, type: %s\n", lvattr->name, lvattr->descriptor);
type_item = r_bin_java_verification_info_from_type (bin, R_BIN_JAVA_STACKMAP_NULL, 0);
}
if (type_item) {
r_list_append (sf->local_items, (void *) type_item);
}
value_cnt++;
}
if (value_cnt != attr->info.local_variable_table_attr.table_length) {
IFDBG eprintf("r_bin_java_build_stack_frame_from_local_variable_table: "
"Number of locals not accurate. Expected %d but got %d",
attr->info.local_variable_table_attr.table_length, value_cnt);
}
return sf;
}
R_API ut64 r_bin_java_stack_map_table_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
RListIter *iter, *iter_tmp;
RBinJavaStackMapFrame *sf;
if (attr) {
// attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
size += 6;
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
// Current spec does not call for variable sizes.
// attr->info.stack_map_table_attr.number_of_entries = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (attr->info.stack_map_table_attr.stack_map_frame_entries, iter, iter_tmp, sf) {
size += r_bin_java_stack_map_frame_calc_size (sf);
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_stack_map_table_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 offset = 0;
RBinJavaStackMapFrame *stack_frame = NULL, *new_stack_frame = NULL;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
IFDBG eprintf("r_bin_java_stack_map_table_attr_new: New stack map allocated.\n");
if (!attr) {
return NULL;
}
attr->info.stack_map_table_attr.stack_map_frame_entries = r_list_newf (r_bin_java_stack_frame_free);
// IFDBG r_bin_java_print_source_code_file_attr_summary(attr);
// Current spec does not call for variable sizes.
attr->info.stack_map_table_attr.number_of_entries = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
IFDBG eprintf("r_bin_java_stack_map_table_attr_new: Processing stack map, summary is:\n");
IFDBG r_bin_java_print_stack_map_table_attr_summary(attr);
for (i = 0; i < attr->info.stack_map_table_attr.number_of_entries; i++) {
// read next stack frame
IFDBG eprintf("Reading StackMap Entry #%d @ 0x%08"PFMT64x "\n", i, buf_offset + offset);
if (stack_frame == NULL && R_BIN_JAVA_GLOBAL_BIN && R_BIN_JAVA_GLOBAL_BIN->current_code_attr) {
IFDBG eprintf("Setting an implicit frame at #%d @ 0x%08"PFMT64x "\n", i, buf_offset + offset);
stack_frame = R_BIN_JAVA_GLOBAL_BIN->current_code_attr->info.code_attr.implicit_frame;
}
IFDBG eprintf("Reading StackMap Entry #%d @ 0x%08"PFMT64x ", current stack_frame: %p\n", i, buf_offset + offset, stack_frame);
if (offset > sz) {
r_bin_java_stack_map_table_attr_free (attr);
return NULL;
}
new_stack_frame = r_bin_java_stack_map_frame_new (buffer + offset, sz - offset, stack_frame, buf_offset + offset);
if (new_stack_frame) {
offset += new_stack_frame->size;
// append stack frame to the list
r_list_append (attr->info.stack_map_table_attr.stack_map_frame_entries, (void *) new_stack_frame);
stack_frame = new_stack_frame;
} else {
eprintf ("r_bin_java_stack_map_table_attr_new: Unable to parse the stack frame for the stack map table.\n");
r_bin_java_stack_map_table_attr_free (attr);
attr = NULL;
break;
}
}
if (attr) {
attr->size = offset;
}
return attr;
}
// End attribute types new
// Start new Constant Pool Types
R_API RBinJavaCPTypeObj *r_bin_java_do_nothing_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
return (RBinJavaCPTypeObj *) NULL;
}
R_API ut64 r_bin_java_do_nothing_calc_size(RBinJavaCPTypeObj *obj) {
return 0;
}
R_API void r_bin_java_do_nothing_free(void /*RBinJavaCPTypeObj*/ *obj) {
return;
}
R_API RBinJavaCPTypeObj *r_bin_java_unknown_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
obj = (RBinJavaCPTypeObj *) malloc (sizeof (RBinJavaCPTypeObj));
if (obj) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[R_BIN_JAVA_CP_UNKNOWN];
}
return obj;
}
R_API ut64 r_bin_java_unknown_cp_calc_size(RBinJavaCPTypeObj *obj) {
return 1LL;
}
R_API RBinJavaCPTypeObj *r_bin_java_class_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_CLASS, tag, sz, "Class");
if (quick_check > 0) {
return NULL;
}
RBinJavaCPTypeObj *obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->info.cp_class.name_idx = R_BIN_JAVA_USHORT (buffer, 1);
}
return obj;
}
R_API ut64 r_bin_java_class_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// ut8 tag = buffer[0];
size += 1;
// obj->info.cp_class.name_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_fieldref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_FIELDREF, tag, sz, "FieldRef");
if (quick_check > 0) {
return obj;
}
obj = (RBinJavaCPTypeObj *) malloc (sizeof (RBinJavaCPTypeObj));
if (obj) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->info.cp_field.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_field.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
}
return (RBinJavaCPTypeObj *) obj;
}
R_API ut64 r_bin_java_fieldref_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_field.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
// obj->info.cp_field.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_methodref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_METHODREF, tag, sz, "MethodRef");
if (quick_check > 0) {
return obj;
}
obj = (RBinJavaCPTypeObj *) malloc (sizeof (RBinJavaCPTypeObj));
if (obj) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->info.cp_method.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_method.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
}
return obj;
}
R_API ut64 r_bin_java_methodref_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_method.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
// obj->info.cp_method.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_interfacemethodref_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_INTERFACEMETHOD_REF, tag, sz, "InterfaceMethodRef");
if (quick_check > 0) {
return NULL;
}
RBinJavaCPTypeObj *obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
obj->info.cp_interface.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_interface.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
}
return obj;
}
R_API ut64 r_bin_java_interfacemethodref_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_interface.class_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
// obj->info.cp_interface.name_and_type_idx = R_BIN_JAVA_USHORT (buffer, 3);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_string_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_STRING, tag, sz, "String");
if (quick_check > 0) {
return NULL;
}
RBinJavaCPTypeObj *obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
}
return obj;
}
R_API ut64 r_bin_java_string_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_integer_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_INTEGER, tag, sz, "Integer");
if (quick_check > 0) {
return obj;
}
obj = (RBinJavaCPTypeObj *) R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
memset (&obj->info.cp_integer.bytes, 0, sizeof (obj->info.cp_integer.bytes));
memcpy (&obj->info.cp_integer.bytes.raw, buffer + 1, 4);
}
return obj;
}
R_API ut64 r_bin_java_integer_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 4;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_float_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_FLOAT, tag, sz, "Float");
if (quick_check > 0) {
return obj;
}
obj = (RBinJavaCPTypeObj *) calloc (1, sizeof (RBinJavaCPTypeObj));
if (obj) {
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
memset (&obj->info.cp_float.bytes, 0, sizeof (obj->info.cp_float.bytes));
memcpy (&obj->info.cp_float.bytes.raw, buffer, 4);
}
return (RBinJavaCPTypeObj *) obj;
}
R_API ut64 r_bin_java_float_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 4;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_long_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_LONG, tag, sz, "Long");
if (quick_check > 0) {
return obj;
}
obj = (RBinJavaCPTypeObj *) malloc (sizeof (RBinJavaCPTypeObj));
if (obj) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
memset (&obj->info.cp_long.bytes, 0, sizeof (obj->info.cp_long.bytes));
memcpy (&(obj->info.cp_long.bytes), buffer + 1, 8);
}
return obj;
}
R_API ut64 r_bin_java_long_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 8;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_double_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_DOUBLE, tag, sz, "Double");
if (quick_check > 0) {
return (RBinJavaCPTypeObj *) obj;
}
obj = (RBinJavaCPTypeObj *) malloc (sizeof (RBinJavaCPTypeObj));
if (obj) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
memset (&obj->info.cp_double.bytes, 0, sizeof (obj->info.cp_double.bytes));
memcpy (&obj->info.cp_double.bytes, buffer + 1, 8);
}
return obj;
}
R_API ut64 r_bin_java_double_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
// tag
size += 1;
// obj->info.cp_string.string_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 8;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_utf8_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj;
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_UTF8, tag, sz, "Utf8");
if (quick_check > 0) {
return NULL;
}
if ((obj = R_NEW0 (RBinJavaCPTypeObj))) {
memset (obj, 0, sizeof (RBinJavaCPTypeObj));
obj->tag = tag;
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);
obj->info.cp_utf8.length = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_utf8.bytes = (ut8 *) malloc (obj->info.cp_utf8.length + 1);
if (obj->info.cp_utf8.bytes) {
memset (obj->info.cp_utf8.bytes, 0, obj->info.cp_utf8.length + 1);
if (obj->info.cp_utf8.length < (sz - 3)) {
memcpy (obj->info.cp_utf8.bytes, buffer + 3, (sz - 3));
obj->info.cp_utf8.length = sz - 3;
} else {
memcpy (obj->info.cp_utf8.bytes, buffer + 3, obj->info.cp_utf8.length);
}
obj->value = obj->info.cp_utf8.bytes;
} else {
r_bin_java_obj_free (obj);
obj = NULL;
}
}
return obj;
}
R_API ut64 r_bin_java_utf8_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
size += 1;
if (obj && R_BIN_JAVA_CP_UTF8 == obj->tag) {
size += 2;
size += obj->info.cp_utf8.length;
}
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_name_and_type_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj = NULL;
int quick_check = 0;
quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_NAMEANDTYPE, tag, sz, "RBinJavaCPTypeNameAndType");
if (quick_check > 0) {
return obj;
}
obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);;
obj->tag = tag;
obj->info.cp_name_and_type.name_idx = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_name_and_type.descriptor_idx = R_BIN_JAVA_USHORT (buffer, 3);
}
return obj;
}
R_API ut64 r_bin_java_name_and_type_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
if (obj) {
size += 1;
// obj->info.cp_name_and_type.name_idx = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
// obj->info.cp_name_and_type.descriptor_idx = R_BIN_JAVA_USHORT (buffer, 3);
size += 2;
}
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_methodtype_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_METHODTYPE, tag, sz, "RBinJavaCPTypeMethodType");
if (quick_check > 0) {
return NULL;
}
RBinJavaCPTypeObj *obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);;
obj->tag = tag;
obj->info.cp_method_type.descriptor_index = R_BIN_JAVA_USHORT (buffer, 1);
}
return obj;
}
R_API ut64 r_bin_java_methodtype_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
size += 1;
// obj->info.cp_method_type.descriptor_index = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_methodhandle_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_METHODHANDLE, tag, sz, "RBinJavaCPTypeMethodHandle");
if (quick_check > 0) {
return NULL;
}
RBinJavaCPTypeObj *obj = R_NEW0 (RBinJavaCPTypeObj);
if (obj) {
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);;
obj->tag = tag;
obj->info.cp_method_handle.reference_kind = buffer[1];
obj->info.cp_method_handle.reference_index = R_BIN_JAVA_USHORT (buffer, 2);
}
return obj;
}
R_API ut64 r_bin_java_methodhandle_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
size += 1;
// obj->info.cp_method_handle.reference_index = R_BIN_JAVA_USHORT (buffer, 2);
size += 2;
return size;
}
R_API RBinJavaCPTypeObj *r_bin_java_invokedynamic_cp_new(RBinJavaObj *bin, ut8 *buffer, ut64 sz) {
ut8 tag = buffer[0];
RBinJavaCPTypeObj *obj;
int quick_check = r_bin_java_quick_check (R_BIN_JAVA_CP_INVOKEDYNAMIC, tag, sz, "RBinJavaCPTypeMethodHandle");
if (quick_check > 0) {
return NULL;
}
if ((obj = R_NEW0 (RBinJavaCPTypeObj))) {
obj->metas = R_NEW0 (RBinJavaMetaInfo);
obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
obj->name = r_str_dup (NULL, (const char *) R_BIN_JAVA_CP_METAS[tag].name);;
obj->tag = tag;
obj->info.cp_invoke_dynamic.bootstrap_method_attr_index = R_BIN_JAVA_USHORT (buffer, 1);
obj->info.cp_invoke_dynamic.name_and_type_index = R_BIN_JAVA_USHORT (buffer, 3);
}
return obj;
}
R_API int r_bin_java_check_reset_cp_obj(RBinJavaCPTypeObj *cp_obj, ut8 tag) {
bool res = false;
if (tag < R_BIN_JAVA_CP_METAS_SZ) {
if (tag != cp_obj->tag) {
if (cp_obj->tag == R_BIN_JAVA_CP_UTF8) {
free (cp_obj->info.cp_utf8.bytes);
cp_obj->info.cp_utf8.bytes = NULL;
cp_obj->info.cp_utf8.length = 0;
free (cp_obj->name);
cp_obj->name = NULL;
res = true;
}
cp_obj->tag = tag;
cp_obj->metas->type_info = (void *) &R_BIN_JAVA_CP_METAS[tag];
cp_obj->name = strdup (R_BIN_JAVA_CP_METAS[tag].name);
res = true;
} else {
eprintf ("Invalid tag\n");
}
} else {
eprintf ("Invalid tag '%d'.\n", tag);
}
return res;
}
R_API ut8 *r_bin_java_cp_get_4bytes(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len) {
ut8 *buffer = malloc (5);
if (!buffer) {
return NULL;
}
ut32 val = 0;
if (!buffer || len < 4) {
if (out_sz) {
*out_sz = 0;
}
free (buffer);
return NULL;
}
buffer[0] = tag;
val = R_BIN_JAVA_UINT (buf, 0);
memcpy (buffer + 1, (const char *) &val, 4);
*out_sz = 5;
return buffer;
}
R_API ut8 *r_bin_java_cp_get_8bytes(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len) {
ut8 *buffer = malloc (10);
if (!buffer) {
return NULL;
}
ut64 val = 0;
if (len < 8) {
*out_sz = 0;
free (buffer);
return NULL;
}
buffer[0] = tag;
val = r_bin_java_raw_to_long (buf, 0);
memcpy (buffer + 1, (const char *) &val, 8);
*out_sz = 9;
return buffer;
}
R_API ut8 *r_bin_java_cp_append_classref_and_name(RBinJavaObj *bin, ut32 *out_sz, const char *classname, const ut32 classname_len) {
ut16 use_name_idx = bin->cp_idx + 1;
ut8 *bytes = NULL, *name_bytes = NULL;
name_bytes = r_bin_java_cp_get_utf8 (R_BIN_JAVA_CP_UTF8, out_sz, (const ut8 *) classname, classname_len);
if (*out_sz > 0 && name_bytes) {
ut8 *idx_addr = (ut8 *) &use_name_idx;
bytes = malloc (*out_sz + 3);
memcpy (bytes, name_bytes, *out_sz);
bytes[*out_sz + 0] = R_BIN_JAVA_CP_CLASS;
bytes[*out_sz + 1] = idx_addr[1];
bytes[*out_sz + 2] = idx_addr[0];
*out_sz += 3;
}
free (name_bytes);
return bytes;
}
R_API ut8 *r_bin_java_cp_get_fref_bytes(RBinJavaObj *bin, ut32 *out_sz, ut8 tag, ut16 cn_idx, ut16 fn_idx, ut16 ft_idx) {
ut8 *bytes = NULL, *fnt_bytes = NULL;
RBinJavaCPTypeObj *ref_cp_obj = NULL;
ut16 fnt_idx = 0, cref_idx = 0;
ut32 fnt_len = 0;
ut16 ref_cp_obj_idx = r_bin_java_find_cp_class_ref_from_name_idx (bin, cn_idx);
if (!ref_cp_obj_idx) {
return NULL;
}
ref_cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, ref_cp_obj_idx);
if (ref_cp_obj) {
cref_idx = ref_cp_obj->idx;
}
ref_cp_obj = r_bin_java_find_cp_name_and_type_info (bin, fn_idx, ft_idx);
if (ref_cp_obj) {
fnt_idx = ref_cp_obj->idx;
} else {
fnt_bytes = r_bin_java_cp_get_name_type (bin, &fnt_len, fn_idx, ft_idx);
fnt_idx = bin->cp_idx + 1;
}
if (cref_idx && fnt_idx) {
bytes = r_bin_java_cp_get_fm_ref (bin, out_sz, tag, cref_idx, fnt_idx);
if (fnt_bytes) {
ut8 *tbuf = malloc (fnt_len + *out_sz);
if (!tbuf) {
free (bytes);
free (fnt_bytes);
return NULL;
}
// copy the bytes to the new buffer
memcpy (tbuf, fnt_bytes, fnt_len);
memcpy (tbuf + fnt_len, bytes, *out_sz);
// update the values free old buffer
*out_sz += fnt_len;
free (bytes);
bytes = tbuf;
}
}
free (fnt_bytes);
return bytes;
}
R_API ut8 *r_bin_java_cp_get_classref(RBinJavaObj *bin, ut32 *out_sz, const char *classname, const ut32 classname_len, const ut16 name_idx) {
ut16 use_name_idx = -1;
ut8 *bytes = NULL;
if (name_idx == (ut16) - 1 && classname && *classname && classname_len > 0) {
// find class_name_idx by class name
RList *results = r_bin_java_find_cp_const_by_val_utf8 (bin, (const ut8 *) classname, classname_len);
if (r_list_length (results) == 1) {
use_name_idx = (ut16) * ((ut32 *) r_list_get_n (results, 0));
}
r_list_free (results);
} else if (name_idx != (ut16) - 1 && name_idx != 0) {
use_name_idx = name_idx;
}
if (use_name_idx == (ut16) - 1 && classname && *classname && classname_len > 0) {
bytes = r_bin_java_cp_append_classref_and_name (bin, out_sz, classname, classname_len);
} else if (use_name_idx != (ut16) - 1) {
ut8 *idx_addr = (ut8 *) &use_name_idx;
bytes = malloc (3);
if (!bytes) {
return NULL;
}
bytes[0] = R_BIN_JAVA_CP_CLASS;
bytes[1] = idx_addr[1];
bytes[2] = idx_addr[0];
*out_sz += 3;
}
return bytes;
}
R_API ut8 *r_bin_java_cp_get_fm_ref(RBinJavaObj *bin, ut32 *out_sz, ut8 tag, ut16 class_idx, ut16 name_and_type_idx) {
return r_bin_java_cp_get_2_ut16 (bin, out_sz, tag, class_idx, name_and_type_idx);
}
R_API ut8 *r_bin_java_cp_get_2_ut16(RBinJavaObj *bin, ut32 *out_sz, ut8 tag, ut16 ut16_one, ut16 ut16_two) {
ut8 *bytes = malloc (7);
if (!bytes) {
return NULL;
}
ut8 *idx_addr = NULL;
bytes[*out_sz] = tag;
*out_sz += 1;
idx_addr = (ut8 *) &ut16_one;
bytes[*out_sz + 1] = idx_addr[1];
bytes[*out_sz + 2] = idx_addr[0];
*out_sz += 3;
idx_addr = (ut8 *) &ut16_two;
bytes[*out_sz + 1] = idx_addr[1];
bytes[*out_sz + 2] = idx_addr[0];
*out_sz += 3;
return bytes;
}
R_API ut8 *r_bin_java_cp_get_name_type(RBinJavaObj *bin, ut32 *out_sz, ut16 name_idx, ut16 type_idx) {
return r_bin_java_cp_get_2_ut16 (bin, out_sz, R_BIN_JAVA_CP_NAMEANDTYPE, name_idx, type_idx);
}
R_API ut8 *r_bin_java_cp_get_utf8(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len) {
ut8 *buffer = NULL;
ut16 sz = 0;
ut16 t = (ut16) len;
if (len > 0 && len > (ut16) - 1) {
*out_sz = 0;
return NULL;
}
sz = R_BIN_JAVA_USHORT (((ut8 *) (ut16 *) &t), 0);
*out_sz = 3 + t; // tag + sz + bytes
buffer = malloc (*out_sz + 3);
if (!buffer) {
return NULL;
}
// XXX - excess bytes are created to ensure null for string operations.
memset (buffer, 0, *out_sz + 3);
buffer[0] = tag;
memcpy (buffer + 1, (const char *) &sz, 2);
memcpy (buffer + 3, buf, *out_sz - 3);
return buffer;
}
R_API ut64 r_bin_java_invokedynamic_cp_calc_size(RBinJavaCPTypeObj *obj) {
ut64 size = 0;
size += 1;
// obj->info.cp_invoke_dynamic.bootstrap_method_attr_index = R_BIN_JAVA_USHORT (buffer, 1);
size += 2;
// obj->info.cp_invoke_dynamic.name_and_type_index = R_BIN_JAVA_USHORT (buffer, 3);
size += 2;
return size;
}
// End new Constant Pool types
// Start free Constant Pool types
R_API void r_bin_java_default_free(void /* RBinJavaCPTypeObj*/ *o) {
RBinJavaCPTypeObj *obj = o;
if (obj) {
free (obj->metas);
free (obj->name);
free (obj->value);
free (obj);
}
}
R_API void r_bin_java_utf8_info_free(void /* RBinJavaCPTypeObj*/ *o) {
RBinJavaCPTypeObj *obj = o;
if (obj) {
free (obj->name);
free (obj->metas);
free (obj->info.cp_utf8.bytes);
free (obj);
}
}
// Deallocs for type objects
R_API void r_bin_java_obj_free(void /*RBinJavaCPTypeObj*/ *o) {
RBinJavaCPTypeObj *obj = o;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
}
R_API void r_bin_java_print_attr_summary(RBinJavaAttrInfo *attr) {
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *.\n");
return;
}
((RBinJavaAttrMetas *) attr->metas->type_info)->allocs->print_summary (attr);
}
R_API void r_bin_java_print_source_debug_attr_summary(RBinJavaAttrInfo *attr) {
ut32 i = 0;
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaSourceDebugExtensionAttr *.\n");
return;
}
Eprintf ("Source Debug Extension Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Extension Length: %d\n", attr->length);
Eprintf (" Source Debug Extension value: \n");
for (i = 0; i < attr->length; i++) {
Eprintf ("%c", attr->info.debug_extensions.debug_extension[i]);
}
Eprintf ("\n Source Debug Extension End\n");
}
R_API void r_bin_java_print_unknown_attr_summary(RBinJavaAttrInfo *attr) {
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Unknown.\n");
return;
}
Eprintf ("Unknown Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
}
R_API void r_bin_java_print_code_exceptions_attr_summary(RBinJavaExceptionEntry *exc_entry) {
if (exc_entry == NULL) {
eprintf ("Attempting to print an invalid RBinJavaExceptionEntry *.\n");
return;
}
Eprintf (" Exception Table Entry Information\n");
Eprintf (" offset: 0x%08"PFMT64x"\n", exc_entry->file_offset);
Eprintf (" catch_type: %d\n", exc_entry->catch_type);
Eprintf (" start_pc: 0x%04x\n", exc_entry->start_pc);
Eprintf (" end_pc: 0x%04x\n", exc_entry->end_pc);
Eprintf (" handler_pc: 0x%04x\n", exc_entry->handler_pc);
}
// End free Constant Pool types
R_API void r_bin_java_print_code_attr_summary(RBinJavaAttrInfo *attr) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaExceptionEntry *exc_entry = NULL;
RBinJavaAttrInfo *_attr = NULL;
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Code.\n");
return;
}
Eprintf ("Code Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d, Attribute Count: %d\n", attr->length, attr->info.code_attr.attributes_count);
Eprintf (" Max Stack: %d\n", attr->info.code_attr.max_stack);
Eprintf (" Max Locals: %d\n", attr->info.code_attr.max_locals);
Eprintf (" Code Length: %d\n", attr->info.code_attr.code_length);
Eprintf (" Code At Offset: 0x%08"PFMT64x "\n", (ut64) attr->info.code_attr.code_offset);
Eprintf ("Code Attribute Exception Table Information:\n");
Eprintf (" Exception Table Length: %d\n", attr->info.code_attr.exception_table_length);
if (attr->info.code_attr.exception_table) {
// Delete the attr entries
r_list_foreach_safe (attr->info.code_attr.exception_table, iter, iter_tmp, exc_entry) {
r_bin_java_print_code_exceptions_attr_summary (exc_entry);
}
}
Eprintf (" Implicit Method Stack Frame:\n");
r_bin_java_print_stack_map_frame_summary (attr->info.code_attr.implicit_frame);
Eprintf ("Code Attribute Attributes Information:\n");
if (attr->info.code_attr.attributes && attr->info.code_attr.attributes_count > 0) {
Eprintf (" Code Attribute Attributes Count: %d\n", attr->info.code_attr.attributes_count);
r_list_foreach_safe (attr->info.code_attr.attributes, iter, iter_tmp, _attr) {
r_bin_java_print_attr_summary (_attr);
}
}
}
R_API void r_bin_java_print_constant_value_attr_summary(RBinJavaAttrInfo *attr) {
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *ConstantValue.\n");
return;
}
Eprintf ("Constant Value Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" ConstantValue Index: %d\n", attr->info.constant_value_attr.constantvalue_idx);
}
R_API void r_bin_java_print_deprecated_attr_summary(RBinJavaAttrInfo *attr) {
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Deperecated.\n");
return;
}
Eprintf ("Deperecated Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
}
R_API void r_bin_java_print_enclosing_methods_attr_summary(RBinJavaAttrInfo *attr) {
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Deperecated.\n");
return;
}
Eprintf ("Enclosing Method Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" Class Info Index : 0x%02x\n", attr->info.enclosing_method_attr.class_idx);
Eprintf (" Method Name and Type Index : 0x%02x\n", attr->info.enclosing_method_attr.method_idx);
Eprintf (" Class Name : %s\n", attr->info.enclosing_method_attr.class_name);
Eprintf (" Method Name and Desc : %s %s\n", attr->info.enclosing_method_attr.method_name, attr->info.enclosing_method_attr.method_descriptor);
}
R_API void r_bin_java_print_exceptions_attr_summary(RBinJavaAttrInfo *attr) {
ut32 i = 0;
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Exceptions.\n");
return;
}
Eprintf ("Exceptions Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
for (i = 0; i < attr->info.exceptions_attr.number_of_exceptions; i++) {
Eprintf (" Exceptions Attribute Index[%d]: %d\n", i, attr->info.exceptions_attr.exception_idx_table[i]);
}
}
R_API void r_bin_java_print_classes_attr_summary(RBinJavaClassesAttribute *icattr) {
if (!icattr) {
eprintf ("Attempting to print an invalid RBinJavaClassesAttribute* (InnerClasses element).\n");
return;
}
eprintf (" Inner Classes Class Attribute Offset: 0x%08"PFMT64x "\n", icattr->file_offset);
eprintf (" Inner Classes Class Attribute Class Name (%d): %s\n", icattr->inner_name_idx, icattr->name);
eprintf (" Inner Classes Class Attribute Class inner_class_info_idx: %d\n", icattr->inner_class_info_idx);
eprintf (" Inner Classes Class Attribute Class inner_class_access_flags: 0x%02x %s\n", icattr->inner_class_access_flags, icattr->flags_str);
eprintf (" Inner Classes Class Attribute Class outer_class_info_idx: %d\n", icattr->outer_class_info_idx);
eprintf (" Inner Classes Class Field Information:\n");
r_bin_java_print_field_summary (icattr->clint_field);
eprintf (" Inner Classes Class Field Information:\n");
r_bin_java_print_field_summary (icattr->clint_field);
eprintf (" Inner Classes Class Attr Info Information:\n");
r_bin_java_print_attr_summary (icattr->clint_attr);
}
R_API void r_bin_java_print_inner_classes_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaClassesAttribute *icattr;
RListIter *iter, *iter_tmp;
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *InnerClasses.\n");
return;
}
Eprintf ("Inner Classes Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
r_list_foreach_safe (attr->info.inner_classes_attr.classes, iter, iter_tmp, icattr) {
r_bin_java_print_classes_attr_summary (icattr);
}
}
R_API void r_bin_java_print_line_number_attr_summary(RBinJavaLineNumberAttribute *lnattr) {
if (!lnattr) {
eprintf ("Attempting to print an invalid RBinJavaLineNumberAttribute *.\n");
return;
}
Eprintf (" Line Number Attribute Offset: 0x%08"PFMT64x "\n", lnattr->file_offset);
Eprintf (" Line Number Attribute StartPC: %d\n", lnattr->start_pc);
Eprintf (" Line Number Attribute LineNumber: %d\n", lnattr->line_number);
}
R_API void r_bin_java_print_line_number_table_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaLineNumberAttribute *lnattr;
RListIter *iter, *iter_tmp;
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *LineNumberTable.\n");
return;
}
Eprintf ("Line Number Table Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
r_list_foreach_safe (attr->info.line_number_table_attr.line_number_table, iter, iter_tmp, lnattr) {
r_bin_java_print_line_number_attr_summary (lnattr);
}
}
R_API void r_bin_java_print_local_variable_attr_summary(RBinJavaLocalVariableAttribute *lvattr) {
if (!lvattr) {
eprintf ("Attempting to print an invalid RBinJavaLocalVariableAttribute *.\n");
return;
}
Eprintf (" Local Variable Attribute offset: 0x%08"PFMT64x "\n", lvattr->file_offset);
Eprintf (" Local Variable Attribute start_pc: %d\n", lvattr->start_pc);
Eprintf (" Local Variable Attribute Length: %d\n", lvattr->length);
Eprintf (" Local Variable Attribute name_idx: %d\n", lvattr->name_idx);
Eprintf (" Local Variable Attribute name: %s\n", lvattr->name);
Eprintf (" Local Variable Attribute descriptor_idx: %d\n", lvattr->descriptor_idx);
Eprintf (" Local Variable Attribute descriptor: %s\n", lvattr->descriptor);
Eprintf (" Local Variable Attribute index: %d\n", lvattr->index);
}
R_API void r_bin_java_print_local_variable_table_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaLocalVariableAttribute *lvattr;
RListIter *iter, *iter_tmp;
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *LocalVariableTable.\n");
return;
}
Eprintf ("Local Variable Table Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
r_list_foreach_safe (attr->info.local_variable_table_attr.local_variable_table, iter, iter_tmp, lvattr) {
r_bin_java_print_local_variable_attr_summary (lvattr);
}
}
R_API void r_bin_java_print_local_variable_type_attr_summary(RBinJavaLocalVariableTypeAttribute *lvattr) {
if (!lvattr) {
eprintf ("Attempting to print an invalid RBinJavaLocalVariableTypeAttribute *.\n");
return;
}
eprintf (" Local Variable Type Attribute offset: 0x%08"PFMT64x "\n", lvattr->file_offset);
eprintf (" Local Variable Type Attribute start_pc: %d\n", lvattr->start_pc);
eprintf (" Local Variable Type Attribute Length: %d\n", lvattr->length);
eprintf (" Local Variable Type Attribute name_idx: %d\n", lvattr->name_idx);
eprintf (" Local Variable Type Attribute name: %s\n", lvattr->name);
eprintf (" Local Variable Type Attribute signature_idx: %d\n", lvattr->signature_idx);
eprintf (" Local Variable Type Attribute signature: %s\n", lvattr->signature);
eprintf (" Local Variable Type Attribute index: %d\n", lvattr->index);
}
R_API void r_bin_java_print_local_variable_type_table_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaLocalVariableTypeAttribute *lvtattr;
RListIter *iter, *iter_tmp;
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *LocalVariableTable.\n");
return;
}
eprintf ("Local Variable Type Table Attribute Information:\n");
eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
eprintf (" Attribute Length: %d\n", attr->length);
r_list_foreach_safe (attr->info.local_variable_type_table_attr.local_variable_table, iter, iter_tmp, lvtattr) {
r_bin_java_print_local_variable_type_attr_summary (lvtattr);
}
}
R_API void r_bin_java_print_signature_attr_summary(RBinJavaAttrInfo *attr) {
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *SignatureAttr.\n");
return;
}
Eprintf ("Signature Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" Signature UTF8 Index: %d\n", attr->info.signature_attr.signature_idx);
Eprintf (" Signature string: %s\n", attr->info.signature_attr.signature);
}
R_API void r_bin_java_print_source_code_file_attr_summary(RBinJavaAttrInfo *attr) {
if (!attr) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *SourceFile.\n");
return;
}
Eprintf ("Source File Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" Source File Index: %d\n", attr->info.source_file_attr.sourcefile_idx);
}
R_API void r_bin_java_print_synthetic_attr_summary(RBinJavaAttrInfo *attr) {
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaAttrInfo *Synthetic.\n");
return;
}
Eprintf ("Synthetic Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" Attribute Index: %d\n", attr->info.source_file_attr.sourcefile_idx);
}
R_API void r_bin_java_print_stack_map_table_attr_summary(RBinJavaAttrInfo *attr) {
RListIter *iter, *iter_tmp;
RList *ptrList;
RBinJavaStackMapFrame *frame;
if (attr == NULL) {
eprintf ("Attempting to print an invalid RBinJavaStackMapTableAttr* .\n");
return;
}
Eprintf ("StackMapTable Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
Eprintf (" StackMapTable Method Code Size: 0x%08x\n", attr->info.stack_map_table_attr.code_size);
Eprintf (" StackMapTable Frame Entries: 0x%08x\n", attr->info.stack_map_table_attr.number_of_entries);
Eprintf (" StackMapTable Frames:\n");
ptrList = attr->info.stack_map_table_attr.stack_map_frame_entries;
if (ptrList) {
r_list_foreach_safe (ptrList, iter, iter_tmp, frame) {
r_bin_java_print_stack_map_frame_summary (frame);
}
}
}
R_API void r_bin_java_print_stack_map_frame_summary(RBinJavaStackMapFrame *obj) {
RListIter *iter, *iter_tmp;
RList *ptrList;
RBinJavaVerificationObj *ver_obj;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaStackMapFrame* .\n");
return;
}
Eprintf ("Stack Map Frame Information\n");
Eprintf (" Tag Value = 0x%02x Name: %s\n", obj->tag, ((RBinJavaStackMapFrameMetas *) obj->metas->type_info)->name);
Eprintf (" Offset: 0x%08"PFMT64x "\n", obj->file_offset);
Eprintf (" Local Variable Count = 0x%04x\n", obj->number_of_locals);
Eprintf (" Stack Items Count = 0x%04x\n", obj->number_of_stack_items);
Eprintf (" Local Variables:\n");
ptrList = obj->local_items;
r_list_foreach_safe (ptrList, iter, iter_tmp, ver_obj) {
r_bin_java_print_verification_info_summary (ver_obj);
}
Eprintf (" Stack Items:\n");
ptrList = obj->stack_items;
r_list_foreach_safe (ptrList, iter, iter_tmp, ver_obj) {
r_bin_java_print_verification_info_summary (ver_obj);
}
}
R_API void r_bin_java_print_verification_info_summary(RBinJavaVerificationObj *obj) {
ut8 tag_value = R_BIN_JAVA_STACKMAP_UNKNOWN;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaVerificationObj* .\n");
return;
}
if (obj->tag < R_BIN_JAVA_STACKMAP_UNKNOWN) {
tag_value = obj->tag;
}
Eprintf ("Verification Information\n");
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" Tag Value = 0x%02x\n", obj->tag);
Eprintf (" Name = %s\n", R_BIN_JAVA_VERIFICATION_METAS[tag_value].name);
if (obj->tag == R_BIN_JAVA_STACKMAP_OBJECT) {
Eprintf (" Object Constant Pool Index = 0x%x\n", obj->info.obj_val_cp_idx);
} else if (obj->tag == R_BIN_JAVA_STACKMAP_UNINIT) {
Eprintf (" Uninitialized Object offset in code = 0x%x\n", obj->info.uninit_offset);
}
}
R_API void r_bin_java_print_field_summary(RBinJavaField *field) {
RBinJavaAttrInfo *attr;
RListIter *iter, *iter_tmp;
if (field) {
if (field->type == R_BIN_JAVA_FIELD_TYPE_METHOD) {
r_bin_java_print_method_summary (field);
} else {
#if 0
r_bin_java_print_interface_summary (field);
return;
} * /
#endif
Eprintf ("Field Summary Information:\n");
Eprintf (" File Offset: 0x%08"PFMT64x "\n", field->file_offset);
Eprintf (" Name Index: %d (%s)\n", field->name_idx, field->name);
Eprintf (" Descriptor Index: %d (%s)\n", field->descriptor_idx, field->descriptor);
Eprintf (" Access Flags: 0x%02x (%s)\n", field->flags, field->flags_str);
Eprintf (" Field Attributes Count: %d\n", field->attr_count);
Eprintf (" Field Attributes:\n");
r_list_foreach_safe (field->attributes, iter, iter_tmp, attr) {
r_bin_java_print_attr_summary (attr);
}
}
} else {
eprintf ("Attempting to print an invalid RBinJavaField* Field.\n");
}
}
R_API void r_bin_java_print_method_summary(RBinJavaField *field) {
RBinJavaAttrInfo *attr;
RListIter *iter, *iter_tmp;
if (field == NULL) {
eprintf ("Attempting to print an invalid RBinJavaField* Method.\n");
return;
}
Eprintf ("Method Summary Information:\n");
Eprintf (" File Offset: 0x%08"PFMT64x "\n", field->file_offset);
Eprintf (" Name Index: %d (%s)\n", field->name_idx, field->name);
Eprintf (" Descriptor Index: %d (%s)\n", field->descriptor_idx, field->descriptor);
Eprintf (" Access Flags: 0x%02x (%s)\n", field->flags, field->flags_str);
Eprintf (" Method Attributes Count: %d\n", field->attr_count);
Eprintf (" Method Attributes:\n");
r_list_foreach_safe (field->attributes, iter, iter_tmp, attr) {
r_bin_java_print_attr_summary (attr);
}
}
/*
R_API void r_bin_java_print_interface_summary(ut16 idx) {//RBinJavaField *field) {
RBinJavaAttrInfo *attr;
RBinJavaCPTypeObj *class_info;
RListIter *iter, *iter_tmp;
if (field == NULL) {
eprintf ("Attempting to print an invalid RBinJavaField* Interface.\n");
return;
}
eprintf ("Interface Summary Information:\n");
eprintf (" File offset: 0x%08"PFMT64x"", field->file_offset);
eprintf (" Access Flags: %d\n", field->flags);
eprintf (" Name Index: %d (%s)\n", field->name_idx, field->name);
eprintf (" Descriptor Index: %d (%s)\n", field->descriptor_idx, field->descriptor);
eprintf (" Interface Attributes Count: %d\n", field->attr_count);
eprintf (" Interface Attributes:\n");
r_list_foreach_safe (field->attributes, iter, iter_tmp, attr) {
r_bin_java_print_attr_summary(attr);
}
}
*/
R_API void r_bin_java_print_interfacemethodref_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* InterfaceMethodRef.\n");
return;
}
eprintf ("InterfaceMethodRef ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Class Index = %d\n", obj->info.cp_interface.class_idx);
eprintf (" Name and type Index = %d\n", obj->info.cp_interface.name_and_type_idx);
}
R_API char *r_bin_java_print_interfacemethodref_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_interface.class_idx, obj->info.cp_interface.name_and_type_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_interface.class_idx, obj->info.cp_interface.name_and_type_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_methodhandle_cp_summary(RBinJavaCPTypeObj *obj) {
ut8 ref_kind;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* RBinJavaCPTypeMethodHandle.\n");
return;
}
ref_kind = obj->info.cp_method_handle.reference_kind;
eprintf ("MethodHandle ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Reference Kind = (0x%02x) %s\n", ref_kind, R_BIN_JAVA_REF_METAS[ref_kind].name);
eprintf (" Reference Index = %d\n", obj->info.cp_method_handle.reference_index);
}
R_API char *r_bin_java_print_methodhandle_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
ut8 ref_kind = obj->info.cp_method_handle.reference_kind;
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_REF_METAS[ref_kind].name, obj->info.cp_method_handle.reference_index);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_REF_METAS[ref_kind].name, obj->info.cp_method_handle.reference_index);
}
}
}
return value;
}
R_API void r_bin_java_print_methodtype_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* RBinJavaCPTypeMethodType.\n");
return;
}
Eprintf ("MethodType ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" Descriptor Index = 0x%02x\n", obj->info.cp_method_type.descriptor_index);
}
R_API char *r_bin_java_print_methodtype_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_method_type.descriptor_index);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_method_type.descriptor_index);
}
}
}
return value;
}
R_API void r_bin_java_print_invokedynamic_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* RBinJavaCPTypeInvokeDynamic.\n");
return;
}
eprintf ("InvokeDynamic ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Bootstrap Method Attr Index = (0x%02x)\n", obj->info.cp_invoke_dynamic.bootstrap_method_attr_index);
eprintf (" Bootstrap Name and Type Index = (0x%02x)\n", obj->info.cp_invoke_dynamic.name_and_type_index);
}
R_API char *r_bin_java_print_invokedynamic_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_invoke_dynamic.bootstrap_method_attr_index,
obj->info.cp_invoke_dynamic.name_and_type_index);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_invoke_dynamic.bootstrap_method_attr_index,
obj->info.cp_invoke_dynamic.name_and_type_index);
}
}
}
return value;
}
R_API void r_bin_java_print_methodref_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* MethodRef.\n");
return;
}
eprintf ("MethodRef ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Class Index = %d\n", obj->info.cp_method.class_idx);
eprintf (" Name and type Index = %d\n", obj->info.cp_method.name_and_type_idx);
}
R_API char *r_bin_java_print_methodref_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_method.class_idx,
obj->info.cp_method.name_and_type_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_method.class_idx,
obj->info.cp_method.name_and_type_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_fieldref_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* FieldRef.\n");
return;
}
eprintf ("FieldRef ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Class Index = %d\n", obj->info.cp_field.class_idx);
eprintf (" Name and type Index = %d\n", obj->info.cp_field.name_and_type_idx);
}
R_API char *r_bin_java_print_fieldref_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_field.class_idx,
obj->info.cp_field.name_and_type_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_field.class_idx,
obj->info.cp_field.name_and_type_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_classref_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* ClassRef.\n");
return;
}
eprintf ("ClassRef ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" Name Index = %d\n", obj->info.cp_class.name_idx);
}
R_API char *r_bin_java_print_classref_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_class.name_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_class.name_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_string_cp_summary(RBinJavaCPTypeObj *obj) {
if (!obj) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* String.\n");
return;
}
Eprintf ("String ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" String Index = %d\n", obj->info.cp_string.string_idx);
}
R_API char *r_bin_java_print_string_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_string.string_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d",
obj->metas->ord, obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_string.string_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_integer_cp_summary(RBinJavaCPTypeObj *obj) {
ut8 *b = NULL;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Integer.\n");
return;
}
b = obj->info.cp_integer.bytes.raw;
eprintf ("Integer ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" bytes = %02x %02x %02x %02x\n", b[0], b[1], b[2], b[3]);
eprintf (" integer = %d\n", R_BIN_JAVA_UINT (obj->info.cp_integer.bytes.raw, 0));
}
R_API char *r_bin_java_print_integer_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.0x%08x",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_UINT (obj->info.cp_integer.bytes.raw, 0));
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.0x%08x",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_UINT (obj->info.cp_integer.bytes.raw, 0));
}
}
}
return value;
}
R_API void r_bin_java_print_float_cp_summary(RBinJavaCPTypeObj *obj) {
ut8 *b = NULL;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Double.\n");
return;
}
b = obj->info.cp_float.bytes.raw;
Eprintf ("Float ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" Bytes = %02x %02x %02x %02x\n", b[0], b[1], b[2], b[3]);
Eprintf (" Float = %f\n", R_BIN_JAVA_FLOAT (obj->info.cp_float.bytes.raw, 0));
}
R_API char *r_bin_java_print_float_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%f",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_FLOAT (obj->info.cp_float.bytes.raw, 0));
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%f",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
R_BIN_JAVA_FLOAT (obj->info.cp_float.bytes.raw, 0));
}
}
}
return value;
}
R_API void r_bin_java_print_long_cp_summary(RBinJavaCPTypeObj *obj) {
ut8 *b = NULL;
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Long.\n");
return;
}
b = obj->info.cp_long.bytes.raw;
Eprintf ("Long ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" High-Bytes = %02x %02x %02x %02x\n", b[0], b[1], b[2], b[3]);
Eprintf (" Low-Bytes = %02x %02x %02x %02x\n", b[4], b[5], b[6], b[7]);
Eprintf (" Long = %08"PFMT64x "\n", r_bin_java_raw_to_long (obj->info.cp_long.bytes.raw, 0));
}
R_API char *r_bin_java_print_long_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.0x%08"PFMT64x "",
obj->metas->ord,
obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
r_bin_java_raw_to_long (obj->info.cp_long.bytes.raw, 0));
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.0x%08"PFMT64x "",
obj->metas->ord,
obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
r_bin_java_raw_to_long (obj->info.cp_long.bytes.raw, 0));
}
}
}
return value;
}
R_API void r_bin_java_print_double_cp_summary(RBinJavaCPTypeObj *obj) {
ut8 *b = NULL;
if (!obj) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Double.\n");
return;
}
b = obj->info.cp_double.bytes.raw;
Eprintf ("Double ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" High-Bytes = %02x %02x %02x %02x\n", b[0], b[1], b[2], b[3]);
Eprintf (" Low-Bytes = %02x %02x %02x %02x\n", b[4], b[5], b[6], b[7]);
Eprintf (" Double = %f\n", r_bin_java_raw_to_double (obj->info.cp_double.bytes.raw, 0));
}
R_API char *r_bin_java_print_double_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%f",
obj->metas->ord,
obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
r_bin_java_raw_to_double (obj->info.cp_double.bytes.raw, 0));
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%f",
obj->metas->ord,
obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
r_bin_java_raw_to_double (obj->info.cp_double.bytes.raw, 0));
}
}
}
return value;
}
R_API void r_bin_java_print_name_and_type_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Name_And_Type.\n");
return;
}
Eprintf ("Name_And_Type ConstantPool Type (%d) ", obj->metas->ord);
Eprintf (" Offset: 0x%08"PFMT64x "", obj->file_offset);
Eprintf (" name_idx = (%d)\n", obj->info.cp_name_and_type.name_idx);
Eprintf (" descriptor_idx = (%d)\n", obj->info.cp_name_and_type.descriptor_idx);
}
R_API char *r_bin_java_print_name_and_type_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_name_and_type.name_idx,
obj->info.cp_name_and_type.descriptor_idx);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%d",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_name_and_type.name_idx,
obj->info.cp_name_and_type.descriptor_idx);
}
}
}
return value;
}
R_API void r_bin_java_print_utf8_cp_summary(RBinJavaCPTypeObj *obj) {
if (obj == NULL) {
eprintf ("Attempting to print an invalid RBinJavaCPTypeObj* Utf8.\n");
return;
}
char *str = convert_string ((const char *) obj->info.cp_utf8.bytes, obj->info.cp_utf8.length);
eprintf ("UTF8 ConstantPool Type (%d) ", obj->metas->ord);
eprintf (" Offset: 0x%08"PFMT64x"", obj->file_offset);
eprintf (" length = %d\n", obj->info.cp_utf8.length);
eprintf (" utf8 = %s\n", str);
free (str);
}
R_API char *r_bin_java_print_utf8_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *utf8_str = r_hex_bin2strdup (obj->info.cp_utf8.bytes, obj->info.cp_utf8.length);
char *value = malloc (size + strlen (utf8_str));
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%s",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_utf8.length,
utf8_str);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size + strlen (utf8_str));
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s.%d.%s",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name,
obj->info.cp_utf8.length,
utf8_str);
}
}
}
free (utf8_str);
return value;
}
R_API void r_bin_java_print_null_cp_summary(RBinJavaCPTypeObj *obj) {
eprintf ("Unknown ConstantPool Type Tag: 0x%04x .\n", obj->tag);
}
R_API char *r_bin_java_print_null_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255, consumed = 0;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name);
if (consumed >= size - 1) {
free (value);
size += size >> 1;
value = malloc (size);
if (value) {
memset (value, 0, size);
consumed = snprintf (value, size, "%d.0x%04"PFMT64x ".%s",
obj->metas->ord, obj->file_offset,
((RBinJavaCPTypeMetas *) obj->metas->type_info)->name);
}
}
}
return value;
}
R_API void r_bin_java_print_unknown_cp_summary(RBinJavaCPTypeObj *obj) {
eprintf ("NULL ConstantPool Type.\n");
}
R_API char *r_bin_java_print_unknown_cp_stringify(RBinJavaCPTypeObj *obj) {
ut32 size = 255;
char *value = malloc (size);
if (value) {
memset (value, 0, size);
snprintf (value, size, "%d.0x%04"PFMT64x ".%s",
obj->metas->ord, obj->file_offset + obj->loadaddr, ((RBinJavaCPTypeMetas *) obj->metas->type_info)->name);
}
return value;
}
R_API RBinJavaElementValuePair *r_bin_java_element_pair_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaElementValuePair *ev_pair = NULL;
ut64 offset = 0;
if (!buffer) {
return NULL;
}
ev_pair = R_NEW0 (RBinJavaElementValuePair);
if (!ev_pair) {
// TODO eprintf ev_pair failed to allocate
return NULL;
}
// TODO: What is the signifigance of ev_pair element
ev_pair->element_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
ev_pair->file_offset = buf_offset;
ev_pair->name = r_bin_java_get_utf8_from_bin_cp_list (R_BIN_JAVA_GLOBAL_BIN, ev_pair->element_name_idx);
if (ev_pair->name == NULL) {
// TODO: eprintf unable to find the name for the given index
eprintf ("ElementValue Name is invalid.\n");
ev_pair->name = strdup ("UNKNOWN");
}
ev_pair->value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);
offset += ev_pair->value->size;
ev_pair->size = offset;
return ev_pair;
}
R_API void r_bin_java_print_element_pair_summary(RBinJavaElementValuePair *ev_pair) {
if (!ev_pair) {
eprintf ("Attempting to print an invalid RBinJavaElementValuePair *pair.\n");
return;
}
Eprintf ("Element Value Pair information:\n");
Eprintf (" EV Pair File Offset: 0x%08"PFMT64x "\n", ev_pair->file_offset);
Eprintf (" EV Pair Element Name index: 0x%02x\n", ev_pair->element_name_idx);
Eprintf (" EV Pair Element Name: %s\n", ev_pair->name);
Eprintf (" EV Pair Element Value:\n");
r_bin_java_print_element_value_summary (ev_pair->value);
}
R_API void r_bin_java_print_element_value_summary(RBinJavaElementValue *element_value) {
RBinJavaCPTypeObj *obj;
RBinJavaElementValue *ev_element = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
char *name;
if (element_value == NULL) {
eprintf ("Attempting to print an invalid RBinJavaElementValuePair *pair.\n");
return;
}
name = ((RBinJavaElementValueMetas *) element_value->metas->type_info)->name;
eprintf ("Element Value information:\n");
eprintf (" EV Pair File Offset: 0x%08"PFMT64x "\n", element_value->file_offset);
eprintf (" EV Value Type (%d): %s\n", element_value->tag, name);
switch (element_value->tag) {
case R_BIN_JAVA_EV_TAG_BYTE:
case R_BIN_JAVA_EV_TAG_CHAR:
case R_BIN_JAVA_EV_TAG_DOUBLE:
case R_BIN_JAVA_EV_TAG_FLOAT:
case R_BIN_JAVA_EV_TAG_INT:
case R_BIN_JAVA_EV_TAG_LONG:
case R_BIN_JAVA_EV_TAG_SHORT:
case R_BIN_JAVA_EV_TAG_BOOLEAN:
case R_BIN_JAVA_EV_TAG_STRING:
eprintf (" EV Value Constant Value index: 0x%02x\n", element_value->value.const_value.const_value_idx);
eprintf (" EV Value Constant Value Information:\n");
obj = element_value->value.const_value.const_value_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->print_summary (obj);
break;
case R_BIN_JAVA_EV_TAG_ENUM:
eprintf (" EV Value Enum Constant Value Const Name Index: 0x%02x\n", element_value->value.enum_const_value.const_name_idx);
eprintf (" EV Value Enum Constant Value Type Name Index: 0x%02x\n", element_value->value.enum_const_value.type_name_idx);
eprintf (" EV Value Enum Constant Value Const CP Information:\n");
obj = element_value->value.enum_const_value.const_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->print_summary (obj);
eprintf (" EV Value Enum Constant Value Type CP Information:\n");
obj = element_value->value.enum_const_value.type_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->print_summary (obj);
break;
case R_BIN_JAVA_EV_TAG_CLASS:
eprintf (" EV Value Class Info Index: 0x%02x\n", element_value->value.class_value.class_info_idx);
eprintf (" EV Value Class Info CP Information:\n");
obj = element_value->value.class_value.class_info_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->print_summary (obj);
break;
case R_BIN_JAVA_EV_TAG_ARRAY:
eprintf (" EV Value Array Value Number of Values: 0x%04x\n", element_value->value.array_value.num_values);
eprintf (" EV Value Array Values\n");
r_list_foreach_safe (element_value->value.array_value.values, iter, iter_tmp, ev_element) {
r_bin_java_print_element_value_summary (ev_element);
}
break;
case R_BIN_JAVA_EV_TAG_ANNOTATION:
eprintf (" EV Annotation Information:\n");
r_bin_java_print_annotation_summary (&element_value->value.annotation_value);
break;
default:
// eprintf unable to handle tag
break;
}
}
R_API void r_bin_java_element_pair_free(void /*RBinJavaElementValuePair*/ *e) {
RBinJavaElementValuePair *ev_pair = e;
if (ev_pair) {
free (ev_pair->name);
r_bin_java_element_value_free (ev_pair->value);
free (ev_pair);
}
ev_pair = NULL;
}
R_API void r_bin_java_element_value_free(void /*RBinJavaElementValue*/ *e) {
RBinJavaElementValue *element_value = e;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaCPTypeObj *obj = NULL;
RBinJavaElementValue *ev_element = NULL;
if (element_value) {
free (element_value->metas);
element_value->metas = NULL;
switch (element_value->tag) {
case R_BIN_JAVA_EV_TAG_BYTE:
case R_BIN_JAVA_EV_TAG_CHAR:
case R_BIN_JAVA_EV_TAG_DOUBLE:
case R_BIN_JAVA_EV_TAG_FLOAT:
case R_BIN_JAVA_EV_TAG_INT:
case R_BIN_JAVA_EV_TAG_LONG:
case R_BIN_JAVA_EV_TAG_SHORT:
case R_BIN_JAVA_EV_TAG_BOOLEAN:
case R_BIN_JAVA_EV_TAG_STRING:
// Delete the CP Type Object
obj = element_value->value.const_value.const_value_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_ENUM:
// Delete the CP Type Objects
obj = element_value->value.enum_const_value.const_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
obj = element_value->value.enum_const_value.type_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_CLASS:
// Delete the CP Type Object
obj = element_value->value.class_value.class_info_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_ARRAY:
// Delete the Element Value array List
r_list_foreach_safe (element_value->value.array_value.values, iter, iter_tmp, ev_element) {
if (ev_element) {
r_bin_java_element_value_free (ev_element);
} else {
// TODO eprintf ev_pairs value was NULL
}
// r_list_delete (element_value->value.array_value.values, iter);
ev_element = NULL;
}
r_list_free (element_value->value.array_value.values);
break;
case R_BIN_JAVA_EV_TAG_ANNOTATION:
// Delete the Annotations List
r_list_free (element_value->value.annotation_value.element_value_pairs);
break;
default:
// eprintf unable to free the tag
break;
}
free (element_value);
}
}
R_API ut64 r_bin_java_annotation_default_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr) {
// attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
size += 6;
// attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer+offset, sz-offset, buf_offset+offset);
size += r_bin_java_element_value_calc_size (attr->info.annotation_default_attr.default_value);
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_annotation_default_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut64 offset = 0;
RBinJavaAttrInfo *attr = NULL;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR;
attr->info.annotation_default_attr.default_value = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);
if (attr->info.annotation_default_attr.default_value) {
offset += attr->info.annotation_default_attr.default_value->size;
}
}
r_bin_java_print_annotation_default_attr_summary (attr);
return attr;
}
R_API void r_bin_java_annotation_default_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
RBinJavaElementValue *element_value = NULL, *ev_element = NULL;
RBinJavaCPTypeObj *obj = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
if (attr == NULL || attr->type != R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR) {
return;
}
element_value = (attr->info.annotation_default_attr.default_value);
switch (element_value->tag) {
case R_BIN_JAVA_EV_TAG_BYTE:
case R_BIN_JAVA_EV_TAG_CHAR:
case R_BIN_JAVA_EV_TAG_DOUBLE:
case R_BIN_JAVA_EV_TAG_FLOAT:
case R_BIN_JAVA_EV_TAG_INT:
case R_BIN_JAVA_EV_TAG_LONG:
case R_BIN_JAVA_EV_TAG_SHORT:
case R_BIN_JAVA_EV_TAG_BOOLEAN:
case R_BIN_JAVA_EV_TAG_STRING:
// Delete the CP Type Object
obj = element_value->value.const_value.const_value_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_ENUM:
// Delete the CP Type Objects
obj = element_value->value.enum_const_value.const_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
obj = element_value->value.enum_const_value.type_name_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_CLASS:
// Delete the CP Type Object
obj = element_value->value.class_value.class_info_cp_obj;
((RBinJavaCPTypeMetas *) obj->metas->type_info)->allocs->delete_obj (obj);
break;
case R_BIN_JAVA_EV_TAG_ARRAY:
// Delete the Element Value array List
r_list_foreach_safe (element_value->value.array_value.values, iter, iter_tmp, ev_element) {
r_bin_java_element_value_free (ev_element);
// r_list_delete (element_value->value.array_value.values, iter);
ev_element = NULL;
}
r_list_free (element_value->value.array_value.values);
break;
case R_BIN_JAVA_EV_TAG_ANNOTATION:
// Delete the Annotations List
r_list_free (element_value->value.annotation_value.element_value_pairs);
break;
default:
// eprintf unable to free the tag
break;
}
if (attr) {
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API RBinJavaAnnotation *r_bin_java_annotation_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAnnotation *annotation = NULL;
RBinJavaElementValuePair *ev_pairs = NULL;
ut64 offset = 0;
annotation = R_NEW0 (RBinJavaAnnotation);
if (!annotation) {
return NULL;
}
// (ut16) read and set annotation_value.type_idx;
annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation->element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < annotation->num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
ev_pairs = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (ev_pairs) {
offset += ev_pairs->size;
r_list_append (annotation->element_value_pairs, (void *) ev_pairs);
}
}
annotation->size = offset;
return annotation;
}
R_API ut64 r_bin_java_annotation_calc_size(RBinJavaAnnotation *annotation) {
ut64 sz = 0;
RListIter *iter, *iter_tmp;
RBinJavaElementValuePair *ev_pairs = NULL;
if (!annotation) {
// TODO eprintf allocation fail
return sz;
}
// annotation->type_idx = R_BIN_JAVA_USHORT (buffer, offset);
sz += 2;
// annotation->num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
sz += 2;
r_list_foreach_safe (annotation->element_value_pairs, iter, iter_tmp, ev_pairs) {
if (ev_pairs) {
sz += r_bin_java_element_pair_calc_size (ev_pairs);
}
}
return sz;
}
R_API void r_bin_java_annotation_free(void /*RBinJavaAnnotation*/ *a) {
RBinJavaAnnotation *annotation = a;
if (annotation) {
r_list_free (annotation->element_value_pairs);
free (annotation);
}
}
R_API void r_bin_java_print_annotation_summary(RBinJavaAnnotation *annotation) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaElementValuePair *ev_pair = NULL;
if (!annotation) {
// TODO eprintf invalid annotation
return;
}
Eprintf (" Annotation Type Index: 0x%02x\n", annotation->type_idx);
Eprintf (" Annotation Number of EV Pairs: 0x%04x\n", annotation->num_element_value_pairs);
Eprintf (" Annotation EV Pair Values:\n");
if (annotation->element_value_pairs) {
r_list_foreach_safe (annotation->element_value_pairs, iter, iter_tmp, ev_pair) {
r_bin_java_print_element_pair_summary (ev_pair);
}
}
}
R_API ut64 r_bin_java_element_pair_calc_size(RBinJavaElementValuePair *ev_pair) {
ut64 sz = 0;
if (ev_pair == NULL) {
return sz;
}
// ev_pair->element_name_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
// ev_pair->value = r_bin_java_element_value_new (bin, offset+2);
if (ev_pair->value) {
sz += r_bin_java_element_value_calc_size (ev_pair->value);
}
return sz;
}
R_API ut64 r_bin_java_element_value_calc_size(RBinJavaElementValue *element_value) {
RListIter *iter, *iter_tmp;
RBinJavaElementValue *ev_element;
RBinJavaElementValuePair *ev_pairs;
ut64 sz = 0;
if (element_value == NULL) {
return sz;
}
// tag
sz += 1;
switch (element_value->tag) {
case R_BIN_JAVA_EV_TAG_BYTE:
case R_BIN_JAVA_EV_TAG_CHAR:
case R_BIN_JAVA_EV_TAG_DOUBLE:
case R_BIN_JAVA_EV_TAG_FLOAT:
case R_BIN_JAVA_EV_TAG_INT:
case R_BIN_JAVA_EV_TAG_LONG:
case R_BIN_JAVA_EV_TAG_SHORT:
case R_BIN_JAVA_EV_TAG_BOOLEAN:
case R_BIN_JAVA_EV_TAG_STRING:
// look up value in bin->cp_list
// (ut16) read and set const_value.const_value_idx
// element_value->value.const_value.const_value_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
break;
case R_BIN_JAVA_EV_TAG_ENUM:
// (ut16) read and set enum_const_value.type_name_idx
// element_value->value.enum_const_value.type_name_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
// (ut16) read and set enum_const_value.const_name_idx
// element_value->value.enum_const_value.const_name_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
break;
case R_BIN_JAVA_EV_TAG_CLASS:
// (ut16) read and set class_value.class_info_idx
// element_value->value.class_value.class_info_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
break;
case R_BIN_JAVA_EV_TAG_ARRAY:
// (ut16) read and set array_value.num_values
// element_value->value.array_value.num_values = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
r_list_foreach_safe (element_value->value.array_value.values, iter, iter_tmp, ev_element) {
if (ev_element) {
sz += r_bin_java_element_value_calc_size (ev_element);
}
}
break;
case R_BIN_JAVA_EV_TAG_ANNOTATION:
// annotation new is not used here.
// (ut16) read and set annotation_value.type_idx;
// element_value->value.annotation_value.type_idx = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
// element_value->value.annotation_value.num_element_value_pairs = r_bin_java_read_short(bin, bin->b->cur);
sz += 2;
element_value->value.annotation_value.element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
r_list_foreach_safe (element_value->value.annotation_value.element_value_pairs, iter, iter_tmp, ev_pairs) {
if (ev_pairs) {
sz += r_bin_java_element_pair_calc_size (ev_pairs);
}
}
break;
default:
// eprintf unable to handle tag
break;
}
return sz;
}
R_API RBinJavaElementValue *r_bin_java_element_value_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
ut64 offset = 0;
RBinJavaElementValue *element_value = R_NEW0 (RBinJavaElementValue);
if (!element_value) {
return NULL;
}
RBinJavaElementValuePair *ev_pairs = NULL;
element_value->metas = R_NEW0 (RBinJavaMetaInfo);
if (!element_value->metas) {
R_FREE (element_value);
return NULL;
}
element_value->file_offset = buf_offset;
element_value->tag = buffer[offset];
element_value->size += 1;
offset += 1;
element_value->metas->type_info = (void *) r_bin_java_get_ev_meta_from_tag (element_value->tag);
switch (element_value->tag) {
case R_BIN_JAVA_EV_TAG_BYTE:
case R_BIN_JAVA_EV_TAG_CHAR:
case R_BIN_JAVA_EV_TAG_DOUBLE:
case R_BIN_JAVA_EV_TAG_FLOAT:
case R_BIN_JAVA_EV_TAG_INT:
case R_BIN_JAVA_EV_TAG_LONG:
case R_BIN_JAVA_EV_TAG_SHORT:
case R_BIN_JAVA_EV_TAG_BOOLEAN:
case R_BIN_JAVA_EV_TAG_STRING:
// look up value in bin->cp_list
// (ut16) read and set const_value.const_value_idx
element_value->value.const_value.const_value_idx = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
// look-up, deep copy, and set const_value.const_value_cp_obj
element_value->value.const_value.const_value_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.const_value.const_value_idx);
break;
case R_BIN_JAVA_EV_TAG_ENUM:
// (ut16) read and set enum_const_value.type_name_idx
element_value->value.enum_const_value.type_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
// (ut16) read and set enum_const_value.const_name_idx
element_value->value.enum_const_value.const_name_idx = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
// look up type_name_index in bin->cp_list
// look-up, deep copy, and set enum_const_value.const_name_cp_obj
element_value->value.enum_const_value.const_name_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.enum_const_value.const_name_idx);
// look-up, deep copy, and set enum_const_value.type_name_cp_obj
element_value->value.enum_const_value.type_name_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.enum_const_value.type_name_idx);
break;
case R_BIN_JAVA_EV_TAG_CLASS:
// (ut16) read and set class_value.class_info_idx
element_value->value.class_value.class_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
// look up type_name_index in bin->cp_list
// look-up, deep copy, and set class_value.class_info_cp_obj
element_value->value.class_value.class_info_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, element_value->value.class_value.class_info_idx);
break;
case R_BIN_JAVA_EV_TAG_ARRAY:
// (ut16) read and set array_value.num_values
element_value->value.array_value.num_values = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
element_value->value.array_value.values = r_list_new ();
for (i = 0; i < element_value->value.array_value.num_values; i++) {
if (offset >= sz) {
break;
}
RBinJavaElementValue *ev_element = r_bin_java_element_value_new (buffer + offset, sz - offset, buf_offset + offset);
if (ev_element) {
element_value->size += ev_element->size;
offset += ev_element->size;
}
// read array_value.num_values, and append to array_value.values
r_list_append (element_value->value.array_value.values, (void *) ev_element);
if (ev_element == NULL) {
// TODO: eprintf error when reading element value
}
}
break;
case R_BIN_JAVA_EV_TAG_ANNOTATION:
// annotation new is not used here.
// (ut16) read and set annotation_value.type_idx;
element_value->value.annotation_value.type_idx = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
// (ut16) read and set annotation_value.num_element_value_pairs;
element_value->value.annotation_value.num_element_value_pairs = R_BIN_JAVA_USHORT (buffer, offset);
element_value->size += 2;
offset += 2;
element_value->value.annotation_value.element_value_pairs = r_list_newf (r_bin_java_element_pair_free);
// read annotation_value.num_element_value_pairs, and append to annotation_value.element_value_pairs
for (i = 0; i < element_value->value.annotation_value.num_element_value_pairs; i++) {
if (offset > sz) {
break;
}
ev_pairs = r_bin_java_element_pair_new (buffer + offset, sz - offset, buf_offset + offset);
if (ev_pairs) {
element_value->size += ev_pairs->size;
offset += ev_pairs->size;
}
if (ev_pairs == NULL) {
// TODO: eprintf error when reading element pair
}
r_list_append (element_value->value.annotation_value.element_value_pairs, (void *) ev_pairs);
}
break;
default:
// eprintf unable to handle tag
break;
}
return element_value;
}
R_API void r_bin_java_bootstrap_method_argument_free(void /*RBinJavaBootStrapArgument*/ *b) {
RBinJavaBootStrapArgument *bsm_arg = b;
if (bsm_arg) {
if (bsm_arg->argument_info_cp_obj) {
((RBinJavaCPTypeMetas *) bsm_arg->argument_info_cp_obj)->allocs->delete_obj (bsm_arg->argument_info_cp_obj);
bsm_arg->argument_info_cp_obj = NULL;
}
free (bsm_arg);
}
}
R_API void r_bin_java_print_bootstrap_method_argument_summary(RBinJavaBootStrapArgument *bsm_arg) {
if (bsm_arg == NULL) {
eprintf ("Attempting to print an invalid RBinJavaBootStrapArgument *.\n");
return;
}
eprintf ("Bootstrap Method Argument Information:\n");
eprintf (" Offset: 0x%08"PFMT64x"", bsm_arg->file_offset);
eprintf (" Name_And_Type Index = (0x%02x)\n", bsm_arg->argument_info_idx);
if (bsm_arg->argument_info_cp_obj) {
eprintf (" Bootstrap Method Argument Type and Name Info:\n");
((RBinJavaCPTypeMetas *) bsm_arg->argument_info_cp_obj)->allocs->print_summary (bsm_arg->argument_info_cp_obj);
} else {
eprintf (" Bootstrap Method Argument Type and Name Info: INVALID\n");
}
}
R_API void r_bin_java_print_bootstrap_method_summary(RBinJavaBootStrapMethod *bsm) {
RBinJavaBootStrapArgument *bsm_arg = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
if (bsm == NULL) {
eprintf ("Attempting to print an invalid RBinJavaBootStrapArgument *.\n");
return;
}
eprintf ("Bootstrap Method Information:\n");
eprintf (" Offset: 0x%08"PFMT64x"", bsm->file_offset);
eprintf (" Method Reference Index = (0x%02x)\n", bsm->bootstrap_method_ref);
eprintf (" Number of Method Arguments = (0x%02x)\n", bsm->num_bootstrap_arguments);
if (bsm->bootstrap_arguments) {
r_list_foreach_safe (bsm->bootstrap_arguments, iter, iter_tmp, bsm_arg) {
if (bsm_arg) {
r_bin_java_print_bootstrap_method_argument_summary (bsm_arg);
}
}
} else {
eprintf (" Bootstrap Method Argument: NONE \n");
}
}
R_API RBinJavaBootStrapArgument *r_bin_java_bootstrap_method_argument_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaBootStrapArgument *bsm_arg = NULL;
ut64 offset = 0;
bsm_arg = (RBinJavaBootStrapArgument *) malloc (sizeof (RBinJavaBootStrapArgument));
if (bsm_arg == NULL) {
// TODO eprintf failed to allocate bytes for bootstrap_method.
return bsm_arg;
}
memset (bsm_arg, 0, sizeof (RBinJavaBootStrapArgument));
bsm_arg->file_offset = buf_offset;
bsm_arg->argument_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
bsm_arg->argument_info_cp_obj = r_bin_java_clone_cp_idx (R_BIN_JAVA_GLOBAL_BIN, bsm_arg->argument_info_idx);
bsm_arg->size = offset;
return bsm_arg;
}
R_API void r_bin_java_bootstrap_method_free(void /*/RBinJavaBootStrapMethod*/ *b) {
RBinJavaBootStrapMethod *bsm = b;
RListIter *iter, *iter_tmp;
RBinJavaBootStrapArgument *obj = NULL;
if (bsm) {
if (bsm->bootstrap_arguments) {
r_list_foreach_safe (bsm->bootstrap_arguments, iter, iter_tmp, obj) {
if (obj) {
r_bin_java_bootstrap_method_argument_free (obj);
}
// r_list_delete (bsm->bootstrap_arguments, iter);
}
r_list_free (bsm->bootstrap_arguments);
bsm->bootstrap_arguments = NULL;
}
free (bsm);
}
}
R_API RBinJavaBootStrapMethod *r_bin_java_bootstrap_method_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaBootStrapMethod *bsm = NULL;
RBinJavaBootStrapArgument *bsm_arg = NULL;
ut32 i = 0;
ut64 offset = 0;
bsm = (RBinJavaBootStrapMethod *) malloc (sizeof (RBinJavaBootStrapMethod));
if (bsm == NULL) {
// TODO eprintf failed to allocate bytes for bootstrap_method.
return bsm;
}
memset (bsm, 0, sizeof (RBinJavaBootStrapMethod));
bsm->file_offset = buf_offset;
bsm->bootstrap_method_ref = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
bsm->num_bootstrap_arguments = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
bsm->bootstrap_arguments = r_list_new ();
for (i = 0; i < bsm->num_bootstrap_arguments; i++) {
// bsm_arg = r_bin_java_bootstrap_method_argument_new (bin, bin->b->cur);
bsm_arg = r_bin_java_bootstrap_method_argument_new (buffer + offset, sz - offset, buf_offset + offset);
if (bsm_arg) {
offset += bsm_arg->size;
r_list_append (bsm->bootstrap_arguments, (void *) bsm_arg);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
bsm->size = offset;
return bsm;
}
R_API void r_bin_java_print_bootstrap_methods_attr_summary(RBinJavaAttrInfo *attr) {
RListIter *iter, *iter_tmp;
RBinJavaBootStrapMethod *obj = NULL;
if (attr == NULL || attr->type == R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR) {
eprintf ("Unable to print attribue summary for RBinJavaAttrInfo *RBinJavaBootstrapMethodsAttr");
return;
}
eprintf ("Bootstrap Methods Attribute Information Information:\n");
eprintf (" Attribute Offset: 0x%08"PFMT64x"", attr->file_offset);
eprintf (" Length: 0x%08x", attr->length);
eprintf (" Number of Method Arguments = (0x%02x)\n", attr->info.bootstrap_methods_attr.num_bootstrap_methods);
if (attr->info.bootstrap_methods_attr.bootstrap_methods) {
r_list_foreach_safe (attr->info.bootstrap_methods_attr.bootstrap_methods, iter, iter_tmp, obj) {
if (obj) {
r_bin_java_print_bootstrap_method_summary (obj);
}
}
} else {
eprintf (" Bootstrap Methods: NONE \n");
}
}
R_API void r_bin_java_bootstrap_methods_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR) {
free (attr->name);
free (attr->metas);
r_list_free (attr->info.bootstrap_methods_attr.bootstrap_methods);
free (attr);
}
}
R_API ut64 r_bin_java_bootstrap_methods_attr_calc_size(RBinJavaAttrInfo *attr) {
RListIter *iter, *iter_tmp;
RBinJavaBootStrapMethod *bsm = NULL;
ut64 size = 0;
if (attr) {
size += 6;
// attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (attr->info.bootstrap_methods_attr.bootstrap_methods, iter, iter_tmp, bsm) {
if (bsm) {
size += r_bin_java_bootstrap_method_calc_size (bsm);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
}
return size;
}
R_API ut64 r_bin_java_bootstrap_arg_calc_size(RBinJavaBootStrapArgument *bsm_arg) {
ut64 size = 0;
if (bsm_arg) {
// bsm_arg->argument_info_idx = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
}
return size;
}
R_API ut64 r_bin_java_bootstrap_method_calc_size(RBinJavaBootStrapMethod *bsm) {
RListIter *iter, *iter_tmp;
RBinJavaBootStrapArgument *bsm_arg = NULL;
ut64 size = 0;
if (bsm) {
size += 6;
// bsm->bootstrap_method_ref = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
// bsm->num_bootstrap_arguments = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (bsm->bootstrap_arguments, iter, iter_tmp, bsm_arg) {
if (bsm_arg) {
size += r_bin_java_bootstrap_arg_calc_size (bsm_arg);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_bootstrap_methods_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaBootStrapMethod *bsm = NULL;
ut64 offset = 0;
RBinJavaAttrInfo *attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_BOOTSTRAP_METHODS_ATTR;
attr->info.bootstrap_methods_attr.num_bootstrap_methods = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.bootstrap_methods_attr.bootstrap_methods = r_list_newf (r_bin_java_bootstrap_method_free);
for (i = 0; i < attr->info.bootstrap_methods_attr.num_bootstrap_methods; i++) {
// bsm = r_bin_java_bootstrap_method_new (bin, bin->b->cur);
bsm = r_bin_java_bootstrap_method_new (buffer + offset, sz - offset, buf_offset + offset);
if (bsm) {
offset += bsm->size;
r_list_append (attr->info.bootstrap_methods_attr.bootstrap_methods, (void *) bsm);
} else {
// TODO eprintf Failed to read the %d boot strap method.
}
}
attr->size = offset;
}
return attr;
}
R_API void r_bin_java_print_annotation_default_attr_summary(RBinJavaAttrInfo *attr) {
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_ANNOTATION_DEFAULT_ATTR) {
eprintf ("Annotation Default Attribute Information:\n");
eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
eprintf (" Attribute Length: %d\n", attr->length);
r_bin_java_print_element_value_summary ((attr->info.annotation_default_attr.default_value));
} else {
// TODO: eprintf attr is invalid
}
}
R_API void r_bin_java_annotation_array_free(void /*RBinJavaAnnotationsArray*/ *a) {
RBinJavaAnnotationsArray *annotation_array = a;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaAnnotation *annotation;
if (annotation_array->annotations == NULL) {
// TODO eprintf
return;
}
r_list_foreach_safe (annotation_array->annotations, iter, iter_tmp, annotation) {
if (annotation) {
r_bin_java_annotation_free (annotation);
}
// r_list_delete (annotation_array->annotations, iter);
}
r_list_free (annotation_array->annotations);
free (annotation_array);
}
R_API void r_bin_java_print_annotation_array_summary(RBinJavaAnnotationsArray *annotation_array) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaAnnotation *annotation;
if (annotation_array->annotations == NULL) {
// TODO eprintf
return;
}
eprintf (" Annotation Array Information:\n");
eprintf (" Number of Annotation Array Elements: %d\n", annotation_array->num_annotations);
r_list_foreach_safe (annotation_array->annotations, iter, iter_tmp, annotation) {
r_bin_java_print_annotation_summary (annotation);
}
}
R_API RBinJavaAnnotationsArray *r_bin_java_annotation_array_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
RBinJavaAnnotation *annotation;
RBinJavaAnnotationsArray *annotation_array;
ut32 i;
ut64 offset = 0;
annotation_array = (RBinJavaAnnotationsArray *) malloc (sizeof (RBinJavaAnnotationsArray));
if (annotation_array == NULL) {
// TODO eprintf
return NULL;
}
annotation_array->num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
annotation_array->annotations = r_list_new ();
for (i = 0; i < annotation_array->num_annotations; i++) {
annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
}
if (annotation == NULL) {
// TODO eprintf
}
r_list_append (annotation_array->annotations, (void *) annotation);
}
annotation_array->size = offset;
return annotation_array;
}
R_API RBinJavaAttrInfo *r_bin_java_rtv_annotations_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.annotation_array.num_annotations; i++) {
int len = sz - offset;
if (len < 1) {
break;
}
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, len, buf_offset + offset);
if (annotation) {
offset += annotation->size;
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
}
attr->size = offset;
}
return attr;
}
R_API ut64 r_bin_java_annotation_array_calc_size(RBinJavaAnnotationsArray *annotation_array) {
ut64 size = 0;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaAnnotation *annotation;
if (annotation_array->annotations == NULL) {
// TODO eprintf
return size;
}
// annotation_array->num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
size += 2;
r_list_foreach_safe (annotation_array->annotations, iter, iter_tmp, annotation) {
size += r_bin_java_annotation_calc_size (annotation);
}
return size;
}
R_API ut64 r_bin_java_rtv_annotations_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr == NULL) {
// TODO eprintf allocation fail
return size;
}
size += (6 + r_bin_java_annotation_array_calc_size (&(attr->info.annotation_array)));
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_rti_annotations_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR;
attr->info.annotation_array.num_annotations = R_BIN_JAVA_USHORT (buffer, offset);
offset += 2;
attr->info.annotation_array.annotations = r_list_newf (r_bin_java_annotation_free);
for (i = 0; i < attr->info.rtv_annotations_attr.num_annotations; i++) {
RBinJavaAnnotation *annotation = r_bin_java_annotation_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation) {
offset += annotation->size;
}
r_list_append (attr->info.annotation_array.annotations, (void *) annotation);
}
attr->size = offset;
}
return attr;
}
R_API ut64 r_bin_java_rti_annotations_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
if (attr == NULL) {
// TODO eprintf allocation fail
return size;
}
size += (6 + r_bin_java_annotation_array_calc_size (&(attr->info.annotation_array)));
return size;
}
R_API void r_bin_java_rtv_annotations_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR) {
r_list_free (attr->info.annotation_array.annotations);
free (attr->metas);
free (attr->name);
free (attr);
}
}
R_API void r_bin_java_rti_annotations_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR) {
r_list_free (attr->info.annotation_array.annotations);
free (attr->metas);
free (attr->name);
free (attr);
}
}
R_API void r_bin_java_print_rtv_annotations_attr_summary(RBinJavaAttrInfo *attr) {
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_ANNOTATION_ATTR) {
Eprintf ("Runtime Visible Annotations Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
r_bin_java_print_annotation_array_summary (&attr->info.annotation_array);
}
}
R_API void r_bin_java_print_rti_annotations_attr_summary(RBinJavaAttrInfo *attr) {
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_ANNOTATION_ATTR) {
Eprintf ("Runtime Invisible Annotations Attribute Information:\n");
Eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
Eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
Eprintf (" Attribute Length: %d\n", attr->length);
r_bin_java_print_annotation_array_summary (&attr->info.annotation_array);
}
}
R_API ut64 r_bin_java_rtip_annotations_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaAnnotationsArray *annotation_array;
if (attr == NULL) {
// TODO eprintf allocation fail
return size;
}
// attr->info.rtip_annotations_attr.num_parameters = buffer[offset];
size += (6 + 1);
r_list_foreach_safe (attr->info.rtip_annotations_attr.parameter_annotations, iter, iter_tmp, annotation_array) {
if (annotation_array) {
size += r_bin_java_annotation_array_calc_size (annotation_array);
}
}
return size;
}
R_API RBinJavaAttrInfo *r_bin_java_rtip_annotations_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
RBinJavaAnnotationsArray *annotation_array;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATION_ATTR;
attr->info.rtip_annotations_attr.num_parameters = buffer[offset];
offset += 1;
attr->info.rtip_annotations_attr.parameter_annotations = r_list_newf (r_bin_java_annotation_array_free);
for (i = 0; i < attr->info.rtip_annotations_attr.num_parameters; i++) {
annotation_array = r_bin_java_annotation_array_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation_array == NULL) {}
if (annotation_array) {
offset += annotation_array->size;
}
r_list_append (attr->info.rtip_annotations_attr.parameter_annotations, (void *) annotation_array);
}
attr->size = offset;
}
return attr;
}
R_API RBinJavaAttrInfo *r_bin_java_rtvp_annotations_attr_new(ut8 *buffer, ut64 sz, ut64 buf_offset) {
ut32 i = 0;
RBinJavaAttrInfo *attr = NULL;
ut64 offset = 0;
attr = r_bin_java_default_attr_new (buffer, sz, buf_offset);
offset += 6;
RBinJavaAnnotationsArray *annotation_array;
if (attr) {
attr->type = R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_PARAMETER_ANNOTATION_ATTR;
attr->info.rtvp_annotations_attr.num_parameters = buffer[offset];
offset += 1;
attr->info.rtvp_annotations_attr.parameter_annotations = r_list_newf (r_bin_java_annotation_array_free);
for (i = 0; i < attr->info.rtvp_annotations_attr.num_parameters; i++) {
annotation_array = r_bin_java_annotation_array_new (buffer + offset, sz - offset, buf_offset + offset);
if (annotation_array == NULL) {}
if (annotation_array) {
offset += annotation_array->size;
}
r_list_append (attr->info.rtvp_annotations_attr.parameter_annotations, (void *) annotation_array);
}
attr->size = offset;
}
return attr;
}
R_API ut64 r_bin_java_rtvp_annotations_attr_calc_size(RBinJavaAttrInfo *attr) {
ut64 size = 0;
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaAnnotationsArray *annotation_array;
if (!attr) {
return size;
}
size += (6 + 1);
r_list_foreach_safe (attr->info.rtvp_annotations_attr.parameter_annotations,
iter, iter_tmp, annotation_array) {
if (annotation_array) {
size += r_bin_java_annotation_array_calc_size (
annotation_array);
}
}
return size;
}
R_API void r_bin_java_rtvp_annotations_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) {
if (attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_PARAMETER_ANNOTATION_ATTR) {
r_list_free (attr->info.rtvp_annotations_attr.parameter_annotations);
}
free (attr->name);
free (attr->metas);
free (attr);
}
}
R_API void r_bin_java_rtip_annotations_attr_free(void /*RBinJavaAttrInfo*/ *a) {
RBinJavaAttrInfo *attr = a;
if (attr) { // && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATION_ATTR) {
r_list_free (attr->info.rtip_annotations_attr.parameter_annotations);
free (attr->metas);
free (attr->name);
free (attr);
}
}
R_API void r_bin_java_print_rtvp_annotations_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaAnnotationsArray *annotation_array = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_VISIBLE_PARAMETER_ANNOTATION_ATTR) {
eprintf ("Runtime Visible Parameter Annotations Attribute Information:\n");
eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
eprintf (" Attribute Length: %d\n", attr->length);
eprintf (" Number of Runtime Invisible Parameters: %d\n", attr->info.rtvp_annotations_attr.num_parameters);
r_list_foreach_safe (attr->info.rtvp_annotations_attr.parameter_annotations, iter, iter_tmp, annotation_array) {
r_bin_java_print_annotation_array_summary (annotation_array);
}
}
}
R_API void r_bin_java_print_rtip_annotations_attr_summary(RBinJavaAttrInfo *attr) {
RBinJavaAnnotationsArray *annotation_array = NULL;
RListIter *iter = NULL, *iter_tmp = NULL;
if (attr && attr->type == R_BIN_JAVA_ATTR_TYPE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATION_ATTR) {
eprintf ("Runtime Invisible Parameter Annotations Attribute Information:\n");
eprintf (" Attribute Offset: 0x%08"PFMT64x "\n", attr->file_offset);
eprintf (" Attribute Name Index: %d (%s)\n", attr->name_idx, attr->name);
eprintf (" Attribute Length: %d\n", attr->length);
eprintf (" Number of Runtime Invisible Parameters: %d\n", attr->info.rtip_annotations_attr.num_parameters);
r_list_foreach_safe (attr->info.rtip_annotations_attr.parameter_annotations, iter, iter_tmp, annotation_array) {
r_bin_java_print_annotation_array_summary (annotation_array);
}
}
}
R_API RBinJavaCPTypeObj *r_bin_java_find_cp_name_and_type_info(RBinJavaObj *bin, ut16 name_idx, ut16 descriptor_idx) {
RListIter *iter, *iter_tmp;
RBinJavaCPTypeObj *res = NULL, *obj = NULL;
IFDBG eprintf("Looking for name_idx: %d and descriptor_idx: %d\n", name_idx, descriptor_idx);
r_list_foreach_safe (bin->cp_list, iter, iter_tmp, obj) {
if (obj && obj->tag == R_BIN_JAVA_CP_NAMEANDTYPE) {
IFDBG eprintf("RBinJavaCPTypeNameAndType has name_idx: %d and descriptor_idx: %d\n",
obj->info.cp_name_and_type.name_idx, obj->info.cp_name_and_type.descriptor_idx);
if (obj->info.cp_name_and_type.name_idx == name_idx &&
obj->info.cp_name_and_type.descriptor_idx == descriptor_idx) {
res = obj;
break;
}
}
}
return res;
}
R_API char *r_bin_java_resolve_cp_idx_type(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaCPTypeObj *item = NULL;
char *str = NULL;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
// r_bin_java_new_bin(BIN_OBJ);
return NULL;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
str = strdup (((RBinJavaCPTypeMetas *) item->metas->type_info)->name);
} else {
str = strdup ("INVALID");
}
return str;
}
R_API RBinJavaCPTypeObj *r_bin_java_find_cp_ref_info_from_name_and_type(RBinJavaObj *bin, ut16 name_idx, ut16 descriptor_idx) {
RBinJavaCPTypeObj *obj = r_bin_java_find_cp_name_and_type_info (bin, name_idx, descriptor_idx);
if (obj) {
return r_bin_java_find_cp_ref_info (bin, obj->metas->ord);
}
return NULL;
}
R_API RBinJavaCPTypeObj *r_bin_java_find_cp_ref_info(RBinJavaObj *bin, ut16 name_and_type_idx) {
RListIter *iter, *iter_tmp;
RBinJavaCPTypeObj *res = NULL, *obj = NULL;
r_list_foreach_safe (bin->cp_list, iter, iter_tmp, obj) {
if (obj->tag == R_BIN_JAVA_CP_FIELDREF &&
obj->info.cp_field.name_and_type_idx == name_and_type_idx) {
res = obj;
break;
} else if (obj->tag == R_BIN_JAVA_CP_METHODREF &&
obj->info.cp_method.name_and_type_idx == name_and_type_idx) {
res = obj;
break;
}
}
return res;
}
R_API char *r_bin_java_resolve(RBinJavaObj *BIN_OBJ, int idx, ut8 space_bn_name_type) {
// TODO XXX FIXME add a size parameter to the str when it is passed in
RBinJavaCPTypeObj *item = NULL, *item2 = NULL;
char *class_str = NULL,
*name_str = NULL,
*desc_str = NULL,
*string_str = NULL,
*empty = "",
*cp_name = NULL,
*str = NULL;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
// r_bin_java_new_bin(BIN_OBJ);
return NULL;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
IFDBG eprintf("java_resolve Resolved: (%d) %s\n", idx, cp_name);
} else {
str = malloc (512);
if (str) {
snprintf (str, 512, "(%d) INVALID CP_OBJ", idx);
}
return str;
}
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
if (strcmp (cp_name, "Class") == 0) {
item2 = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
// str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, idx-1);
class_str = empty;
class_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item2);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item2);
if (!desc_str) {
desc_str = empty;
}
str = r_str_newf ("%s%s%s", name_str,
space_bn_name_type ? " " : "", desc_str);
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (!strcmp (cp_name, "MethodRef") ||
!strcmp (cp_name, "FieldRef") ||
!strcmp (cp_name, "InterfaceMethodRef")) {
/*
* The MethodRef, FieldRef, and InterfaceMethodRef structures
*/
class_str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, item->info.cp_method.class_idx);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
str = r_str_newf ("%s/%s%s%s", class_str, name_str,
space_bn_name_type ? " " : "", desc_str);
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (!strcmp (cp_name, "String")) {
string_str = r_bin_java_get_utf8_from_bin_cp_list (BIN_OBJ, item->info.cp_string.string_idx);
str = NULL;
IFDBG eprintf("java_resolve String got: (%d) %s\n", item->info.cp_string.string_idx, string_str);
if (!string_str) {
string_str = empty;
}
str = r_str_newf ("\"%s\"", string_str);
IFDBG eprintf("java_resolve String return: %s\n", str);
if (string_str != empty) {
free (string_str);
}
} else if (!strcmp (cp_name, "Utf8")) {
char *tmp_str = convert_string ((const char *) item->info.cp_utf8.bytes, item->info.cp_utf8.length);
ut32 tmp_str_len = tmp_str ? strlen (tmp_str) + 4 : 0;
if (tmp_str) {
str = malloc (tmp_str_len + 4);
snprintf (str, tmp_str_len + 4, "\"%s\"", tmp_str);
}
free (tmp_str);
} else if (!strcmp (cp_name, "Long")) {
str = r_str_newf ("0x%"PFMT64x, r_bin_java_raw_to_long (item->info.cp_long.bytes.raw, 0));
} else if (!strcmp (cp_name, "Double")) {
str = r_str_newf ("%f", r_bin_java_raw_to_double (item->info.cp_double.bytes.raw, 0));
} else if (!strcmp (cp_name, "Integer")) {
str = r_str_newf ("0x%08x", R_BIN_JAVA_UINT (item->info.cp_integer.bytes.raw, 0));
} else if (!strcmp (cp_name, "Float")) {
str = r_str_newf ("%f", R_BIN_JAVA_FLOAT (item->info.cp_float.bytes.raw, 0));
} else if (!strcmp (cp_name, "NameAndType")) {
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
str = r_str_newf ("%s%s%s", name_str, space_bn_name_type ? " " : "", desc_str);
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else {
str = strdup ("(null)");
}
return str;
}
R_API ut8 r_bin_java_does_cp_idx_ref_method(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaField *fm_type = NULL;
RListIter *iter;
ut8 res = 0;
r_list_foreach (BIN_OBJ->methods_list, iter, fm_type) {
if (fm_type->field_ref_cp_obj->metas->ord == idx) {
res = 1;
break;
}
}
return res;
}
R_API ut8 r_bin_java_does_cp_idx_ref_field(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaField *fm_type = NULL;
RListIter *iter;
ut8 res = 0;
r_list_foreach (BIN_OBJ->fields_list, iter, fm_type) {
if (fm_type->field_ref_cp_obj->metas->ord == idx) {
res = 1;
break;
}
}
return res;
}
R_API char *r_bin_java_get_method_name(RBinJavaObj *bin_obj, ut32 idx) {
char *name = NULL;
if (idx < r_list_length (bin_obj->methods_list)) {
RBinJavaField *fm_type = r_list_get_n (bin_obj->methods_list, idx);
name = strdup (fm_type->name);
}
return name;
}
R_API RList *r_bin_java_get_method_num_name(RBinJavaObj *bin_obj) {
ut32 i = 0;
RListIter *iter = NULL;
RBinJavaField *fm_type;
RList *res = r_list_newf (free);
r_list_foreach (bin_obj->methods_list, iter, fm_type) {
ut32 len = strlen (fm_type->name) + 30;
char *str = malloc (len);
snprintf (str, len, "%d %s", i, fm_type->name);
++i;
r_list_append (res, str);
}
return res;
}
/*
R_API int r_bin_java_does_cp_obj_ref_idx (RBinJavaObj *bin_obj, RBinJavaCPTypeObj *cp_obj, ut16 idx) {
int res = false;
RBinJavaCPTypeObj *t_obj = NULL;
if (cp_obj) {
switch (cp_obj->tag) {
case R_BIN_JAVA_CP_NULL: break;
case R_BIN_JAVA_CP_UTF8: break;
case R_BIN_JAVA_CP_UNKNOWN: break;
case R_BIN_JAVA_CP_INTEGER: break;
case R_BIN_JAVA_CP_FLOAT: break;
case R_BIN_JAVA_CP_LONG: break;
case R_BIN_JAVA_CP_DOUBLE: break;
case R_BIN_JAVA_CP_CLASS:
res = idx == cp_obj->info.cp_class.name_idx ? true : false;
break;
case R_BIN_JAVA_CP_STRING:
res = idx == cp_obj->info.cp_string.string_idx ? true : false;
break;
case R_BIN_JAVA_CP_METHODREF: break;// check if idx is referenced here
case R_BIN_JAVA_CP_INTERFACEMETHOD_REF: break; // check if idx is referenced here
case R_BIN_JAVA_CP_FIELDREF:
t_obj = r_bin_java_get_item_from_cp (bin_obj, cp_obj->info.cp_method.class_idx);
res = r_bin_java_does_cp_obj_ref_idx (bin_obj, t_obj, idx);
if (res == true) break;
t_obj = r_bin_java_get_item_from_cp (bin_obj, cp_obj->info.cp_method.name_and_type_idx);
res = r_bin_java_does_cp_obj_ref_idx (bin_obj, t_obj, idx);
break;
case R_BIN_JAVA_CP_NAMEANDTYPE: break;// check if idx is referenced here
obj->info.cp_name_and_type.name_idx
case R_BIN_JAVA_CP_METHODHANDLE: break;// check if idx is referenced here
case R_BIN_JAVA_CP_METHODTYPE: break;// check if idx is referenced here
case R_BIN_JAVA_CP_INVOKEDYNAMIC: break;// check if idx is referenced here
}
}
}
*/
R_API RList *r_bin_java_find_cp_const_by_val_long(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
RList *res = r_list_newf (free);
ut32 *v = NULL;
RListIter *iter;
RBinJavaCPTypeObj *cp_obj;
eprintf ("Looking for 0x%08x\n", R_BIN_JAVA_UINT (bytes, 0));
r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
if (cp_obj->tag == R_BIN_JAVA_CP_LONG) {
if (len == 8 && r_bin_java_raw_to_long (cp_obj->info.cp_long.bytes.raw, 0) == r_bin_java_raw_to_long (bytes, 0)) {
// TODO: we can safely store a ut32 inside the list without having to allocate it
v = malloc (sizeof (ut32));
if (!v) {
r_list_free (res);
return NULL;
}
*v = cp_obj->idx;
r_list_append (res, v);
}
}
}
return res;
}
R_API RList *r_bin_java_find_cp_const_by_val_double(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
RList *res = r_list_newf (free);
ut32 *v = NULL;
RListIter *iter;
RBinJavaCPTypeObj *cp_obj;
eprintf ("Looking for %f\n", r_bin_java_raw_to_double (bytes, 0));
r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
if (cp_obj->tag == R_BIN_JAVA_CP_DOUBLE) {
if (len == 8 && r_bin_java_raw_to_double (cp_obj->info.cp_long.bytes.raw, 0) == r_bin_java_raw_to_double (bytes, 0)) {
v = malloc (sizeof (ut32));
if (!v) {
r_list_free (res);
return NULL;
}
*v = cp_obj->idx;
r_list_append (res, v);
}
}
}
return res;
}
R_API RList *r_bin_java_find_cp_const_by_val_float(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
RList *res = r_list_newf (free);
ut32 *v = NULL;
RListIter *iter;
RBinJavaCPTypeObj *cp_obj;
eprintf ("Looking for %f\n", R_BIN_JAVA_FLOAT (bytes, 0));
r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
if (cp_obj->tag == R_BIN_JAVA_CP_FLOAT) {
if (len == 4 && R_BIN_JAVA_FLOAT (cp_obj->info.cp_long.bytes.raw, 0) == R_BIN_JAVA_FLOAT (bytes, 0)) {
v = malloc (sizeof (ut32));
if (!v) {
r_list_free (res);
return NULL;
}
*v = cp_obj->idx;
r_list_append (res, v);
}
}
}
return res;
}
R_API RList *r_bin_java_find_cp_const_by_val(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len, const char t) {
switch (t) {
case R_BIN_JAVA_CP_UTF8: return r_bin_java_find_cp_const_by_val_utf8 (bin_obj, bytes, len);
case R_BIN_JAVA_CP_INTEGER: return r_bin_java_find_cp_const_by_val_int (bin_obj, bytes, len);
case R_BIN_JAVA_CP_FLOAT: return r_bin_java_find_cp_const_by_val_float (bin_obj, bytes, len);
case R_BIN_JAVA_CP_LONG: return r_bin_java_find_cp_const_by_val_long (bin_obj, bytes, len);
case R_BIN_JAVA_CP_DOUBLE: return r_bin_java_find_cp_const_by_val_double (bin_obj, bytes, len);
case R_BIN_JAVA_CP_UNKNOWN:
default:
eprintf ("Failed to perform the search for: %s\n", bytes);
return r_list_new ();
}
}
// #if 0
// Attempted to clean up these functions and remove them since they are "unused" but without
// them there are some compile time warnings, because other projects actually depend on these
// for some form of information.
R_API void U(add_cp_objs_to_sdb)(RBinJavaObj * bin) {
/*
Add Constant Pool Serialized Object to an Array
the key for this info is:
Key:
java.<classname>.cp_obj
Each Value varies by type:
In general its:
<ordinal>.<file_offset>.<type_name>.[type specific stuff]
Example:
UTF-8: <ordinal>.<file_offset>.<type_name>.<strlen>.<hexlified(str)>
Integer: <ordinal>.<file_offset>.<type_name>.<abs(int)>
Long: <ordinal>.<file_offset>.<type_name>.abs(long)>
FieldRef/MethodRef: <ordinal>.<file_offset>.<type_name>.<class_idx>.<name_and_type_idx>
*/
ut32 idx = 0, class_name_inheap = 1;
RBinJavaCPTypeObj *cp_obj = NULL;
char *key = NULL,
*value = NULL;
char str_cnt[40];
char *class_name = r_bin_java_get_this_class_name (bin);
ut32 key_buf_size = 0;
if (class_name == NULL) {
class_name = "unknown";
class_name_inheap = 0;
}
// 4 - format, 8 number, 1 null byte, 7 "unknown"
key_buf_size = strlen (class_name) + 4 + 8 + 1;
key = malloc (key_buf_size);
if (key == NULL) {
if (class_name_inheap) {
free (class_name);
}
return;
}
snprintf (key, key_buf_size - 1, "%s.cp_count", class_name);
key[key_buf_size - 1] = 0;
snprintf (str_cnt, 39, "%d", bin->cp_count);
str_cnt[39] = 0;
sdb_set (bin->kv, key, value, 0);
// sdb_alist(bin->kv, key);
for (idx = 0; idx < bin->cp_count; idx++) {
snprintf (key, key_buf_size - 1, "%s.cp.%d", class_name, idx);
key[key_buf_size - 1] = 0;
cp_obj = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (bin, idx);
IFDBG eprintf("Adding %s to the sdb.\n", key);
if (cp_obj) {
value = ((RBinJavaCPTypeMetas *)
cp_obj->metas->type_info)->
allocs->stringify_obj (cp_obj);
sdb_set (bin->kv, key, value, 0);
free (value);
}
}
if (class_name_inheap) {
free (class_name);
}
free (key);
}
R_API void U(add_field_infos_to_sdb)(RBinJavaObj * bin) {
/*
*** Experimental and May Change ***
Add field information to an Array
the key for this info variable depenedent on addr, method ordinal, etc.
Key 1, mapping to method key:
java.<file_offset> = <field_key>
Key 3, method description
<field_key>.info = [<access str>, <class_name>, <name>, <signature>]
key 4, method meta
<field_key>.meta = [<file_offset>, ?]
*/
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaField *fm_type;
ut32 key_size = 255,
value_buffer_size = 1024,
class_name_inheap = 1;
char *field_key = NULL,
*field_key_value = NULL,
*value_buffer = NULL;
char *class_name = r_bin_java_get_this_class_name (bin);
if (class_name == NULL) {
class_name = "unknown";
class_name_inheap = 0;
}
key_size += strlen (class_name);
value_buffer_size += strlen (class_name);
field_key = malloc (key_size);
value_buffer = malloc (value_buffer_size);
field_key_value = malloc (key_size);
snprintf (field_key, key_size, "%s.methods", class_name);
field_key[key_size - 1] = 0;
r_list_foreach_safe (bin->fields_list, iter, iter_tmp, fm_type) {
char number_buffer[80];
ut64 file_offset = fm_type->file_offset + bin->loadaddr;
snprintf (number_buffer, sizeof (number_buffer), "0x%04"PFMT64x, file_offset);
IFDBG eprintf("Inserting: []%s = %s\n", field_key, number_buffer);
sdb_array_push (bin->kv, field_key, number_buffer, 0);
}
r_list_foreach_safe (bin->fields_list, iter, iter_tmp, fm_type) {
ut64 field_offset = fm_type->file_offset + bin->loadaddr;
// generate method specific key & value
snprintf (field_key, key_size, "%s.0x%04"PFMT64x, class_name, field_offset);
field_key[key_size - 1] = 0;
snprintf (field_key_value, key_size, "%s.0x%04"PFMT64x ".field", class_name, field_offset);
field_key_value[key_size - 1] = 0;
sdb_set (bin->kv, field_key, field_key_value, 0);
IFDBG eprintf("Inserting: %s = %s\n", field_key, field_key_value);
// generate info key, and place values in method info array
snprintf (field_key, key_size, "%s.info", field_key_value);
field_key[key_size - 1] = 0;
snprintf (value_buffer, value_buffer_size, "%s", fm_type->flags_str);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, field_key, value_buffer, 0);
IFDBG eprintf("Inserting: []%s = %s\n", field_key, value_buffer);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->class_name);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, field_key, value_buffer, 0);
IFDBG eprintf("Inserting: []%s = %s\n", field_key, value_buffer);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->name);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, field_key, value_buffer, 0);
IFDBG eprintf("Inserting: []%s = %s\n", field_key, value_buffer);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->descriptor);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, field_key, value_buffer, 0);
IFDBG eprintf("Inserting: []%s = %s\n", field_key, value_buffer);
}
free (field_key);
free (field_key_value);
free (value_buffer);
if (class_name_inheap) {
free (class_name);
}
}
R_API void U(add_method_infos_to_sdb)(RBinJavaObj * bin) {
/*
*** Experimental and May Change ***
Add Mehtod information to an Array
the key for this info variable depenedent on addr, method ordinal, etc.
Key 1, mapping to method key:
java.<file_offset> = <method_key>
Key 2, basic code information
<method_key>.code = [<addr>, <size>]
Key 3, method description
<method_key>.info = [<access str>, <class_name>, <name>, <signature>,]
key 4, method meta
<method_key>.meta = [<file_offset>, ?]
// TODO in key 3 add <class_name>?
e.g. <access str>.<name>.<signature>
Note: method name not used because of collisions with operator overloading
also take note that code offset and the method offset are not the same
values.
*/
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaField *fm_type;
ut32 key_size = 255,
value_buffer_size = 1024,
class_name_inheap = 1;
char *method_key = NULL,
*method_key_value = NULL,
*value_buffer = NULL;
char *class_name = r_bin_java_get_this_class_name (bin);
ut64 baddr = bin->loadaddr;
if (class_name == NULL) {
class_name = "unknown";
class_name_inheap = 0;
}
key_size += strlen (class_name);
value_buffer_size += strlen (class_name);
method_key = malloc (key_size);
value_buffer = malloc (value_buffer_size);
method_key_value = malloc (key_size);
snprintf (method_key, key_size, "%s.methods", class_name);
method_key[key_size - 1] = 0;
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
char number_buffer[80];
ut64 file_offset = fm_type->file_offset + baddr;
snprintf (number_buffer, sizeof (number_buffer), "0x%04"PFMT64x, file_offset);
sdb_array_push (bin->kv, method_key, number_buffer, 0);
}
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
ut64 code_offset = r_bin_java_get_method_code_offset (fm_type) + baddr,
code_size = r_bin_java_get_method_code_size (fm_type),
method_offset = fm_type->file_offset + baddr;
// generate method specific key & value
snprintf (method_key, key_size, "%s.0x%04"PFMT64x, class_name, code_offset);
method_key[key_size - 1] = 0;
snprintf (method_key_value, key_size, "%s.0x%04"PFMT64x ".method", class_name, method_offset);
method_key_value[key_size - 1] = 0;
IFDBG eprintf("Adding %s to sdb_array: %s\n", method_key_value, method_key);
sdb_set (bin->kv, method_key, method_key_value, 0);
// generate code key and values
snprintf (method_key, key_size, "%s.code", method_key_value);
method_key[key_size - 1] = 0;
snprintf (value_buffer, value_buffer_size, "0x%04"PFMT64x, code_offset);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, method_key, value_buffer, 0);
snprintf (value_buffer, value_buffer_size, "0x%04"PFMT64x, code_size);
value_buffer[value_buffer_size - 1] = 0;
sdb_array_push (bin->kv, method_key, value_buffer, 0);
// generate info key, and place values in method info array
snprintf (method_key, key_size, "%s.info", method_key_value);
method_key[key_size - 1] = 0;
snprintf (value_buffer, value_buffer_size, "%s", fm_type->flags_str);
value_buffer[value_buffer_size - 1] = 0;
IFDBG eprintf("Adding %s to sdb_array: %s\n", value_buffer, method_key);
sdb_array_push (bin->kv, method_key, value_buffer, 0);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->class_name);
value_buffer[value_buffer_size - 1] = 0;
IFDBG eprintf("Adding %s to sdb_array: %s\n", value_buffer, method_key);
sdb_array_push (bin->kv, method_key, value_buffer, 0);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->name);
value_buffer[value_buffer_size - 1] = 0;
IFDBG eprintf("Adding %s to sdb_array: %s\n", value_buffer, method_key);
sdb_array_push (bin->kv, method_key, value_buffer, 0);
snprintf (value_buffer, value_buffer_size, "%s", fm_type->descriptor);
value_buffer[value_buffer_size - 1] = 0;
IFDBG eprintf("Adding %s to sdb_array: %s\n", value_buffer, method_key);
sdb_array_push (bin->kv, method_key, value_buffer, 0);
}
free (method_key);
free (method_key_value);
free (value_buffer);
if (class_name_inheap) {
free (class_name);
}
}
R_API RList *U(r_bin_java_get_args_from_bin)(RBinJavaObj * bin_obj, ut64 addr) {
RBinJavaField *fm_type = r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr);
return fm_type ? r_bin_java_get_args (fm_type) : NULL;
}
R_API RList *U(r_bin_java_get_ret_from_bin)(RBinJavaObj * bin_obj, ut64 addr) {
RBinJavaField *fm_type = r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr);
return fm_type ? r_bin_java_get_ret (fm_type) : NULL;
}
R_API char *U(r_bin_java_get_fcn_name_from_bin)(RBinJavaObj * bin_obj, ut64 addr) {
RBinJavaField *fm_type = r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr);
return fm_type && fm_type->name ? strdup (fm_type->name) : NULL;
}
R_API int U(r_bin_java_is_method_static)(RBinJavaObj * bin_obj, ut64 addr) {
RBinJavaField *fm_type = r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr);
return fm_type && fm_type->flags & R_BIN_JAVA_METHOD_ACC_STATIC;
}
R_API int U(r_bin_java_is_method_private)(RBinJavaObj * bin_obj, ut64 addr) {
return r_bin_java_is_fm_type_private (r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr));
}
R_API int U(r_bin_java_is_method_protected)(RBinJavaObj * bin_obj, ut64 addr) {
return r_bin_java_is_fm_type_protected (
r_bin_java_get_method_code_attribute_with_addr (bin_obj, addr));
}
R_API int r_bin_java_print_method_idx_summary(RBinJavaObj *bin_obj, ut32 idx) {
int res = false;
if (idx < r_list_length (bin_obj->methods_list)) {
RBinJavaField *fm_type = r_list_get_n (bin_obj->methods_list, idx);
r_bin_java_print_method_summary (fm_type);
res = true;
}
return res;
}
R_API ut32 r_bin_java_get_method_count(RBinJavaObj *bin_obj) {
return r_list_length (bin_obj->methods_list);
}
R_API RList *r_bin_java_get_interface_names(RBinJavaObj *bin) {
RList *interfaces_names = r_list_new ();
RListIter *iter;
RBinJavaInterfaceInfo *ifobj;
r_list_foreach (bin->interfaces_list, iter, ifobj) {
if (ifobj && ifobj->name) {
r_list_append (interfaces_names, strdup (ifobj->name));
}
}
return interfaces_names;
}
R_API ut64 r_bin_java_get_main(RBinJavaObj *bin) {
if (bin->main_code_attr) {
return bin->main_code_attr->info.code_attr.code_offset + bin->loadaddr;
}
return 0;
}
R_API RBinJavaObj *r_bin_java_new(const char *file, ut64 loadaddr, Sdb *kv) {
ut8 *buf;
RBinJavaObj *bin = R_NEW0 (RBinJavaObj);
if (!bin) {
return NULL;
}
bin->file = strdup (file);
if (!(buf = (ut8 *) r_file_slurp (file, &bin->size))) {
return r_bin_java_free (bin);
}
if (!r_bin_java_new_bin (bin, loadaddr, kv, buf, bin->size)) {
r_bin_java_free (bin);
bin = NULL;
}
free (buf);
return bin;
}
R_API ut64 r_bin_java_get_class_entrypoint(RBinJavaObj *bin) {
if (bin->cf2.this_class_entrypoint_code_attr) {
return bin->cf2.this_class_entrypoint_code_attr->info.code_attr.code_offset;
}
return 0;
}
R_API RList *r_bin_java_get_method_exception_table_with_addr(RBinJavaObj *bin, ut64 addr) {
RListIter *iter = NULL, *iter_tmp = NULL;
RBinJavaField *fm_type, *res = NULL;
if (!bin && R_BIN_JAVA_GLOBAL_BIN) {
bin = R_BIN_JAVA_GLOBAL_BIN;
}
if (!bin) {
eprintf ("Attempting to analyse function when the R_BIN_JAVA_GLOBAL_BIN has not been set.\n");
return NULL;
}
r_list_foreach_safe (bin->methods_list, iter, iter_tmp, fm_type) {
ut64 offset = r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr,
size = r_bin_java_get_method_code_size (fm_type);
if (addr >= offset && addr <= size + offset) {
res = fm_type;
}
}
if (res) {
RBinJavaAttrInfo *code_attr = r_bin_java_get_method_code_attribute (res);
return code_attr->info.code_attr.exception_table;
}
return NULL;
}
R_API const RList *r_bin_java_get_methods_list(RBinJavaObj *bin) {
if (bin) {
return bin->methods_list;
}
if (R_BIN_JAVA_GLOBAL_BIN) {
return R_BIN_JAVA_GLOBAL_BIN->methods_list;
}
return NULL;
}
R_API RList *r_bin_java_get_bin_obj_list_thru_obj(RBinJavaObj *bin_obj) {
RList *the_list;
Sdb *sdb;
if (!bin_obj) {
return NULL;
}
sdb = bin_obj->AllJavaBinObjs;
if (!sdb) {
return NULL;
}
the_list = r_list_new ();
if (!the_list) {
return NULL;
}
sdb_foreach (sdb, sdb_iterate_build_list, (void *) the_list);
return the_list;
}
R_API RList *r_bin_java_extract_all_bin_type_values(RBinJavaObj *bin_obj) {
RListIter *fm_type_iter;
RList *all_types = r_list_new ();
RBinJavaField *fm_type;
// get all field types
r_list_foreach (bin_obj->fields_list, fm_type_iter, fm_type) {
char *desc = NULL;
if (!extract_type_value (fm_type->descriptor, &desc)) {
return NULL;
}
IFDBG eprintf("Adding field type: %s\n", desc);
r_list_append (all_types, desc);
}
// get all method types
r_list_foreach (bin_obj->methods_list, fm_type_iter, fm_type) {
RList *the_list = r_bin_java_extract_type_values (fm_type->descriptor);
RListIter *desc_iter;
char *str;
r_list_foreach (the_list, desc_iter, str) {
if (str && *str != '(' && *str != ')') {
r_list_append (all_types, strdup (str));
IFDBG eprintf("Adding method type: %s\n", str);
}
}
r_list_free (the_list);
}
return all_types;
}
R_API RList *r_bin_java_get_method_definitions(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RList *the_list = r_list_new ();
if (!the_list) {
return NULL;
}
RListIter *iter = NULL;
if (!bin) {
return the_list;
}
r_list_foreach (bin->methods_list, iter, fm_type) {
char *method_proto = r_bin_java_get_method_definition (fm_type);
// eprintf ("Method prototype: %s\n", method_proto);
r_list_append (the_list, method_proto);
}
return the_list;
}
R_API RList *r_bin_java_get_field_definitions(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RList *the_list = r_list_new ();
if (!the_list) {
return NULL;
}
RListIter *iter = NULL;
if (!bin) {
return the_list;
}
r_list_foreach (bin->fields_list, iter, fm_type) {
char *field_def = r_bin_java_get_field_definition (fm_type);
// eprintf ("Field def: %s, %s, %s, %s\n", fm_type->name, fm_type->descriptor, fm_type->flags_str, field_def);
r_list_append (the_list, field_def);
}
return the_list;
}
R_API RList *r_bin_java_get_import_definitions(RBinJavaObj *bin) {
RList *the_list = r_bin_java_get_lib_names (bin);
RListIter *iter = NULL;
char *new_str;
if (!bin || !the_list) {
return the_list;
}
r_list_foreach (the_list, iter, new_str) {
while (*new_str) {
if (*new_str == '/') {
*new_str = '.';
}
new_str++;
}
}
return the_list;
}
R_API RList *r_bin_java_get_field_offsets(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RList *the_list = r_list_new ();
if (!the_list) {
return NULL;
}
RListIter *iter = NULL;
ut64 *paddr = NULL;
if (!bin) {
return the_list;
}
the_list->free = free;
r_list_foreach (bin->fields_list, iter, fm_type) {
paddr = malloc (sizeof(ut64));
if (!paddr) {
r_list_free (the_list);
return NULL;
}
*paddr = fm_type->file_offset + bin->loadaddr;
// eprintf ("Field def: %s, %s, %s, %s\n", fm_type->name, fm_type->descriptor, fm_type->flags_str, field_def);
r_list_append (the_list, paddr);
}
return the_list;
}
R_API RList *r_bin_java_get_method_offsets(RBinJavaObj *bin) {
RBinJavaField *fm_type = NULL;
RList *the_list = r_list_new ();
RListIter *iter = NULL;
ut64 *paddr = NULL;
if (!bin) {
return the_list;
}
the_list->free = free;
r_list_foreach (bin->methods_list, iter, fm_type) {
paddr = R_NEW0 (ut64);
*paddr = fm_type->file_offset + bin->loadaddr;
r_list_append (the_list, paddr);
}
return the_list;
}
R_API ut16 r_bin_java_calculate_field_access_value(const char *access_flags_str) {
return calculate_access_value (access_flags_str, FIELD_ACCESS_FLAGS);
}
R_API ut16 r_bin_java_calculate_class_access_value(const char *access_flags_str) {
return calculate_access_value (access_flags_str, CLASS_ACCESS_FLAGS);
}
R_API ut16 r_bin_java_calculate_method_access_value(const char *access_flags_str) {
return calculate_access_value (access_flags_str, METHOD_ACCESS_FLAGS);
}
R_API RList *retrieve_all_method_access_string_and_value() {
return retrieve_all_access_string_and_value (METHOD_ACCESS_FLAGS);
}
R_API RList *retrieve_all_field_access_string_and_value() {
return retrieve_all_access_string_and_value (FIELD_ACCESS_FLAGS);
}
R_API RList *retrieve_all_class_access_string_and_value() {
return retrieve_all_access_string_and_value (CLASS_ACCESS_FLAGS);
}
R_API char *r_bin_java_resolve_with_space(RBinJavaObj *obj, int idx) {
return r_bin_java_resolve (obj, idx, 1);
}
R_API char *r_bin_java_resolve_without_space(RBinJavaObj *obj, int idx) {
return r_bin_java_resolve (obj, idx, 0);
}
R_API char *r_bin_java_resolve_b64_encode(RBinJavaObj *BIN_OBJ, ut16 idx) {
RBinJavaCPTypeObj *item = NULL, *item2 = NULL;
char *class_str = NULL,
*name_str = NULL,
*desc_str = NULL,
*string_str = NULL,
*empty = "",
*cp_name = NULL,
*str = NULL, *out = NULL;
int memory_alloc = 0;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
// r_bin_java_new_bin(BIN_OBJ);
return NULL;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
IFDBG eprintf("java_resolve Resolved: (%d) %s\n", idx, cp_name);
} else {
return NULL;
}
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
if (!strcmp (cp_name, "Class")) {
item2 = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
// str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, idx-1);
class_str = empty;
class_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item2);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item2);
if (!desc_str) {
desc_str = empty;
}
memory_alloc = strlen (class_str) + strlen (name_str) + strlen (desc_str) + 3;
if (memory_alloc) {
str = malloc (memory_alloc);
snprintf (str, memory_alloc, "%s%s", name_str, desc_str);
out = (char *) malloc (memory_alloc);
memset (out, 0, memory_alloc);
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (strcmp (cp_name, "MethodRef") == 0 ||
strcmp (cp_name, "FieldRef") == 0 ||
strcmp (cp_name, "InterfaceMethodRef") == 0) {
/*
* The MethodRef, FieldRef, and InterfaceMethodRef structures
*/
class_str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, item->info.cp_method.class_idx);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
memory_alloc = strlen (class_str) + strlen (name_str) + strlen (desc_str) + 3;
if (memory_alloc) {
str = malloc (memory_alloc);
snprintf (str, memory_alloc, "%s/%s%s", class_str, name_str, desc_str);
out = malloc (memory_alloc);
memset (out, 0, memory_alloc);
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (strcmp (cp_name, "String") == 0) {
ut32 length = r_bin_java_get_utf8_len_from_bin_cp_list (BIN_OBJ, item->info.cp_string.string_idx);
string_str = r_bin_java_get_utf8_from_bin_cp_list (BIN_OBJ, item->info.cp_string.string_idx);
str = NULL;
IFDBG eprintf("java_resolve String got: (%d) %s\n", item->info.cp_string.string_idx, string_str);
if (!string_str) {
string_str = empty;
length = strlen (empty);
}
memory_alloc = length + 3;
if (memory_alloc) {
str = malloc (memory_alloc);
snprintf (str, memory_alloc, "\"%s\"", string_str);
out = malloc (memory_alloc);
memset (out, 0, memory_alloc);
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
IFDBG eprintf("java_resolve String return: %s\n", str);
if (string_str != empty) {
free (string_str);
}
} else if (strcmp (cp_name, "Utf8") == 0) {
ut64 sz = item->info.cp_utf8.length ? item->info.cp_utf8.length + 10 : 10;
str = malloc (sz);
memset (str, 0, sz);
if (sz > 10) {
r_base64_encode (str, item->info.cp_utf8.bytes, item->info.cp_utf8.length);
}
} else if (strcmp (cp_name, "Long") == 0) {
str = malloc (34);
out = malloc (34);
memset (out, 0, 34);
if (str) {
snprintf (str, 34, "0x%"PFMT64x, r_bin_java_raw_to_long (item->info.cp_long.bytes.raw, 0));
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
} else if (strcmp (cp_name, "Double") == 0) {
str = malloc (1000);
out = malloc (1000);
memset (out, 0, 1000);
if (str) {
snprintf (str, 1000, "%f", r_bin_java_raw_to_double (item->info.cp_double.bytes.raw, 0));
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
} else if (strcmp (cp_name, "Integer") == 0) {
str = calloc (34, 1);
out = calloc (34, 1);
if (str) {
snprintf (str, 34, "0x%08x", R_BIN_JAVA_UINT (item->info.cp_integer.bytes.raw, 0));
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
} else if (strcmp (cp_name, "Float") == 0) {
str = malloc (34);
out = malloc (34);
memset (out, 0, 34);
if (str) {
snprintf (str, 34, "%f", R_BIN_JAVA_FLOAT (item->info.cp_float.bytes.raw, 0));
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
} else if (!strcmp (cp_name, "NameAndType")) {
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
memory_alloc = strlen (name_str) + strlen (desc_str) + 3;
if (memory_alloc) {
str = malloc (memory_alloc);
snprintf (str, memory_alloc, "%s %s", name_str, desc_str);
out = malloc (memory_alloc);
memset (out, 0, memory_alloc);
r_base64_encode (out, (const ut8 *) str, strlen (str));
free (str);
str = out;
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else {
str = malloc (16);
memset (str, 0, 16);
if (str) {
r_base64_encode (str, (const ut8 *) "(null)", 6);
}
}
return str;
}
R_API ut64 r_bin_java_resolve_cp_idx_address(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaCPTypeObj *item = NULL;
ut64 addr = -1;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
return -1;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
addr = item->file_offset + item->loadaddr;
}
return addr;
}
R_API char *r_bin_java_resolve_cp_idx_to_string(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaCPTypeObj *item = NULL;
char *value = NULL;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
return NULL;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
value = ((RBinJavaCPTypeMetas *)
item->metas->type_info)->
allocs->stringify_obj (item);
}
return value;
}
R_API int r_bin_java_resolve_cp_idx_print_summary(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaCPTypeObj *item = NULL;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
return false;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
((RBinJavaCPTypeMetas *)
item->metas->type_info)->
allocs->print_summary (item);
} else {
eprintf ("Error: Invalid CP Object.\n");
}
return item ? true : false;
}
R_API ConstJavaValue *U(r_bin_java_resolve_to_const_value)(RBinJavaObj * BIN_OBJ, int idx) {
// TODO XXX FIXME add a size parameter to the str when it is passed in
RBinJavaCPTypeObj *item = NULL, *item2 = NULL;
ConstJavaValue *result = R_NEW0 (ConstJavaValue);
if (!result) {
return NULL;
}
char *class_str = NULL,
*name_str = NULL,
*desc_str = NULL,
*string_str = NULL,
*empty = "",
*cp_name = NULL;
result->type = "unknown";
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
// r_bin_java_new_bin(BIN_OBJ);
return result;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
IFDBG eprintf("java_resolve Resolved: (%d) %s\n", idx, cp_name);
} else {
return result;
}
cp_name = ((RBinJavaCPTypeMetas *) item->metas->type_info)->name;
if (strcmp (cp_name, "Class") == 0) {
item2 = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
// str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, idx-1);
class_str = empty;
class_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item2);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item2);
if (!desc_str) {
desc_str = empty;
}
result->value._ref = R_NEW0 (_JavaRef);
result->type = "ref";
result->value._ref->class_name = strdup (class_str);
result->value._ref->name = strdup (name_str);
result->value._ref->desc = strdup (desc_str);
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (strcmp (cp_name, "MethodRef") == 0 ||
strcmp (cp_name, "FieldRef") == 0 ||
strcmp (cp_name, "InterfaceMethodRef") == 0) {
/*
* The MethodRef, FieldRef, and InterfaceMethodRef structures
*/
class_str = r_bin_java_get_name_from_bin_cp_list (BIN_OBJ, item->info.cp_method.class_idx);
if (!class_str) {
class_str = empty;
}
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
result->value._ref = R_NEW0 (_JavaRef);
result->type = "ref";
result->value._ref->class_name = strdup (class_str);
result->value._ref->name = strdup (name_str);
result->value._ref->desc = strdup (desc_str);
if (class_str != empty) {
free (class_str);
}
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
} else if (strcmp (cp_name, "String") == 0) {
ut32 length = r_bin_java_get_utf8_len_from_bin_cp_list (BIN_OBJ, item->info.cp_string.string_idx);
string_str = r_bin_java_get_utf8_from_bin_cp_list (BIN_OBJ, item->info.cp_string.string_idx);
IFDBG eprintf("java_resolve String got: (%d) %s\n", item->info.cp_string.string_idx, string_str);
if (!string_str) {
string_str = empty;
length = strlen (empty);
}
result->type = "str";
result->value._str = R_NEW0 (struct java_const_value_str_t);
result->value._str->len = length;
if (length > 0) {
result->value._str->str = malloc (length);
memcpy (result->value._str->str, string_str, length);
} else {
result->value._str->str = strdup ("");
}
if (string_str != empty) {
free (string_str);
}
} else if (strcmp (cp_name, "Utf8") == 0) {
result->type = "str";
result->value._str = R_NEW0 (struct java_const_value_str_t);
result->value._str->str = malloc (item->info.cp_utf8.length);
result->value._str->len = item->info.cp_utf8.length;
memcpy (result->value._str->str, item->info.cp_utf8.bytes, item->info.cp_utf8.length);
} else if (strcmp (cp_name, "Long") == 0) {
result->type = "long";
result->value._long = r_bin_java_raw_to_long (item->info.cp_long.bytes.raw, 0);
} else if (strcmp (cp_name, "Double") == 0) {
result->type = "double";
result->value._double = r_bin_java_raw_to_double (item->info.cp_double.bytes.raw, 0);
} else if (strcmp (cp_name, "Integer") == 0) {
result->type = "int";
result->value._int = R_BIN_JAVA_UINT (item->info.cp_integer.bytes.raw, 0);
} else if (strcmp (cp_name, "Float") == 0) {
result->type = "float";
result->value._float = R_BIN_JAVA_FLOAT (item->info.cp_float.bytes.raw, 0);
} else if (strcmp (cp_name, "NameAndType") == 0) {
result->value._ref = R_NEW0 (struct java_const_value_ref_t);
result->type = "ref";
name_str = r_bin_java_get_item_name_from_bin_cp_list (BIN_OBJ, item);
if (!name_str) {
name_str = empty;
}
desc_str = r_bin_java_get_item_desc_from_bin_cp_list (BIN_OBJ, item);
if (!desc_str) {
desc_str = empty;
}
result->value._ref->class_name = strdup (empty);
result->value._ref->name = strdup (name_str);
result->value._ref->desc = strdup (desc_str);
if (name_str != empty) {
free (name_str);
}
if (desc_str != empty) {
free (desc_str);
}
result->value._ref->is_method = r_bin_java_does_cp_idx_ref_method (BIN_OBJ, idx);
result->value._ref->is_field = r_bin_java_does_cp_idx_ref_field (BIN_OBJ, idx);
}
return result;
}
R_API void U(r_bin_java_free_const_value)(ConstJavaValue * cp_value) {
char first_char = cp_value && cp_value->type ? *cp_value->type : 0,
second_char = cp_value && cp_value->type ? *(cp_value->type + 1) : 0;
switch (first_char) {
case 'r':
if (cp_value && cp_value->value._ref) {
free (cp_value->value._ref->class_name);
free (cp_value->value._ref->name);
free (cp_value->value._ref->desc);
}
break;
case 's':
if (second_char == 't' && cp_value->value._str) {
free (cp_value->value._str->str);
}
break;
}
free (cp_value);
}
R_API char *r_bin_java_get_field_name(RBinJavaObj *bin_obj, ut32 idx) {
char *name = NULL;
if (idx < r_list_length (bin_obj->fields_list)) {
RBinJavaField *fm_type = r_list_get_n (bin_obj->fields_list, idx);
name = strdup (fm_type->name);
}
return name;
}
R_API int r_bin_java_print_field_idx_summary(RBinJavaObj *bin_obj, ut32 idx) {
int res = false;
if (idx < r_list_length (bin_obj->fields_list)) {
RBinJavaField *fm_type = r_list_get_n (bin_obj->fields_list, idx);
r_bin_java_print_field_summary (fm_type);
res = true;
}
return res;
}
R_API ut32 r_bin_java_get_field_count(RBinJavaObj *bin_obj) {
return r_list_length (bin_obj->fields_list);
}
R_API RList *r_bin_java_get_field_num_name(RBinJavaObj *bin_obj) {
ut32 i = 0;
RBinJavaField *fm_type;
RListIter *iter = NULL;
RList *res = r_list_newf (free);
r_list_foreach (bin_obj->fields_list, iter, fm_type) {
ut32 len = strlen (fm_type->name) + 30;
char *str = malloc (len);
if (!str) {
r_list_free (res);
return NULL;
}
snprintf (str, len, "%d %s", i, fm_type->name);
++i;
r_list_append (res, str);
}
return res;
}
R_API RList *r_bin_java_find_cp_const_by_val_utf8(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
RList *res = r_list_newf (free);
ut32 *v = NULL;
RListIter *iter;
RBinJavaCPTypeObj *cp_obj;
IFDBG eprintf("In UTF-8 Looking for %s\n", bytes);
r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
if (cp_obj->tag == R_BIN_JAVA_CP_UTF8) {
IFDBG eprintf("In UTF-8 Looking @ %s\n", cp_obj->info.cp_utf8.bytes);
IFDBG eprintf("UTF-8 len = %d and memcmp = %d\n", cp_obj->info.cp_utf8.length, memcmp (bytes, cp_obj->info.cp_utf8.bytes, len));
if (len == cp_obj->info.cp_utf8.length && !memcmp (bytes, cp_obj->info.cp_utf8.bytes, len)) {
v = malloc (sizeof (ut32));
if (!v) {
r_list_free (res);
return NULL;
}
*v = cp_obj->metas->ord;
IFDBG eprintf("Found a match adding idx: %d\n", *v);
r_list_append (res, v);
}
}
}
return res;
}
R_API RList *r_bin_java_find_cp_const_by_val_int(RBinJavaObj *bin_obj, const ut8 *bytes, ut32 len) {
RList *res = r_list_newf (free);
ut32 *v = NULL;
RListIter *iter;
RBinJavaCPTypeObj *cp_obj;
eprintf ("Looking for 0x%08x\n", (ut32) R_BIN_JAVA_UINT (bytes, 0));
r_list_foreach (bin_obj->cp_list, iter, cp_obj) {
if (cp_obj->tag == R_BIN_JAVA_CP_INTEGER) {
if (len == 4 && R_BIN_JAVA_UINT (bytes, 0) == R_BIN_JAVA_UINT (cp_obj->info.cp_integer.bytes.raw, 0)) {
v = malloc (sizeof (ut32));
if (!v) {
r_list_free (res);
return NULL;
}
*v = cp_obj->idx;
r_list_append (res, v);
}
}
}
return res;
}
R_API char r_bin_java_resolve_cp_idx_tag(RBinJavaObj *BIN_OBJ, int idx) {
RBinJavaCPTypeObj *item = NULL;
if (BIN_OBJ && BIN_OBJ->cp_count < 1) {
// r_bin_java_new_bin(BIN_OBJ);
return R_BIN_JAVA_CP_UNKNOWN;
}
item = (RBinJavaCPTypeObj *) r_bin_java_get_item_from_bin_cp_list (BIN_OBJ, idx);
if (item) {
return item->tag;
}
return R_BIN_JAVA_CP_UNKNOWN;
}
R_API int U(r_bin_java_integer_cp_set)(RBinJavaObj * bin, ut16 idx, ut32 val) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj) {
return false;
}
ut8 bytes[4] = {
0
};
if (cp_obj->tag != R_BIN_JAVA_CP_INTEGER && cp_obj->tag != R_BIN_JAVA_CP_FLOAT) {
eprintf ("Not supporting the overwrite of CP Objects with one of a different size.\n");
return false;
}
r_bin_java_check_reset_cp_obj (cp_obj, R_BIN_JAVA_CP_INTEGER);
cp_obj->tag = R_BIN_JAVA_CP_INTEGER;
memcpy (bytes, (const char *) &val, 4);
val = R_BIN_JAVA_UINT (bytes, 0);
memcpy (&cp_obj->info.cp_integer.bytes.raw, (const char *) &val, 4);
return true;
}
R_API int U(r_bin_java_float_cp_set)(RBinJavaObj * bin, ut16 idx, float val) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj) {
return false;
}
ut8 bytes[4] = {
0
};
if (cp_obj->tag != R_BIN_JAVA_CP_INTEGER && cp_obj->tag != R_BIN_JAVA_CP_FLOAT) {
eprintf ("Not supporting the overwrite of CP Objects with one of a different size.\n");
return false;
}
r_bin_java_check_reset_cp_obj (cp_obj, R_BIN_JAVA_CP_FLOAT);
cp_obj->tag = R_BIN_JAVA_CP_FLOAT;
memcpy (bytes, (const char *) &val, 4);
float *foo = (float*) bytes;
val = *foo; //(float)R_BIN_JAVA_UINT (bytes, 0);
memcpy (&cp_obj->info.cp_float.bytes.raw, (const char *) &val, 4);
return true;
}
R_API int U(r_bin_java_long_cp_set)(RBinJavaObj * bin, ut16 idx, ut64 val) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj) {
return false;
}
ut8 bytes[8] = {
0
};
if (cp_obj->tag != R_BIN_JAVA_CP_LONG && cp_obj->tag != R_BIN_JAVA_CP_DOUBLE) {
eprintf ("Not supporting the overwrite of CP Objects with one of a different size.\n");
return false;
}
r_bin_java_check_reset_cp_obj (cp_obj, R_BIN_JAVA_CP_LONG);
cp_obj->tag = R_BIN_JAVA_CP_LONG;
memcpy (bytes, (const char *) &val, 8);
val = r_bin_java_raw_to_long (bytes, 0);
memcpy (&cp_obj->info.cp_long.bytes.raw, (const char *) &val, 8);
return true;
}
R_API int U(r_bin_java_double_cp_set)(RBinJavaObj * bin, ut16 idx, ut32 val) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj) {
return false;
}
ut8 bytes[8] = {
0
};
if (cp_obj->tag != R_BIN_JAVA_CP_LONG && cp_obj->tag != R_BIN_JAVA_CP_DOUBLE) {
eprintf ("Not supporting the overwrite of CP Objects with one of a different size.\n");
return false;
}
r_bin_java_check_reset_cp_obj (cp_obj, R_BIN_JAVA_CP_DOUBLE);
cp_obj->tag = R_BIN_JAVA_CP_DOUBLE;
ut64 val64 = val;
memcpy (bytes, (const char *) &val64, 8);
val64 = r_bin_java_raw_to_long (bytes, 0);
memcpy (&cp_obj->info.cp_double.bytes.raw, (const char *) &val64, 8);
return true;
}
R_API int U(r_bin_java_utf8_cp_set)(RBinJavaObj * bin, ut16 idx, const ut8 * buffer, ut32 len) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj) {
return false;
}
eprintf ("Writing %d byte(s) (%s)\n", len, buffer);
// r_bin_java_check_reset_cp_obj(cp_obj, R_BIN_JAVA_CP_INTEGER);
if (cp_obj->tag != R_BIN_JAVA_CP_UTF8) {
eprintf ("Not supporting the overwrite of CP Objects with one of a different size.\n");
return false;
}
if (cp_obj->info.cp_utf8.length != len) {
eprintf ("Not supporting the resize, rewriting utf8 string up to %d byte(s).\n", cp_obj->info.cp_utf8.length);
if (cp_obj->info.cp_utf8.length > len) {
eprintf ("Remaining %d byte(s) will be filled with \\x00.\n", cp_obj->info.cp_utf8.length - len);
}
}
memcpy (cp_obj->info.cp_utf8.bytes, buffer, cp_obj->info.cp_utf8.length);
if (cp_obj->info.cp_utf8.length > len) {
memset (cp_obj->info.cp_utf8.bytes + len, 0, cp_obj->info.cp_utf8.length - len);
}
return true;
}
R_API ut8 *r_bin_java_cp_get_bytes(ut8 tag, ut32 *out_sz, const ut8 *buf, const ut64 len) {
if (!out_sz) {
return NULL;
}
if (out_sz) {
*out_sz = 0;
}
switch (tag) {
case R_BIN_JAVA_CP_INTEGER:
case R_BIN_JAVA_CP_FLOAT:
return r_bin_java_cp_get_4bytes (tag, out_sz, buf, len);
case R_BIN_JAVA_CP_LONG:
case R_BIN_JAVA_CP_DOUBLE:
return r_bin_java_cp_get_8bytes (tag, out_sz, buf, len);
case R_BIN_JAVA_CP_UTF8:
return r_bin_java_cp_get_utf8 (tag, out_sz, buf, len);
}
return NULL;
}
R_API ut32 r_bin_java_cp_get_size(RBinJavaObj *bin, ut16 idx) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
switch (cp_obj->tag) {
case R_BIN_JAVA_CP_INTEGER:
case R_BIN_JAVA_CP_FLOAT:
return 1 + 4;
case R_BIN_JAVA_CP_LONG:
case R_BIN_JAVA_CP_DOUBLE:
return 1 + 8;
case R_BIN_JAVA_CP_UTF8:
return 1 + 2 + cp_obj->info.cp_utf8.length;
}
return 0;
}
R_API ut64 r_bin_java_get_method_start(RBinJavaObj *bin, RBinJavaField *fm_type) {
return r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr;
}
R_API ut64 r_bin_java_get_method_end(RBinJavaObj *bin, RBinJavaField *fm_type) {
return r_bin_java_get_method_code_offset (fm_type) + bin->loadaddr +
+r_bin_java_get_method_code_size (fm_type);
}
R_API ut8 *U(r_bin_java_cp_append_method_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 cn_idx, ut16 fn_idx, ut16 ft_idx) {
return r_bin_java_cp_get_fref_bytes (bin, out_sz, R_BIN_JAVA_CP_METHODREF, cn_idx, fn_idx, ft_idx);
}
R_API ut8 *U(r_bin_java_cp_append_field_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 cn_idx, ut16 fn_idx, ut16 ft_idx) {
return r_bin_java_cp_get_fref_bytes (bin, out_sz, R_BIN_JAVA_CP_FIELDREF, cn_idx, fn_idx, ft_idx);
}
R_API char *r_bin_java_unmangle_without_flags(const char *name, const char *descriptor) {
return r_bin_java_unmangle (NULL, name, descriptor);
}
R_API void U(r_bin_java_print_stack_map_append_frame_summary)(RBinJavaStackMapFrame * obj) {
RListIter *iter, *iter_tmp;
RList *ptrList;
RBinJavaVerificationObj *ver_obj;
Eprintf ("Stack Map Frame Information\n");
Eprintf (" Tag Value = 0x%02x Name: %s\n", obj->tag, ((RBinJavaStackMapFrameMetas *) obj->metas->type_info)->name);
Eprintf (" Offset: 0x%08"PFMT64x "\n", obj->file_offset);
Eprintf (" Local Variable Count = 0x%04x\n", obj->number_of_locals);
Eprintf (" Local Variables:\n");
ptrList = obj->local_items;
r_list_foreach_safe (ptrList, iter, iter_tmp, ver_obj) {
r_bin_java_print_verification_info_summary (ver_obj);
}
Eprintf (" Stack Items Count = 0x%04x\n", obj->number_of_stack_items);
Eprintf (" Stack Items:\n");
ptrList = obj->stack_items;
r_list_foreach_safe (ptrList, iter, iter_tmp, ver_obj) {
r_bin_java_print_verification_info_summary (ver_obj);
}
}
R_API void U(r_bin_java_stack_frame_default_free)(void *s) {
RBinJavaStackMapFrame *stack_frame = s;
if (stack_frame) {
free (stack_frame->metas);
free (stack_frame);
}
}
R_API void U(r_bin_java_stack_frame_do_nothing_free)(void /*RBinJavaStackMapFrame*/ *stack_frame) {}
R_API void U(r_bin_java_stack_frame_do_nothing_new)(RBinJavaObj * bin, RBinJavaStackMapFrame * stack_frame, ut64 offset) {}
R_API RBinJavaCPTypeMetas *U(r_bin_java_get_cp_meta_from_tag)(ut8 tag) {
ut16 i = 0;
// set default to unknown.
RBinJavaCPTypeMetas *res = &R_BIN_JAVA_CP_METAS[2];
for (i = 0; i < R_BIN_JAVA_CP_METAS_SZ; i++) {
if (tag == R_BIN_JAVA_CP_METAS[i].tag) {
res = &R_BIN_JAVA_CP_METAS[i];
break;
}
}
return res;
}
R_API ut8 *U(r_bin_java_cp_append_ref_cname_fname_ftype)(RBinJavaObj * bin, ut32 * out_sz, ut8 tag, const char *cname, const ut32 c_len, const char *fname, const ut32 f_len, const char *tname, const ut32 t_len) {
ut32 cn_len = 0, fn_len = 0, ft_len = 0, total_len;
ut16 cn_idx = 0, fn_idx = 0, ft_idx = 0;
ut8 *bytes = NULL, *cn_bytes = NULL, *fn_bytes = NULL, *ft_bytes = NULL, *cref_bytes = NULL, *fref_bytes = NULL, *fnt_bytes = NULL;
*out_sz = 0;
cn_bytes = r_bin_java_cp_get_utf8 (R_BIN_JAVA_CP_UTF8, &cn_len, (const ut8 *) cname, c_len);
cn_idx = bin->cp_idx + 1;
if (cn_bytes) {
fn_bytes = r_bin_java_cp_get_utf8 (R_BIN_JAVA_CP_UTF8, &fn_len, (const ut8 *) fname, f_len);
fn_idx = bin->cp_idx + 2;
}
if (fn_bytes) {
ft_bytes = r_bin_java_cp_get_utf8 (R_BIN_JAVA_CP_UTF8, &ft_len, (const ut8 *) tname, t_len);
ft_idx = bin->cp_idx + 3;
}
if (cn_bytes && fn_bytes && ft_bytes) {
ut32 cref_len = 0, fnt_len = 0, fref_len = 0;
ut32 cref_idx = 0, fnt_idx = 0;
cref_bytes = r_bin_java_cp_get_classref (bin, &cref_len, NULL, 0, cn_idx);
cref_idx = bin->cp_idx + 3;
fnt_bytes = r_bin_java_cp_get_name_type (bin, &fnt_len, fn_idx, ft_idx);
fnt_idx = bin->cp_idx + 4;
fref_bytes = r_bin_java_cp_get_2_ut16 (bin, &fref_len, tag, cref_idx, fnt_idx);
if (cref_bytes && fref_bytes && fnt_bytes) {
total_len = cn_len + fn_len + ft_len + cref_len + fnt_len + fref_len + 2;
if (total_len < cn_len) {
goto beach;
}
bytes = calloc (1, total_len);
// class name bytes
if (*out_sz + cn_len >= total_len) {
goto beach;
}
memcpy (bytes, cn_bytes + *out_sz, cn_len);
*out_sz += cn_len;
// field name bytes
if (*out_sz + fn_len >= total_len) {
goto beach;
}
memcpy (bytes, fn_bytes + *out_sz, fn_len);
*out_sz += fn_len;
// field type bytes
if (*out_sz + ft_len >= total_len) {
goto beach;
}
memcpy (bytes, ft_bytes + *out_sz, ft_len);
*out_sz += ft_len;
// class ref bytes
if (*out_sz + cref_len >= total_len) {
goto beach;
}
memcpy (bytes, cref_bytes + *out_sz, cref_len);
*out_sz += fn_len;
// field name and type bytes
if (*out_sz + fnt_len >= total_len) {
goto beach;
}
memcpy (bytes, fnt_bytes + *out_sz, fnt_len);
*out_sz += fnt_len;
// field ref bytes
if (*out_sz + fref_len >= total_len) {
goto beach;
}
memcpy (bytes, fref_bytes + *out_sz, fref_len);
*out_sz += fref_len;
}
}
beach:
free (cn_bytes);
free (ft_bytes);
free (fn_bytes);
free (fnt_bytes);
free (fref_bytes);
free (cref_bytes);
return bytes;
}
R_API ut8 *U(r_bin_java_cp_get_method_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 class_idx, ut16 name_and_type_idx) {
return r_bin_java_cp_get_fm_ref (bin, out_sz, R_BIN_JAVA_CP_METHODREF, class_idx, name_and_type_idx);
}
R_API ut8 *U(r_bin_java_cp_get_field_ref)(RBinJavaObj * bin, ut32 * out_sz, ut16 class_idx, ut16 name_and_type_idx) {
return r_bin_java_cp_get_fm_ref (bin, out_sz, R_BIN_JAVA_CP_FIELDREF, class_idx, name_and_type_idx);
}
R_API void U(deinit_java_type_null)() {
free (R_BIN_JAVA_NULL_TYPE.metas);
}
R_API RBinJavaCPTypeObj *r_bin_java_get_item_from_cp(RBinJavaObj *bin, int i) {
if (i < 1 || i > bin->cf.cp_count) {
return &R_BIN_JAVA_NULL_TYPE;
}
RBinJavaCPTypeObj *obj = (RBinJavaCPTypeObj *) r_list_get_n (bin->cp_list, i);
return obj ? obj : &R_BIN_JAVA_NULL_TYPE;
}
R_API void U(copy_type_info_to_stack_frame_list)(RList * type_list, RList * sf_list) {
RListIter *iter, *iter_tmp;
RBinJavaVerificationObj *ver_obj, *new_ver_obj;
if (type_list == NULL) {
return;
}
if (sf_list == NULL) {
return;
}
r_list_foreach_safe (type_list, iter, iter_tmp, ver_obj) {
new_ver_obj = (RBinJavaVerificationObj *) malloc (sizeof (RBinJavaVerificationObj));
// FIXME: how to handle failed memory allocation?
if (new_ver_obj && ver_obj) {
memcpy (new_ver_obj, ver_obj, sizeof (RBinJavaVerificationObj));
if (!r_list_append (sf_list, (void *) new_ver_obj)) {
R_FREE (new_ver_obj);
}
} else {
R_FREE (new_ver_obj);
}
}
}
R_API void U(copy_type_info_to_stack_frame_list_up_to_idx)(RList * type_list, RList * sf_list, ut64 idx) {
RListIter *iter, *iter_tmp;
RBinJavaVerificationObj *ver_obj, *new_ver_obj;
ut32 pos = 0;
if (type_list == NULL) {
return;
}
if (sf_list == NULL) {
return;
}
r_list_foreach_safe (type_list, iter, iter_tmp, ver_obj) {
new_ver_obj = (RBinJavaVerificationObj *) malloc (sizeof (RBinJavaVerificationObj));
// FIXME: how to handle failed memory allocation?
if (new_ver_obj && ver_obj) {
memcpy (new_ver_obj, ver_obj, sizeof (RBinJavaVerificationObj));
if (!r_list_append (sf_list, (void *) new_ver_obj)) {
R_FREE (new_ver_obj);
}
} else {
R_FREE (new_ver_obj);
}
pos++;
if (pos == idx) {
break;
}
}
}
R_API ut8 *r_bin_java_cp_get_idx_bytes(RBinJavaObj *bin, ut16 idx, ut32 *out_sz) {
RBinJavaCPTypeObj *cp_obj = r_bin_java_get_item_from_bin_cp_list (bin, idx);
if (!cp_obj || !out_sz) {
return NULL;
}
if (out_sz) {
*out_sz = 0;
}
switch (cp_obj->tag) {
case R_BIN_JAVA_CP_INTEGER:
case R_BIN_JAVA_CP_FLOAT:
return r_bin_java_cp_get_4bytes (cp_obj->tag, out_sz, cp_obj->info.cp_integer.bytes.raw, 5);
case R_BIN_JAVA_CP_LONG:
case R_BIN_JAVA_CP_DOUBLE:
return r_bin_java_cp_get_4bytes (cp_obj->tag, out_sz, cp_obj->info.cp_long.bytes.raw, 9);
case R_BIN_JAVA_CP_UTF8:
// eprintf ("Getting idx: %d = %p (3+0x%"PFMT64x")\n", idx, cp_obj, cp_obj->info.cp_utf8.length);
if (cp_obj->info.cp_utf8.length > 0) {
return r_bin_java_cp_get_utf8 (cp_obj->tag, out_sz,
cp_obj->info.cp_utf8.bytes, cp_obj->info.cp_utf8.length);
}
}
return NULL;
}
R_API int r_bin_java_valid_class(const ut8 *buf, ut64 buf_sz) {
RBinJavaObj *bin = R_NEW0 (RBinJavaObj), *cur_bin = R_BIN_JAVA_GLOBAL_BIN;
if (!bin) {
return false;
}
int res = r_bin_java_load_bin (bin, buf, buf_sz);
if (bin->calc_size == buf_sz) {
res = true;
}
r_bin_java_free (bin);
R_BIN_JAVA_GLOBAL_BIN = cur_bin;
return res;
}
R_API ut64 r_bin_java_calc_class_size(ut8 *bytes, ut64 size) {
RBinJavaObj *bin = R_NEW0 (RBinJavaObj);
if (!bin) {
return false;
}
RBinJavaObj *cur_bin = R_BIN_JAVA_GLOBAL_BIN;
ut64 bin_size = UT64_MAX;
if (bin) {
if (r_bin_java_load_bin (bin, bytes, size)) {
bin_size = bin->calc_size;
}
r_bin_java_free (bin);
R_BIN_JAVA_GLOBAL_BIN = cur_bin;
}
return bin_size;
}
R_API int U(r_bin_java_get_cp_idx_with_name)(RBinJavaObj * bin_obj, const char *name, ut32 len) {
RListIter *iter;
RBinJavaCPTypeObj *obj;
r_list_foreach (bin_obj->cp_list, iter, obj) {
if (obj->tag == R_BIN_JAVA_CP_UTF8) {
if (!strncmp (name, (const char *) obj->info.cp_utf8.bytes, len)) {
return obj->metas->ord;
}
}
}
return 0;
}
R_API void r_bin_java_external_printf(PrintfCallback cb) {
Eprintf = cb ? cb : (PrintfCallback) printf;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_236_0 |
crossvul-cpp_data_bad_3946_1 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Print Virtual Channel
*
* Copyright 2010-2011 Vic Lee
* Copyright 2015 Thincast Technologies GmbH
* Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
* Copyright 2016 Armin Novak <armin.novak@gmail.com>
* Copyright 2016 David PHAM-VAN <d.phamvan@inuvika.com>
*
* 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 <winpr/string.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/stream.h>
#include <winpr/interlocked.h>
#include <winpr/path.h>
#include <freerdp/channels/rdpdr.h>
#include <freerdp/crypto/crypto.h>
#include "../printer.h"
#include <freerdp/client/printer.h>
#include <freerdp/channels/log.h>
#define TAG CHANNELS_TAG("printer.client")
typedef struct _PRINTER_DEVICE PRINTER_DEVICE;
struct _PRINTER_DEVICE
{
DEVICE device;
rdpPrinter* printer;
WINPR_PSLIST_HEADER pIrpList;
HANDLE event;
HANDLE stopEvent;
HANDLE thread;
rdpContext* rdpcontext;
char port[64];
};
typedef enum
{
PRN_CONF_PORT = 0,
PRN_CONF_PNP = 1,
PRN_CONF_DRIVER = 2,
PRN_CONF_DATA = 3
} prn_conf_t;
static const char* filemap[] = { "PortDosName", "PnPName", "DriverName",
"CachedPrinterConfigData" };
static char* get_printer_config_path(const rdpSettings* settings, const WCHAR* name, size_t length)
{
char* dir = GetCombinedPath(settings->ConfigPath, "printers");
char* bname = crypto_base64_encode((const BYTE*)name, (int)length);
char* config = GetCombinedPath(dir, bname);
if (config && !PathFileExistsA(config))
{
if (!PathMakePathA(config, NULL))
{
free(config);
config = NULL;
}
}
free(dir);
free(bname);
return config;
}
static BOOL printer_write_setting(const char* path, prn_conf_t type, const void* data,
size_t length)
{
DWORD written = 0;
BOOL rc = FALSE;
HANDLE file;
size_t b64len;
char* base64 = NULL;
const char* name = filemap[type];
char* abs = GetCombinedPath(path, name);
if (!abs)
return FALSE;
file = CreateFileA(abs, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
free(abs);
if (file == INVALID_HANDLE_VALUE)
return FALSE;
if (length > 0)
{
base64 = crypto_base64_encode(data, length);
if (!base64)
goto fail;
/* base64 char represents 6bit -> 4*(n/3) is the length which is
* always smaller than 2*n */
b64len = strnlen(base64, 2 * length);
rc = WriteFile(file, base64, b64len, &written, NULL);
if (b64len != written)
rc = FALSE;
}
else
rc = TRUE;
fail:
CloseHandle(file);
free(base64);
return rc;
}
static BOOL printer_config_valid(const char* path)
{
if (!path)
return FALSE;
if (!PathFileExistsA(path))
return FALSE;
return TRUE;
}
static BOOL printer_read_setting(const char* path, prn_conf_t type, void** data, UINT32* length)
{
DWORD lowSize, highSize;
DWORD read = 0;
BOOL rc = FALSE;
HANDLE file;
char* fdata = NULL;
const char* name = filemap[type];
char* abs = GetCombinedPath(path, name);
if (!abs)
return FALSE;
file = CreateFileA(abs, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
free(abs);
if (file == INVALID_HANDLE_VALUE)
return FALSE;
lowSize = GetFileSize(file, &highSize);
if ((lowSize == INVALID_FILE_SIZE) || (highSize != 0))
goto fail;
if (lowSize != 0)
{
fdata = malloc(lowSize);
if (!fdata)
goto fail;
rc = ReadFile(file, fdata, lowSize, &read, NULL);
if (lowSize != read)
rc = FALSE;
}
fail:
CloseHandle(file);
if (rc && (lowSize <= INT_MAX))
{
int blen = 0;
crypto_base64_decode(fdata, (int)lowSize, (BYTE**)data, &blen);
if (*data && (blen > 0))
*length = (UINT32)blen;
else
{
rc = FALSE;
*length = 0;
}
}
else
{
*length = 0;
*data = NULL;
}
free(fdata);
return rc;
}
static BOOL printer_save_to_config(const rdpSettings* settings, const char* PortDosName,
size_t PortDosNameLen, const WCHAR* PnPName, size_t PnPNameLen,
const WCHAR* DriverName, size_t DriverNameLen,
const WCHAR* PrinterName, size_t PrintNameLen,
const BYTE* CachedPrinterConfigData, size_t CacheFieldsLen)
{
BOOL rc = FALSE;
char* path = get_printer_config_path(settings, PrinterName, PrintNameLen);
if (!path)
goto fail;
if (!printer_write_setting(path, PRN_CONF_PORT, PortDosName, PortDosNameLen))
goto fail;
if (!printer_write_setting(path, PRN_CONF_PNP, PnPName, PnPNameLen))
goto fail;
if (!printer_write_setting(path, PRN_CONF_DRIVER, DriverName, DriverNameLen))
goto fail;
if (!printer_write_setting(path, PRN_CONF_DATA, CachedPrinterConfigData, CacheFieldsLen))
goto fail;
fail:
free(path);
return rc;
}
static BOOL printer_update_to_config(const rdpSettings* settings, const WCHAR* name, size_t length,
const BYTE* data, size_t datalen)
{
BOOL rc = FALSE;
char* path = get_printer_config_path(settings, name, length);
rc = printer_write_setting(path, PRN_CONF_DATA, data, datalen);
free(path);
return rc;
}
static BOOL printer_remove_config(const rdpSettings* settings, const WCHAR* name, size_t length)
{
BOOL rc = FALSE;
char* path = get_printer_config_path(settings, name, length);
if (!printer_config_valid(path))
goto fail;
rc = RemoveDirectoryA(path);
fail:
free(path);
return rc;
}
static BOOL printer_move_config(const rdpSettings* settings, const WCHAR* oldName, size_t oldLength,
const WCHAR* newName, size_t newLength)
{
BOOL rc = FALSE;
char* oldPath = get_printer_config_path(settings, oldName, oldLength);
char* newPath = get_printer_config_path(settings, newName, newLength);
if (printer_config_valid(oldPath))
rc = MoveFileA(oldPath, newPath);
free(oldPath);
free(newPath);
return rc;
}
static BOOL printer_load_from_config(const rdpSettings* settings, rdpPrinter* printer,
PRINTER_DEVICE* printer_dev)
{
BOOL res = FALSE;
WCHAR* wname = NULL;
size_t wlen;
char* path = NULL;
int rc;
UINT32 flags = 0;
void* DriverName = NULL;
UINT32 DriverNameLen = 0;
void* PnPName = NULL;
UINT32 PnPNameLen = 0;
void* CachedPrinterConfigData = NULL;
UINT32 CachedFieldsLen = 0;
UINT32 PrinterNameLen = 0;
if (!settings || !printer)
return FALSE;
rc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);
if (rc <= 0)
goto fail;
wlen = _wcslen(wname) + 1;
path = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));
PrinterNameLen = (wlen + 1) * sizeof(WCHAR);
if (!path)
goto fail;
if (printer->is_default)
flags |= RDPDR_PRINTER_ANNOUNCE_FLAG_DEFAULTPRINTER;
if (!printer_read_setting(path, PRN_CONF_PNP, &PnPName, &PnPNameLen))
{
}
if (!printer_read_setting(path, PRN_CONF_DRIVER, &DriverName, &DriverNameLen))
{
DriverNameLen =
ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, (LPWSTR*)&DriverName, 0) * 2 + 1;
}
if (!printer_read_setting(path, PRN_CONF_DATA, &CachedPrinterConfigData, &CachedFieldsLen))
{
}
Stream_SetPosition(printer_dev->device.data, 0);
if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, 24))
goto fail;
Stream_Write_UINT32(printer_dev->device.data, flags);
Stream_Write_UINT32(printer_dev->device.data, 0); /* CodePage, reserved */
Stream_Write_UINT32(printer_dev->device.data, PnPNameLen); /* PnPNameLen */
Stream_Write_UINT32(printer_dev->device.data, DriverNameLen);
Stream_Write_UINT32(printer_dev->device.data, PrinterNameLen);
Stream_Write_UINT32(printer_dev->device.data, CachedFieldsLen);
if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PnPNameLen))
goto fail;
if (PnPNameLen > 0)
Stream_Write(printer_dev->device.data, PnPName, PnPNameLen);
if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, DriverNameLen))
goto fail;
Stream_Write(printer_dev->device.data, DriverName, DriverNameLen);
if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, PrinterNameLen))
goto fail;
Stream_Write(printer_dev->device.data, wname, PrinterNameLen);
if (!Stream_EnsureRemainingCapacity(printer_dev->device.data, CachedFieldsLen))
goto fail;
Stream_Write(printer_dev->device.data, CachedPrinterConfigData, CachedFieldsLen);
res = TRUE;
fail:
free(path);
free(wname);
free(PnPName);
free(DriverName);
free(CachedPrinterConfigData);
return res;
}
static BOOL printer_save_default_config(const rdpSettings* settings, rdpPrinter* printer)
{
BOOL res = FALSE;
WCHAR* wname = NULL;
WCHAR* driver = NULL;
size_t wlen, dlen;
char* path = NULL;
int rc;
if (!settings || !printer)
return FALSE;
rc = ConvertToUnicode(CP_UTF8, 0, printer->name, -1, &wname, 0);
if (rc <= 0)
goto fail;
rc = ConvertToUnicode(CP_UTF8, 0, printer->driver, -1, &driver, 0);
if (rc <= 0)
goto fail;
wlen = _wcslen(wname) + 1;
dlen = _wcslen(driver) + 1;
path = get_printer_config_path(settings, wname, wlen * sizeof(WCHAR));
if (!path)
goto fail;
if (dlen > 1)
{
if (!printer_write_setting(path, PRN_CONF_DRIVER, driver, dlen * sizeof(WCHAR)))
goto fail;
}
res = TRUE;
fail:
free(path);
free(wname);
free(driver);
return res;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_process_irp_create(PRINTER_DEVICE* printer_dev, IRP* irp)
{
rdpPrintJob* printjob = NULL;
if (printer_dev->printer)
printjob =
printer_dev->printer->CreatePrintJob(printer_dev->printer, irp->devman->id_sequence++);
if (printjob)
{
Stream_Write_UINT32(irp->output, printjob->id); /* FileId */
}
else
{
Stream_Write_UINT32(irp->output, 0); /* FileId */
irp->IoStatus = STATUS_PRINT_QUEUE_FULL;
}
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_process_irp_close(PRINTER_DEVICE* printer_dev, IRP* irp)
{
rdpPrintJob* printjob = NULL;
if (printer_dev->printer)
printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);
if (!printjob)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
}
else
{
printjob->Close(printjob);
}
Stream_Zero(irp->output, 4); /* Padding(4) */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_process_irp_write(PRINTER_DEVICE* printer_dev, IRP* irp)
{
UINT32 Length;
UINT64 Offset;
rdpPrintJob* printjob = NULL;
UINT error = CHANNEL_RC_OK;
Stream_Read_UINT32(irp->input, Length);
Stream_Read_UINT64(irp->input, Offset);
Stream_Seek(irp->input, 20); /* Padding */
if (printer_dev->printer)
printjob = printer_dev->printer->FindPrintJob(printer_dev->printer, irp->FileId);
if (!printjob)
{
irp->IoStatus = STATUS_UNSUCCESSFUL;
Length = 0;
}
else
{
error = printjob->Write(printjob, Stream_Pointer(irp->input), Length);
}
if (error)
{
WLog_ERR(TAG, "printjob->Write failed with error %" PRIu32 "!", error);
return error;
}
Stream_Write_UINT32(irp->output, Length);
Stream_Write_UINT8(irp->output, 0); /* Padding */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_process_irp_device_control(PRINTER_DEVICE* printer_dev, IRP* irp)
{
Stream_Write_UINT32(irp->output, 0); /* OutputBufferLength */
return irp->Complete(irp);
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_process_irp(PRINTER_DEVICE* printer_dev, IRP* irp)
{
UINT error;
switch (irp->MajorFunction)
{
case IRP_MJ_CREATE:
if ((error = printer_process_irp_create(printer_dev, irp)))
{
WLog_ERR(TAG, "printer_process_irp_create failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_CLOSE:
if ((error = printer_process_irp_close(printer_dev, irp)))
{
WLog_ERR(TAG, "printer_process_irp_close failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_WRITE:
if ((error = printer_process_irp_write(printer_dev, irp)))
{
WLog_ERR(TAG, "printer_process_irp_write failed with error %" PRIu32 "!", error);
return error;
}
break;
case IRP_MJ_DEVICE_CONTROL:
if ((error = printer_process_irp_device_control(printer_dev, irp)))
{
WLog_ERR(TAG, "printer_process_irp_device_control failed with error %" PRIu32 "!",
error);
return error;
}
break;
default:
irp->IoStatus = STATUS_NOT_SUPPORTED;
return irp->Complete(irp);
break;
}
return CHANNEL_RC_OK;
}
static DWORD WINAPI printer_thread_func(LPVOID arg)
{
IRP* irp;
PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)arg;
HANDLE obj[] = { printer_dev->event, printer_dev->stopEvent };
UINT error = CHANNEL_RC_OK;
while (1)
{
DWORD rc = WaitForMultipleObjects(2, obj, FALSE, INFINITE);
if (rc == WAIT_FAILED)
{
error = GetLastError();
WLog_ERR(TAG, "WaitForMultipleObjects failed with error %" PRIu32 "!", error);
break;
}
if (rc == WAIT_OBJECT_0 + 1)
break;
else if (rc != WAIT_OBJECT_0)
continue;
ResetEvent(printer_dev->event);
irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList);
if (irp == NULL)
{
WLog_ERR(TAG, "InterlockedPopEntrySList failed!");
error = ERROR_INTERNAL_ERROR;
break;
}
if ((error = printer_process_irp(printer_dev, irp)))
{
WLog_ERR(TAG, "printer_process_irp failed with error %" PRIu32 "!", error);
break;
}
}
if (error && printer_dev->rdpcontext)
setChannelError(printer_dev->rdpcontext, error, "printer_thread_func reported an error");
ExitThread(error);
return error;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_irp_request(DEVICE* device, IRP* irp)
{
PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;
InterlockedPushEntrySList(printer_dev->pIrpList, &(irp->ItemEntry));
SetEvent(printer_dev->event);
return CHANNEL_RC_OK;
}
static UINT printer_custom_component(DEVICE* device, UINT16 component, UINT16 packetId, wStream* s)
{
UINT32 eventID;
PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;
const rdpSettings* settings = printer_dev->rdpcontext->settings;
if (component != RDPDR_CTYP_PRN)
return ERROR_INVALID_DATA;
if (Stream_GetRemainingLength(s) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(s, eventID);
switch (packetId)
{
case PAKID_PRN_CACHE_DATA:
switch (eventID)
{
case RDPDR_ADD_PRINTER_EVENT:
{
char PortDosName[8];
UINT32 PnPNameLen, DriverNameLen, PrintNameLen, CacheFieldsLen;
const WCHAR *PnPName, *DriverName, *PrinterName;
const BYTE* CachedPrinterConfigData;
if (Stream_GetRemainingLength(s) < 24)
return ERROR_INVALID_DATA;
Stream_Read(s, PortDosName, sizeof(PortDosName));
Stream_Read_UINT32(s, PnPNameLen);
Stream_Read_UINT32(s, DriverNameLen);
Stream_Read_UINT32(s, PrintNameLen);
Stream_Read_UINT32(s, CacheFieldsLen);
if (Stream_GetRemainingLength(s) < PnPNameLen)
return ERROR_INVALID_DATA;
PnPName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, PnPNameLen);
if (Stream_GetRemainingLength(s) < DriverNameLen)
return ERROR_INVALID_DATA;
DriverName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, DriverNameLen);
if (Stream_GetRemainingLength(s) < PrintNameLen)
return ERROR_INVALID_DATA;
PrinterName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, PrintNameLen);
if (Stream_GetRemainingLength(s) < CacheFieldsLen)
return ERROR_INVALID_DATA;
CachedPrinterConfigData = Stream_Pointer(s);
Stream_Seek(s, CacheFieldsLen);
if (!printer_save_to_config(settings, PortDosName, sizeof(PortDosName), PnPName,
PnPNameLen, DriverName, DriverNameLen, PrinterName,
PrintNameLen, CachedPrinterConfigData,
CacheFieldsLen))
return ERROR_INTERNAL_ERROR;
}
break;
case RDPDR_UPDATE_PRINTER_EVENT:
{
UINT32 PrinterNameLen, ConfigDataLen;
const WCHAR* PrinterName;
const BYTE* ConfigData;
if (Stream_GetRemainingLength(s) < 8)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(s, PrinterNameLen);
Stream_Read_UINT32(s, ConfigDataLen);
if (Stream_GetRemainingLength(s) < PrinterNameLen)
return ERROR_INVALID_DATA;
PrinterName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, PrinterNameLen);
if (Stream_GetRemainingLength(s) < ConfigDataLen)
return ERROR_INVALID_DATA;
ConfigData = Stream_Pointer(s);
Stream_Seek(s, ConfigDataLen);
if (!printer_update_to_config(settings, PrinterName, PrinterNameLen, ConfigData,
ConfigDataLen))
return ERROR_INTERNAL_ERROR;
}
break;
case RDPDR_DELETE_PRINTER_EVENT:
{
UINT32 PrinterNameLen;
const WCHAR* PrinterName;
if (Stream_GetRemainingLength(s) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(s, PrinterNameLen);
if (Stream_GetRemainingLength(s) < PrinterNameLen)
return ERROR_INVALID_DATA;
PrinterName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, PrinterNameLen);
printer_remove_config(settings, PrinterName, PrinterNameLen);
}
break;
case RDPDR_RENAME_PRINTER_EVENT:
{
UINT32 OldPrinterNameLen, NewPrinterNameLen;
const WCHAR* OldPrinterName;
const WCHAR* NewPrinterName;
if (Stream_GetRemainingLength(s) < 8)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(s, OldPrinterNameLen);
Stream_Read_UINT32(s, NewPrinterNameLen);
if (Stream_GetRemainingLength(s) < OldPrinterNameLen)
return ERROR_INVALID_DATA;
OldPrinterName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, OldPrinterNameLen);
if (Stream_GetRemainingLength(s) < NewPrinterNameLen)
return ERROR_INVALID_DATA;
NewPrinterName = (const WCHAR*)Stream_Pointer(s);
Stream_Seek(s, NewPrinterNameLen);
if (!printer_move_config(settings, OldPrinterName, OldPrinterNameLen,
NewPrinterName, NewPrinterNameLen))
return ERROR_INTERNAL_ERROR;
}
break;
default:
WLog_ERR(TAG, "Unknown cache data eventID: 0x%08" PRIX32 "", eventID);
return ERROR_INVALID_DATA;
}
break;
case PAKID_PRN_USING_XPS:
{
UINT32 flags;
if (Stream_GetRemainingLength(s) < 4)
return ERROR_INVALID_DATA;
Stream_Read_UINT32(s, flags);
WLog_ERR(TAG,
"Ignoring unhandled message PAKID_PRN_USING_XPS [printerID=%08" PRIx32
", flags=%08" PRIx32 "]",
eventID, flags);
}
break;
default:
WLog_ERR(TAG, "Unknown printing component packetID: 0x%04" PRIX16 "", packetId);
return ERROR_INVALID_DATA;
}
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_free(DEVICE* device)
{
IRP* irp;
PRINTER_DEVICE* printer_dev = (PRINTER_DEVICE*)device;
UINT error;
SetEvent(printer_dev->stopEvent);
if (WaitForSingleObject(printer_dev->thread, INFINITE) == WAIT_FAILED)
{
error = GetLastError();
WLog_ERR(TAG, "WaitForSingleObject failed with error %" PRIu32 "", error);
/* The analyzer is confused by this premature return value.
* Since this case can not be handled gracefully silence the
* analyzer here. */
#ifndef __clang_analyzer__
return error;
#endif
}
while ((irp = (IRP*)InterlockedPopEntrySList(printer_dev->pIrpList)) != NULL)
irp->Discard(irp);
CloseHandle(printer_dev->thread);
CloseHandle(printer_dev->stopEvent);
CloseHandle(printer_dev->event);
_aligned_free(printer_dev->pIrpList);
if (printer_dev->printer)
printer_dev->printer->ReleaseRef(printer_dev->printer);
Stream_Free(printer_dev->device.data, TRUE);
free(printer_dev);
return CHANNEL_RC_OK;
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
static UINT printer_register(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints, rdpPrinter* printer)
{
PRINTER_DEVICE* printer_dev;
UINT error = ERROR_INTERNAL_ERROR;
printer_dev = (PRINTER_DEVICE*)calloc(1, sizeof(PRINTER_DEVICE));
if (!printer_dev)
{
WLog_ERR(TAG, "calloc failed!");
return CHANNEL_RC_NO_MEMORY;
}
printer_dev->device.data = Stream_New(NULL, 1024);
if (!printer_dev->device.data)
goto error_out;
sprintf_s(printer_dev->port, sizeof(printer_dev->port), "PRN%" PRIdz, printer->id);
printer_dev->device.type = RDPDR_DTYP_PRINT;
printer_dev->device.name = printer_dev->port;
printer_dev->device.IRPRequest = printer_irp_request;
printer_dev->device.CustomComponentRequest = printer_custom_component;
printer_dev->device.Free = printer_free;
printer_dev->rdpcontext = pEntryPoints->rdpcontext;
printer_dev->printer = printer;
printer_dev->pIrpList = (WINPR_PSLIST_HEADER)_aligned_malloc(sizeof(WINPR_SLIST_HEADER),
MEMORY_ALLOCATION_ALIGNMENT);
if (!printer_dev->pIrpList)
{
WLog_ERR(TAG, "_aligned_malloc failed!");
error = CHANNEL_RC_NO_MEMORY;
goto error_out;
}
if (!printer_load_from_config(pEntryPoints->rdpcontext->settings, printer, printer_dev))
goto error_out;
InitializeSListHead(printer_dev->pIrpList);
if (!(printer_dev->event = CreateEvent(NULL, TRUE, FALSE, NULL)))
{
WLog_ERR(TAG, "CreateEvent failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
if (!(printer_dev->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
{
WLog_ERR(TAG, "CreateEvent failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
if ((error = pEntryPoints->RegisterDevice(pEntryPoints->devman, (DEVICE*)printer_dev)))
{
WLog_ERR(TAG, "RegisterDevice failed with error %" PRIu32 "!", error);
goto error_out;
}
if (!(printer_dev->thread =
CreateThread(NULL, 0, printer_thread_func, (void*)printer_dev, 0, NULL)))
{
WLog_ERR(TAG, "CreateThread failed!");
error = ERROR_INTERNAL_ERROR;
goto error_out;
}
printer->AddRef(printer);
return CHANNEL_RC_OK;
error_out:
printer_free(&printer_dev->device);
return error;
}
static rdpPrinterDriver* printer_load_backend(const char* backend)
{
typedef rdpPrinterDriver* (*backend_load_t)(void);
union {
PVIRTUALCHANNELENTRY entry;
backend_load_t backend;
} fktconv;
fktconv.entry = freerdp_load_channel_addin_entry("printer", backend, NULL, 0);
if (!fktconv.entry)
return NULL;
return fktconv.backend();
}
/**
* Function description
*
* @return 0 on success, otherwise a Win32 error code
*/
UINT
#ifdef BUILTIN_CHANNELS
printer_DeviceServiceEntry
#else
FREERDP_API
DeviceServiceEntry
#endif
(PDEVICE_SERVICE_ENTRY_POINTS pEntryPoints)
{
int i;
char* name;
char* driver_name;
BOOL default_backend = TRUE;
RDPDR_PRINTER* device = NULL;
rdpPrinterDriver* driver = NULL;
UINT error = CHANNEL_RC_OK;
if (!pEntryPoints || !pEntryPoints->device)
return ERROR_INVALID_PARAMETER;
device = (RDPDR_PRINTER*)pEntryPoints->device;
name = device->Name;
driver_name = device->DriverName;
/* Secondary argument is one of the following:
*
* <driver_name> ... name of a printer driver
* <driver_name>:<backend_name> ... name of a printer driver and local printer backend to use
*/
if (driver_name)
{
char* sep = strstr(driver_name, ":");
if (sep)
{
const char* backend = sep + 1;
*sep = '\0';
driver = printer_load_backend(backend);
default_backend = FALSE;
}
}
if (!driver && default_backend)
{
const char* backend =
#if defined(WITH_CUPS)
"cups"
#elif defined(_WIN32)
"win"
#else
""
#endif
;
driver = printer_load_backend(backend);
}
if (!driver)
{
WLog_ERR(TAG, "Could not get a printer driver!");
return CHANNEL_RC_INITIALIZATION_ERROR;
}
if (name && name[0])
{
rdpPrinter* printer = driver->GetPrinter(driver, name, driver_name);
if (!printer)
{
WLog_ERR(TAG, "Could not get printer %s!", name);
error = CHANNEL_RC_INITIALIZATION_ERROR;
goto fail;
}
if (!printer_save_default_config(pEntryPoints->rdpcontext->settings, printer))
{
error = CHANNEL_RC_INITIALIZATION_ERROR;
printer->ReleaseRef(printer);
goto fail;
}
if ((error = printer_register(pEntryPoints, printer)))
{
WLog_ERR(TAG, "printer_register failed with error %" PRIu32 "!", error);
printer->ReleaseRef(printer);
goto fail;
}
}
else
{
rdpPrinter** printers = driver->EnumPrinters(driver);
rdpPrinter** current = printers;
for (i = 0; current[i]; i++)
{
rdpPrinter* printer = current[i];
if ((error = printer_register(pEntryPoints, printer)))
{
WLog_ERR(TAG, "printer_register failed with error %" PRIu32 "!", error);
break;
}
}
driver->ReleaseEnumPrinters(printers);
}
fail:
driver->ReleaseRef(driver);
return error;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3946_1 |
crossvul-cpp_data_bad_5241_0 | /*
* io_dp.c
*
* Implements the dynamic pointer interface.
*
* Based on GD.pm code by Lincoln Stein for interfacing to libgd.
* Added support for reading as well as support for 'tell' and 'seek'.
*
* As will all I/O modules, most functions are for local use only (called
* via function pointers in the I/O context).
*
* gdDPExtractData is the exception to this: it will return the pointer to
* the internal data, and reset the internal storage.
*
* Written/Modified 1999, Philip Warner.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gd.h"
#include "gdhelpers.h"
#define TRUE 1
#define FALSE 0
/* this is used for creating images in main memory */
typedef struct dpStruct {
void *data;
int logicalSize;
int realSize;
int dataGood;
int pos;
int freeOK;
}
dynamicPtr;
typedef struct dpIOCtx {
gdIOCtx ctx;
dynamicPtr *dp;
}
dpIOCtx;
typedef struct dpIOCtx *dpIOCtxPtr;
/* these functions operate on in-memory dynamic pointers */
static int allocDynamic(dynamicPtr *dp, int initialSize, void *data);
static int appendDynamic(dynamicPtr *dp, const void *src, int size);
static int gdReallocDynamic(dynamicPtr *dp, int required);
static int trimDynamic(dynamicPtr *dp);
static void gdFreeDynamicCtx(struct gdIOCtx *ctx);
static dynamicPtr *newDynamic(int initialSize, void *data, int freeOKFlag);
static int dynamicPutbuf(struct gdIOCtx *, const void *, int);
static void dynamicPutchar(struct gdIOCtx *, int a);
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len);
static int dynamicGetchar(gdIOCtxPtr ctx);
static int dynamicSeek(struct gdIOCtx *, const int);
static long dynamicTell(struct gdIOCtx *);
/*
Function: gdNewDynamicCtx
Return data as a dynamic pointer.
*/
BGD_DECLARE(gdIOCtx *) gdNewDynamicCtx(int initialSize, void *data)
{
/* 2.0.23: Phil Moore: 'return' keyword was missing! */
return gdNewDynamicCtxEx(initialSize, data, 1);
}
/*
Function: gdNewDynamicCtxEx
*/
BGD_DECLARE(gdIOCtx *) gdNewDynamicCtxEx(int initialSize, void *data, int freeOKFlag)
{
dpIOCtx *ctx;
dynamicPtr *dp;
ctx = (dpIOCtx *)gdMalloc(sizeof (dpIOCtx));
if(ctx == NULL) {
return NULL;
}
dp = newDynamic(initialSize, data, freeOKFlag);
if(!dp) {
gdFree (ctx);
return NULL;
};
ctx->dp = dp;
ctx->ctx.getC = dynamicGetchar;
ctx->ctx.putC = dynamicPutchar;
ctx->ctx.getBuf = dynamicGetbuf;
ctx->ctx.putBuf = dynamicPutbuf;
ctx->ctx.seek = dynamicSeek;
ctx->ctx.tell = dynamicTell;
ctx->ctx.gd_free = gdFreeDynamicCtx;
return (gdIOCtx *)ctx;
}
/*
Function: gdDPExtractData
*/
BGD_DECLARE(void *) gdDPExtractData (struct gdIOCtx *ctx, int *size)
{
dynamicPtr *dp;
dpIOCtx *dctx;
void *data;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
/* clean up the data block and return it */
if(dp->dataGood) {
trimDynamic(dp);
*size = dp->logicalSize;
data = dp->data;
} else {
*size = 0;
data = NULL;
/* 2.0.21: never free memory we don't own */
if((dp->data != NULL) && (dp->freeOK)) {
gdFree(dp->data);
}
}
dp->data = NULL;
dp->realSize = 0;
dp->logicalSize = 0;
return data;
}
static void gdFreeDynamicCtx(struct gdIOCtx *ctx)
{
dynamicPtr *dp;
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
gdFree(ctx);
/* clean up the data block and return it */
/* 2.0.21: never free memory we don't own */
if((dp->data != NULL) && (dp->freeOK)) {
gdFree(dp->data);
dp->data = NULL;
}
dp->realSize = 0;
dp->logicalSize = 0;
gdFree(dp);
}
static long dynamicTell(struct gdIOCtx *ctx)
{
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
return (dctx->dp->pos);
}
static int dynamicSeek(struct gdIOCtx *ctx, const int pos)
{
int bytesNeeded;
dynamicPtr *dp;
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
dp = dctx->dp;
if(!dp->dataGood) {
return FALSE;
}
bytesNeeded = pos;
if(bytesNeeded > dp->realSize) {
/* 2.0.21 */
if(!dp->freeOK) {
return FALSE;
}
if(overflow2(dp->realSize, 2)) {
return FALSE;
}
if(!gdReallocDynamic(dp, dp->realSize * 2)) {
dp->dataGood = FALSE;
return FALSE;
}
}
/* if we get here, we can be sure that we have enough bytes
* to copy safely */
/* Extend the logical size if we seek beyond EOF. */
if(pos > dp->logicalSize) {
dp->logicalSize = pos;
};
dp->pos = pos;
return TRUE;
}
/* return data as a dynamic pointer */
static dynamicPtr *newDynamic(int initialSize, void *data, int freeOKFlag)
{
dynamicPtr *dp;
dp = (dynamicPtr *) gdMalloc(sizeof (dynamicPtr));
if(dp == NULL) {
return NULL;
}
if(!allocDynamic(dp, initialSize, data)) {
gdFree(dp);
return NULL;
}
dp->pos = 0;
dp->freeOK = freeOKFlag;
return dp;
}
static int dynamicPutbuf(struct gdIOCtx *ctx, const void *buf, int size)
{
dpIOCtx *dctx;
dctx = (dpIOCtx *)ctx;
appendDynamic(dctx->dp, buf, size);
if(dctx->dp->dataGood) {
return size;
} else {
return -1;
};
}
static void dynamicPutchar(struct gdIOCtx *ctx, int a)
{
unsigned char b;
dpIOCtxPtr dctx;
b = a;
dctx = (dpIOCtxPtr) ctx;
appendDynamic(dctx->dp, &b, 1);
}
static int dynamicGetbuf(gdIOCtxPtr ctx, void *buf, int len)
{
int rlen, remain;
dpIOCtxPtr dctx;
dynamicPtr *dp;
dctx = (dpIOCtxPtr) ctx;
dp = dctx->dp;
remain = dp->logicalSize - dp->pos;
if(remain >= len) {
rlen = len;
} else {
if(remain <= 0) {
/* 2.0.34: EOF is incorrect. We use 0 for
* errors and EOF, just like fileGetbuf,
* which is a simple fread() wrapper.
* TBB. Original bug report: Daniel Cowgill. */
return 0; /* NOT EOF */
}
rlen = remain;
}
memcpy(buf, (void *) ((char *)dp->data + dp->pos), rlen);
dp->pos += rlen;
return rlen;
}
static int dynamicGetchar(gdIOCtxPtr ctx)
{
unsigned char b;
int rv;
rv = dynamicGetbuf(ctx, &b, 1);
if(rv != 1) {
return EOF;
} else {
return b; /* (b & 0xff); */
}
}
/**********************************************************************
* InitDynamic - Return a dynamically resizable void*
**********************************************************************/
static int allocDynamic(dynamicPtr *dp, int initialSize, void *data)
{
if(data == NULL) {
dp->logicalSize = 0;
dp->dataGood = FALSE;
dp->data = gdMalloc(initialSize);
} else {
dp->logicalSize = initialSize;
dp->dataGood = TRUE;
dp->data = data;
}
if(dp->data != NULL) {
dp->realSize = initialSize;
dp->dataGood = TRUE;
dp->pos = 0;
return TRUE;
} else {
dp->realSize = 0;
return FALSE;
}
}
/* append bytes to the end of a dynamic pointer */
static int appendDynamic(dynamicPtr * dp, const void *src, int size)
{
int bytesNeeded;
char *tmp;
if(!dp->dataGood) {
return FALSE;
}
/* bytesNeeded = dp->logicalSize + size; */
bytesNeeded = dp->pos + size;
if(bytesNeeded > dp->realSize) {
/* 2.0.21 */
if(!dp->freeOK) {
return FALSE;
}
if(overflow2(dp->realSize, 2)) {
return FALSE;
}
if(!gdReallocDynamic(dp, bytesNeeded * 2)) {
dp->dataGood = FALSE;
return FALSE;
}
}
/* if we get here, we can be sure that we have enough bytes
* to copy safely */
/*printf("Mem OK Size: %d, Pos: %d\n", dp->realSize, dp->pos); */
tmp = (char *)dp->data;
memcpy ((void *)(tmp + (dp->pos)), src, size);
dp->pos += size;
if(dp->pos > dp->logicalSize) {
dp->logicalSize = dp->pos;
};
return TRUE;
}
/* grow (or shrink) dynamic pointer */
static int gdReallocDynamic(dynamicPtr *dp, int required)
{
void *newPtr;
/* First try gdRealloc(). If that doesn't work, make a new
* memory block and copy. */
if((newPtr = gdRealloc(dp->data, required))) {
dp->realSize = required;
dp->data = newPtr;
return TRUE;
}
/* create a new pointer */
newPtr = gdMalloc(required);
if(!newPtr) {
dp->dataGood = FALSE;
return FALSE;
}
/* copy the old data into it */
memcpy(newPtr, dp->data, dp->logicalSize);
gdFree(dp->data);
dp->data = newPtr;
dp->realSize = required;
return TRUE;
}
/* trim pointer so that its real and logical sizes match */
static int trimDynamic(dynamicPtr *dp)
{
/* 2.0.21: we don't reallocate memory we don't own */
if(!dp->freeOK) {
return TRUE;
}
return gdReallocDynamic(dp, dp->logicalSize);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5241_0 |
crossvul-cpp_data_bad_2720_0 | /*
* Copyright (c) 2016 Antonin Décimo, Jean-Raphaël Gaglione
*
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
/* \summary: Home Networking Control Protocol (HNCP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent);
void
hncp_print(netdissect_options *ndo,
const u_char *cp, u_int length)
{
ND_PRINT((ndo, "hncp (%d)", length));
hncp_print_rec(ndo, cp, length, 1);
}
/* RFC7787 */
#define DNCP_REQUEST_NETWORK_STATE 1
#define DNCP_REQUEST_NODE_STATE 2
#define DNCP_NODE_ENDPOINT 3
#define DNCP_NETWORK_STATE 4
#define DNCP_NODE_STATE 5
#define DNCP_PEER 8
#define DNCP_KEEP_ALIVE_INTERVAL 9
#define DNCP_TRUST_VERDICT 10
/* RFC7788 */
#define HNCP_HNCP_VERSION 32
#define HNCP_EXTERNAL_CONNECTION 33
#define HNCP_DELEGATED_PREFIX 34
#define HNCP_PREFIX_POLICY 43
#define HNCP_DHCPV4_DATA 37
#define HNCP_DHCPV6_DATA 38
#define HNCP_ASSIGNED_PREFIX 35
#define HNCP_NODE_ADDRESS 36
#define HNCP_DNS_DELEGATED_ZONE 39
#define HNCP_DOMAIN_NAME 40
#define HNCP_NODE_NAME 41
#define HNCP_MANAGED_PSK 42
/* See type_mask in hncp_print_rec below */
#define RANGE_DNCP_RESERVED 0x10000
#define RANGE_HNCP_UNASSIGNED 0x10001
#define RANGE_DNCP_PRIVATE_USE 0x10002
#define RANGE_DNCP_FUTURE_USE 0x10003
static const struct tok type_values[] = {
{ DNCP_REQUEST_NETWORK_STATE, "Request network state" },
{ DNCP_REQUEST_NODE_STATE, "Request node state" },
{ DNCP_NODE_ENDPOINT, "Node endpoint" },
{ DNCP_NETWORK_STATE, "Network state" },
{ DNCP_NODE_STATE, "Node state" },
{ DNCP_PEER, "Peer" },
{ DNCP_KEEP_ALIVE_INTERVAL, "Keep-alive interval" },
{ DNCP_TRUST_VERDICT, "Trust-Verdict" },
{ HNCP_HNCP_VERSION, "HNCP-Version" },
{ HNCP_EXTERNAL_CONNECTION, "External-Connection" },
{ HNCP_DELEGATED_PREFIX, "Delegated-Prefix" },
{ HNCP_PREFIX_POLICY, "Prefix-Policy" },
{ HNCP_DHCPV4_DATA, "DHCPv4-Data" },
{ HNCP_DHCPV6_DATA, "DHCPv6-Data" },
{ HNCP_ASSIGNED_PREFIX, "Assigned-Prefix" },
{ HNCP_NODE_ADDRESS, "Node-Address" },
{ HNCP_DNS_DELEGATED_ZONE, "DNS-Delegated-Zone" },
{ HNCP_DOMAIN_NAME, "Domain-Name" },
{ HNCP_NODE_NAME, "Node-Name" },
{ HNCP_MANAGED_PSK, "Managed-PSK" },
{ RANGE_DNCP_RESERVED, "Reserved" },
{ RANGE_HNCP_UNASSIGNED, "Unassigned" },
{ RANGE_DNCP_PRIVATE_USE, "Private use" },
{ RANGE_DNCP_FUTURE_USE, "Future use" },
{ 0, NULL}
};
#define DH4OPT_DNS_SERVERS 6 /* RFC2132 */
#define DH4OPT_NTP_SERVERS 42 /* RFC2132 */
#define DH4OPT_DOMAIN_SEARCH 119 /* RFC3397 */
static const struct tok dh4opt_str[] = {
{ DH4OPT_DNS_SERVERS, "DNS-server" },
{ DH4OPT_NTP_SERVERS, "NTP-server"},
{ DH4OPT_DOMAIN_SEARCH, "DNS-search" },
{ 0, NULL }
};
#define DH6OPT_DNS_SERVERS 23 /* RFC3646 */
#define DH6OPT_DOMAIN_LIST 24 /* RFC3646 */
#define DH6OPT_SNTP_SERVERS 31 /* RFC4075 */
static const struct tok dh6opt_str[] = {
{ DH6OPT_DNS_SERVERS, "DNS-server" },
{ DH6OPT_DOMAIN_LIST, "DNS-search-list" },
{ DH6OPT_SNTP_SERVERS, "SNTP-servers" },
{ 0, NULL }
};
/*
* For IPv4-mapped IPv6 addresses, length of the prefix that precedes
* the 4 bytes of IPv4 address at the end of the IPv6 address.
*/
#define IPV4_MAPPED_HEADING_LEN 12
/*
* Is an IPv6 address an IPv4-mapped address?
*/
static inline int
is_ipv4_mapped_address(const u_char *addr)
{
/* The value of the prefix */
static const u_char ipv4_mapped_heading[IPV4_MAPPED_HEADING_LEN] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
return memcmp(addr, ipv4_mapped_heading, IPV4_MAPPED_HEADING_LEN) == 0;
}
static const char *
format_nid(const u_char *data)
{
static char buf[4][sizeof("01:01:01:01")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x",
data[0], data[1], data[2], data[3]);
return buf[i];
}
static const char *
format_256(const u_char *data)
{
static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64,
EXTRACT_64BITS(data),
EXTRACT_64BITS(data + 8),
EXTRACT_64BITS(data + 16),
EXTRACT_64BITS(data + 24)
);
return buf[i];
}
static const char *
format_interval(const uint32_t n)
{
static char buf[4][sizeof("0000000.000s")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%u.%03us", n / 1000, n % 1000);
return buf[i];
}
static const char *
format_ip6addr(netdissect_options *ndo, const u_char *cp)
{
if (is_ipv4_mapped_address(cp))
return ipaddr_string(ndo, cp + IPV4_MAPPED_HEADING_LEN);
else
return ip6addr_string(ndo, cp);
}
static int
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length)
{
int plenbytes;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")];
if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 &&
is_ipv4_mapped_address(&prefix[1])) {
struct in_addr addr;
u_int plen;
plen = prefix[0]-96;
if (32 < plen)
return -1;
max_length -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN)
return -3;
memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen);
plenbytes += 1 + IPV4_MAPPED_HEADING_LEN;
} else {
plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf));
}
ND_PRINT((ndo, "%s", buf));
return plenbytes;
}
static int
print_dns_label(netdissect_options *ndo,
const u_char *cp, u_int max_length, int print)
{
u_int length = 0;
while (length < max_length) {
u_int lab_length = cp[length++];
if (lab_length == 0)
return (int)length;
if (length > 1 && print)
safeputchar(ndo, '.');
if (length+lab_length > max_length) {
if (print)
safeputs(ndo, cp+length, max_length-length);
break;
}
if (print)
safeputs(ndo, cp+length, lab_length);
length += lab_length;
}
if (print)
ND_PRINT((ndo, "[|DNS]"));
return -1;
}
static int
dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
static int
dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
if (i + 4 > length)
return -1;
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
if (i + 4 + optlen > length)
return -1;
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
/* Determine in-line mode */
static int
is_in_line(netdissect_options *ndo, int indent)
{
return indent - 1 >= ndo->ndo_vflag && ndo->ndo_vflag < 3;
}
static void
print_type_in_line(netdissect_options *ndo,
uint32_t type, int count, int indent, int *first_one)
{
if (count > 0) {
if (*first_one) {
*first_one = 0;
if (indent > 1) {
u_int t;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
} else {
ND_PRINT((ndo, " "));
}
} else {
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, "%s", tok2str(type_values, "Easter Egg", type)));
if (count > 1)
ND_PRINT((ndo, " (x%d)", count));
}
}
void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
const int in_line = is_in_line(ndo, indent);
int first_one = 1;
u_int i, t;
uint32_t last_type_mask = 0xffffffffU;
int last_type_count = -1;
const u_char *tlv, *value;
uint16_t type, bodylen;
uint32_t type_mask;
i = 0;
while (i < length) {
tlv = cp + i;
if (!in_line) {
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
}
ND_TCHECK2(*tlv, 4);
if (i + 4 > length)
goto invalid;
type = EXTRACT_16BITS(tlv);
bodylen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_TCHECK2(*value, bodylen);
if (i + bodylen + 4 > length)
goto invalid;
type_mask =
(type == 0) ? RANGE_DNCP_RESERVED:
(44 <= type && type <= 511) ? RANGE_HNCP_UNASSIGNED:
(768 <= type && type <= 1023) ? RANGE_DNCP_PRIVATE_USE:
RANGE_DNCP_FUTURE_USE;
if (type == 6 || type == 7)
type_mask = RANGE_DNCP_FUTURE_USE;
/* defined types */
{
t = 0;
while (1) {
u_int key = type_values[t++].v;
if (key > 0xffff)
break;
if (key == type) {
type_mask = type;
break;
}
}
}
if (in_line) {
if (last_type_mask == type_mask) {
last_type_count++;
} else {
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
last_type_mask = type_mask;
last_type_count = 1;
}
goto skip_multiline;
}
ND_PRINT((ndo,"%s", tok2str(type_values, "Easter Egg (42)", type_mask) ));
if (type_mask > 0xffff)
ND_PRINT((ndo,": type=%u", type ));
ND_PRINT((ndo," (%u)", bodylen + 4 ));
switch (type_mask) {
case DNCP_REQUEST_NETWORK_STATE: {
if (bodylen != 0)
ND_PRINT((ndo, " %s", istr));
}
break;
case DNCP_REQUEST_NODE_STATE: {
const char *node_identifier;
if (bodylen != 4) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
ND_PRINT((ndo, " NID: %s", node_identifier));
}
break;
case DNCP_NODE_ENDPOINT: {
const char *node_identifier;
uint32_t endpoint_identifier;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
endpoint_identifier = EXTRACT_32BITS(value + 4);
ND_PRINT((ndo, " NID: %s EPID: %08x",
node_identifier,
endpoint_identifier
));
}
break;
case DNCP_NETWORK_STATE: {
uint64_t hash;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
hash = EXTRACT_64BITS(value);
ND_PRINT((ndo, " hash: %016" PRIx64, hash));
}
break;
case DNCP_NODE_STATE: {
const char *node_identifier, *interval;
uint32_t sequence_number;
uint64_t hash;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
sequence_number = EXTRACT_32BITS(value + 4);
interval = format_interval(EXTRACT_32BITS(value + 8));
hash = EXTRACT_64BITS(value + 12);
ND_PRINT((ndo, " NID: %s seqno: %u %s hash: %016" PRIx64,
node_identifier,
sequence_number,
interval,
hash
));
hncp_print_rec(ndo, value+20, bodylen-20, indent+1);
}
break;
case DNCP_PEER: {
const char *peer_node_identifier;
uint32_t peer_endpoint_identifier, endpoint_identifier;
if (bodylen != 12) {
ND_PRINT((ndo, " %s", istr));
break;
}
peer_node_identifier = format_nid(value);
peer_endpoint_identifier = EXTRACT_32BITS(value + 4);
endpoint_identifier = EXTRACT_32BITS(value + 8);
ND_PRINT((ndo, " Peer-NID: %s Peer-EPID: %08x Local-EPID: %08x",
peer_node_identifier,
peer_endpoint_identifier,
endpoint_identifier
));
}
break;
case DNCP_KEEP_ALIVE_INTERVAL: {
uint32_t endpoint_identifier;
const char *interval;
if (bodylen < 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
interval = format_interval(EXTRACT_32BITS(value + 4));
ND_PRINT((ndo, " EPID: %08x Interval: %s",
endpoint_identifier,
interval
));
}
break;
case DNCP_TRUST_VERDICT: {
if (bodylen <= 36) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Verdict: %u Fingerprint: %s Common Name: ",
*value,
format_256(value + 4)));
safeputs(ndo, value + 36, bodylen - 36);
}
break;
case HNCP_HNCP_VERSION: {
uint16_t capabilities;
uint8_t M, P, H, L;
if (bodylen < 5) {
ND_PRINT((ndo, " %s", istr));
break;
}
capabilities = EXTRACT_16BITS(value + 2);
M = (uint8_t)((capabilities >> 12) & 0xf);
P = (uint8_t)((capabilities >> 8) & 0xf);
H = (uint8_t)((capabilities >> 4) & 0xf);
L = (uint8_t)(capabilities & 0xf);
ND_PRINT((ndo, " M: %u P: %u H: %u L: %u User-agent: ",
M, P, H, L
));
safeputs(ndo, value + 4, bodylen - 4);
}
break;
case HNCP_EXTERNAL_CONNECTION: {
/* Container TLV */
hncp_print_rec(ndo, value, bodylen, indent+1);
}
break;
case HNCP_DELEGATED_PREFIX: {
int l;
if (bodylen < 9 || bodylen < 9 + (value[8] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " VLSO: %s PLSO: %s Prefix: ",
format_interval(EXTRACT_32BITS(value)),
format_interval(EXTRACT_32BITS(value + 4))
));
l = print_prefix(ndo, value + 8, bodylen - 8);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
l += 8 + (-l & 3);
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_PREFIX_POLICY: {
uint8_t policy;
int l;
if (bodylen < 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
policy = value[0];
ND_PRINT((ndo, " type: "));
if (policy == 0) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Internet connectivity"));
} else if (policy >= 1 && policy <= 128) {
ND_PRINT((ndo, "Dest-Prefix: "));
l = print_prefix(ndo, value, bodylen);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
} else if (policy == 129) {
ND_PRINT((ndo, "DNS domain: "));
print_dns_label(ndo, value+1, bodylen-1, 1);
} else if (policy == 130) {
ND_PRINT((ndo, "Opaque UTF-8: "));
safeputs(ndo, value + 1, bodylen - 1);
} else if (policy == 131) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Restrictive assignment"));
} else if (policy >= 132) {
ND_PRINT((ndo, "Unknown (%u)", policy)); /* Reserved for future additions */
}
}
break;
case HNCP_DHCPV4_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv4_print(ndo, value, bodylen, indent+1) != 0)
goto invalid;
}
break;
case HNCP_DHCPV6_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv6_print(ndo, value, bodylen, indent+1) != 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
}
break;
case HNCP_ASSIGNED_PREFIX: {
uint8_t prty;
int l;
if (bodylen < 6 || bodylen < 6 + (value[5] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
prty = (uint8_t)(value[4] & 0xf);
ND_PRINT((ndo, " EPID: %08x Prty: %u",
EXTRACT_32BITS(value),
prty
));
ND_PRINT((ndo, " Prefix: "));
if ((l = print_prefix(ndo, value + 5, bodylen - 5)) < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
l += 5;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_NODE_ADDRESS: {
uint32_t endpoint_identifier;
const char *ip_address;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
ip_address = format_ip6addr(ndo, value + 4);
ND_PRINT((ndo, " EPID: %08x IP Address: %s",
endpoint_identifier,
ip_address
));
hncp_print_rec(ndo, value + 20, bodylen - 20, indent+1);
}
break;
case HNCP_DNS_DELEGATED_ZONE: {
const char *ip_address;
int len;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
ip_address = format_ip6addr(ndo, value);
ND_PRINT((ndo, " IP-Address: %s %c%c%c ",
ip_address,
(value[16] & 4) ? 'l' : '-',
(value[16] & 2) ? 'b' : '-',
(value[16] & 1) ? 's' : '-'
));
len = print_dns_label(ndo, value+17, bodylen-17, 1);
if (len < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
len += 17;
len += -len & 3;
if (bodylen >= len)
hncp_print_rec(ndo, value+len, bodylen-len, indent+1);
}
break;
case HNCP_DOMAIN_NAME: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Domain: "));
print_dns_label(ndo, value, bodylen, 1);
}
break;
case HNCP_NODE_NAME: {
u_int l;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
l = value[16];
if (bodylen < 17 + l) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " IP-Address: %s Name: ",
format_ip6addr(ndo, value)
));
if (l < 64) {
safeputchar(ndo, '"');
safeputs(ndo, value + 17, l);
safeputchar(ndo, '"');
} else {
ND_PRINT((ndo, "%s", istr));
}
l += 17;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_MANAGED_PSK: {
if (bodylen < 32) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " PSK: %s", format_256(value)));
hncp_print_rec(ndo, value + 32, bodylen - 32, indent+1);
}
break;
case RANGE_DNCP_RESERVED:
case RANGE_HNCP_UNASSIGNED:
case RANGE_DNCP_PRIVATE_USE:
case RANGE_DNCP_FUTURE_USE:
break;
}
skip_multiline:
i += 4 + bodylen + (-bodylen & 3);
}
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
return;
trunc:
ND_PRINT((ndo, "%s", "[|hncp]"));
return;
invalid:
ND_PRINT((ndo, "%s", istr));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2720_0 |
crossvul-cpp_data_bad_2644_2 | /*
* Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: Cisco HDLC printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ethertype.h"
#include "extract.h"
#include "chdlc.h"
static void chdlc_slarp_print(netdissect_options *, const u_char *, u_int);
static const struct tok chdlc_cast_values[] = {
{ CHDLC_UNICAST, "unicast" },
{ CHDLC_BCAST, "bcast" },
{ 0, NULL}
};
/* Standard CHDLC printer */
u_int
chdlc_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, register const u_char *p)
{
return chdlc_print(ndo, p, h->len);
}
u_int
chdlc_print(netdissect_options *ndo, register const u_char *p, u_int length)
{
u_int proto;
const u_char *bp = p;
if (length < CHDLC_HDRLEN)
goto trunc;
ND_TCHECK2(*p, CHDLC_HDRLEN);
proto = EXTRACT_16BITS(&p[2]);
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "%s, ethertype %s (0x%04x), length %u: ",
tok2str(chdlc_cast_values, "0x%02x", p[0]),
tok2str(ethertype_values, "Unknown", proto),
proto,
length));
}
length -= CHDLC_HDRLEN;
p += CHDLC_HDRLEN;
switch (proto) {
case ETHERTYPE_IP:
ip_print(ndo, p, length);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, p, length);
break;
case CHDLC_TYPE_SLARP:
chdlc_slarp_print(ndo, p, length);
break;
#if 0
case CHDLC_TYPE_CDP:
chdlc_cdp_print(p, length);
break;
#endif
case ETHERTYPE_MPLS:
case ETHERTYPE_MPLS_MULTI:
mpls_print(ndo, p, length);
break;
case ETHERTYPE_ISO:
/* is the fudge byte set ? lets verify by spotting ISO headers */
if (length < 2)
goto trunc;
ND_TCHECK_16BITS(p);
if (*(p+1) == 0x81 ||
*(p+1) == 0x82 ||
*(p+1) == 0x83)
isoclns_print(ndo, p + 1, length - 1, ndo->ndo_snapend - p - 1);
else
isoclns_print(ndo, p, length, ndo->ndo_snapend - p);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "unknown CHDLC protocol (0x%04x)", proto));
break;
}
return (CHDLC_HDRLEN);
trunc:
ND_PRINT((ndo, "[|chdlc]"));
return ndo->ndo_snapend - bp;
}
/*
* The fixed-length portion of a SLARP packet.
*/
struct cisco_slarp {
uint8_t code[4];
#define SLARP_REQUEST 0
#define SLARP_REPLY 1
#define SLARP_KEEPALIVE 2
union {
struct {
uint8_t addr[4];
uint8_t mask[4];
} addr;
struct {
uint8_t myseq[4];
uint8_t yourseq[4];
uint8_t rel[2];
} keep;
} un;
};
#define SLARP_MIN_LEN 14
#define SLARP_MAX_LEN 18
static void
chdlc_slarp_print(netdissect_options *ndo, const u_char *cp, u_int length)
{
const struct cisco_slarp *slarp;
u_int sec,min,hrs,days;
ND_PRINT((ndo, "SLARP (length: %u), ",length));
if (length < SLARP_MIN_LEN)
goto trunc;
slarp = (const struct cisco_slarp *)cp;
ND_TCHECK2(*slarp, SLARP_MIN_LEN);
switch (EXTRACT_32BITS(&slarp->code)) {
case SLARP_REQUEST:
ND_PRINT((ndo, "request"));
/*
* At least according to William "Chops" Westfield's
* message in
*
* http://www.nethelp.no/net/cisco-hdlc.txt
*
* the address and mask aren't used in requests -
* they're just zero.
*/
break;
case SLARP_REPLY:
ND_PRINT((ndo, "reply %s/%s",
ipaddr_string(ndo, &slarp->un.addr.addr),
ipaddr_string(ndo, &slarp->un.addr.mask)));
break;
case SLARP_KEEPALIVE:
ND_PRINT((ndo, "keepalive: mineseen=0x%08x, yourseen=0x%08x, reliability=0x%04x",
EXTRACT_32BITS(&slarp->un.keep.myseq),
EXTRACT_32BITS(&slarp->un.keep.yourseq),
EXTRACT_16BITS(&slarp->un.keep.rel)));
if (length >= SLARP_MAX_LEN) { /* uptime-stamp is optional */
cp += SLARP_MIN_LEN;
ND_TCHECK2(*cp, 4);
sec = EXTRACT_32BITS(cp) / 1000;
min = sec / 60; sec -= min * 60;
hrs = min / 60; min -= hrs * 60;
days = hrs / 24; hrs -= days * 24;
ND_PRINT((ndo, ", link uptime=%ud%uh%um%us",days,hrs,min,sec));
}
break;
default:
ND_PRINT((ndo, "0x%02x unknown", EXTRACT_32BITS(&slarp->code)));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
break;
}
if (SLARP_MAX_LEN < length && ndo->ndo_vflag)
ND_PRINT((ndo, ", (trailing junk: %d bytes)", length - SLARP_MAX_LEN));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo,cp+4,"\n\t",length-4);
return;
trunc:
ND_PRINT((ndo, "[|slarp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_2 |
crossvul-cpp_data_bad_2672_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (netal == 0)
ND_PRINT((ndo, "\n\t %s", etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_MCID_MIN_LEN);
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + sizeof(struct isis_subtlv_spb_mcid);
len = len - sizeof(struct isis_subtlv_spb_mcid);
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_DIGEST_MIN_LEN);
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
ND_TCHECK2(*(tptr), stlv_len);
while (len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_TCHECK2(*(tptr), ISIS_SUBTLV_SPB_BVID_MIN_LEN);
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN);
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
ND_TCHECK2(*tptr, ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN);
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
for (i = 1; i <= SYSTEM_ID_LEN; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2672_0 |
crossvul-cpp_data_bad_4687_0 |
#include <config.h>
#include "ftpd.h"
#include "utils.h"
#ifdef WITH_DMALLOC
# include <dmalloc.h>
#endif
#ifdef HAVE_LIBSODIUM
# if !defined(pure_memzero) || !defined(pure_memcmp)
# error pure_memzero/pure_memcmp not defined
# endif
#else
void pure_memzero(void * const pnt, const size_t len)
{
# ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(pnt, len);
# else
volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;
size_t i = (size_t) 0U;
while (i < len) {
pnt_[i++] = 0U;
}
# endif
}
int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)
{
const unsigned char *b1 = (const unsigned char *) b1_;
const unsigned char *b2 = (const unsigned char *) b2_;
size_t i;
unsigned char d = (unsigned char) 0U;
for (i = 0U; i < len; i++) {
d |= b1[i] ^ b2[i];
}
return (int) ((1 & ((d - 1) >> 8)) - 1);
}
#endif
int pure_strcmp(const char * const s1, const char * const s2)
{
return pure_memcmp(s1, s2, strlen(s1) + 1U);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4687_0 |
crossvul-cpp_data_good_3358_2 | /*
* IPv6 library code, needed by static components when full IPv6 support is
* not configured or static. These functions are needed by GSO/GRO implementation.
*/
#include <linux/export.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/ip6_fib.h>
#include <net/addrconf.h>
#include <net/secure_seq.h>
#include <linux/netfilter.h>
static u32 __ipv6_select_ident(struct net *net, u32 hashrnd,
const struct in6_addr *dst,
const struct in6_addr *src)
{
u32 hash, id;
hash = __ipv6_addr_jhash(dst, hashrnd);
hash = __ipv6_addr_jhash(src, hash);
hash ^= net_hash_mix(net);
/* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve,
* set the hight order instead thus minimizing possible future
* collisions.
*/
id = ip_idents_reserve(hash, 1);
if (unlikely(!id))
id = 1 << 31;
return id;
}
/* This function exists only for tap drivers that must support broken
* clients requesting UFO without specifying an IPv6 fragment ID.
*
* This is similar to ipv6_select_ident() but we use an independent hash
* seed to limit information leakage.
*
* The network header must be set before calling this.
*/
void ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb)
{
static u32 ip6_proxy_idents_hashrnd __read_mostly;
struct in6_addr buf[2];
struct in6_addr *addrs;
u32 id;
addrs = skb_header_pointer(skb,
skb_network_offset(skb) +
offsetof(struct ipv6hdr, saddr),
sizeof(buf), buf);
if (!addrs)
return;
net_get_random_once(&ip6_proxy_idents_hashrnd,
sizeof(ip6_proxy_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd,
&addrs[1], &addrs[0]);
skb_shinfo(skb)->ip6_frag_id = htonl(id);
}
EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident);
__be32 ipv6_select_ident(struct net *net,
const struct in6_addr *daddr,
const struct in6_addr *saddr)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr);
return htonl(id);
}
EXPORT_SYMBOL(ipv6_select_ident);
int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr)
{
u16 offset = sizeof(struct ipv6hdr);
unsigned int packet_len = skb_tail_pointer(skb) -
skb_network_header(skb);
int found_rhdr = 0;
*nexthdr = &ipv6_hdr(skb)->nexthdr;
while (offset <= packet_len) {
struct ipv6_opt_hdr *exthdr;
switch (**nexthdr) {
case NEXTHDR_HOP:
break;
case NEXTHDR_ROUTING:
found_rhdr = 1;
break;
case NEXTHDR_DEST:
#if IS_ENABLED(CONFIG_IPV6_MIP6)
if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0)
break;
#endif
if (found_rhdr)
return offset;
break;
default:
return offset;
}
if (offset + sizeof(struct ipv6_opt_hdr) > packet_len)
return -EINVAL;
exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) +
offset);
offset += ipv6_optlen(exthdr);
*nexthdr = &exthdr->nexthdr;
}
return -EINVAL;
}
EXPORT_SYMBOL(ip6_find_1stfragopt);
#if IS_ENABLED(CONFIG_IPV6)
int ip6_dst_hoplimit(struct dst_entry *dst)
{
int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT);
if (hoplimit == 0) {
struct net_device *dev = dst->dev;
struct inet6_dev *idev;
rcu_read_lock();
idev = __in6_dev_get(dev);
if (idev)
hoplimit = idev->cnf.hop_limit;
else
hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit;
rcu_read_unlock();
}
return hoplimit;
}
EXPORT_SYMBOL(ip6_dst_hoplimit);
#endif
int __ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int len;
len = skb->len - sizeof(struct ipv6hdr);
if (len > IPV6_MAXPLEN)
len = 0;
ipv6_hdr(skb)->payload_len = htons(len);
IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr);
/* if egress device is enslaved to an L3 master device pass the
* skb to its handler for processing
*/
skb = l3mdev_ip6_out(sk, skb);
if (unlikely(!skb))
return 0;
skb->protocol = htons(ETH_P_IPV6);
return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT,
net, sk, skb, NULL, skb_dst(skb)->dev,
dst_output);
}
EXPORT_SYMBOL_GPL(__ip6_local_out);
int ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb)
{
int err;
err = __ip6_local_out(net, sk, skb);
if (likely(err == 1))
err = dst_output(net, sk, skb);
return err;
}
EXPORT_SYMBOL_GPL(ip6_local_out);
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3358_2 |
crossvul-cpp_data_bad_767_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L OOO CCCC AAA L EEEEE %
% L O O C A A L E %
% L O O C AAAAA L EEE %
% L O O C A A L E %
% LLLLL OOO CCCC A A LLLLL EEEEE %
% %
% %
% MagickCore Image Locale Methods %
% %
% Software Design %
% Cristy %
% July 2003 %
% %
% %
% Copyright 1999-2019 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 %
% %
% https://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 "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/client.h"
#include "MagickCore/configure.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image-private.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/locale_.h"
#include "MagickCore/locale-private.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/nt-base-private.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
Define declarations.
*/
#if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT)
# define MAGICKCORE_LOCALE_SUPPORT
#endif
#define LocaleFilename "locale.xml"
/*
Static declarations.
*/
static const char
*LocaleMap =
"<?xml version=\"1.0\"?>"
"<localemap>"
" <locale name=\"C\">"
" <Exception>"
" <Message name=\"\">"
" </Message>"
" </Exception>"
" </locale>"
"</localemap>";
#ifdef __VMS
#define asciimap AsciiMap
#endif
#if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP)
static const unsigned char
AsciiMap[] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73,
0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b,
0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,
0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3,
0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb,
0xfc, 0xfd, 0xfe, 0xff,
};
#endif
static SemaphoreInfo
*locale_semaphore = (SemaphoreInfo *) NULL;
static SplayTreeInfo
*locale_cache = (SplayTreeInfo *) NULL;
#if defined(MAGICKCORE_LOCALE_SUPPORT)
static volatile locale_t
c_locale = (locale_t) NULL;
#endif
/*
Forward declarations.
*/
static MagickBooleanType
IsLocaleTreeInstantiated(ExceptionInfo *),
LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *,
const size_t,ExceptionInfo *);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e C L o c a l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireCLocale() allocates the C locale object, or (locale_t) 0 with
% errno set if it cannot be acquired.
%
% The format of the AcquireCLocale method is:
%
% locale_t AcquireCLocale(void)
%
*/
static locale_t AcquireCLocale(void)
{
#if defined(MAGICKCORE_HAVE_NEWLOCALE)
if (c_locale == (locale_t) NULL)
c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0);
#elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__)
if (c_locale == (locale_t) NULL)
c_locale=_create_locale(LC_ALL,"C");
#endif
return(c_locale);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e L o c a l e S p l a y T r e e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireLocaleSplayTree() caches one or more locale configurations which
% provides a mapping between locale attributes and a locale tag.
%
% The format of the AcquireLocaleSplayTree method is:
%
% SplayTreeInfo *AcquireLocaleSplayTree(const char *filename,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o filename: the font file tag.
%
% o locale: the actual locale.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void *DestroyLocaleNode(void *locale_info)
{
register LocaleInfo
*p;
p=(LocaleInfo *) locale_info;
if (p->path != (char *) NULL)
p->path=DestroyString(p->path);
if (p->tag != (char *) NULL)
p->tag=DestroyString(p->tag);
if (p->message != (char *) NULL)
p->message=DestroyString(p->message);
return(RelinquishMagickMemory(p));
}
static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename,
const char *locale,ExceptionInfo *exception)
{
MagickStatusType
status;
SplayTreeInfo
*cache;
cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL,
DestroyLocaleNode);
status=MagickTrue;
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
{
const StringInfo
*option;
LinkedListInfo
*options;
options=GetLocaleOptions(filename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
status&=LoadLocaleCache(cache,(const char *)
GetStringInfoDatum(option),GetStringInfoPath(option),locale,0,
exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyLocaleOptions(options);
if (GetNumberOfNodesInSplayTree(cache) == 0)
{
options=GetLocaleOptions("english.xml",exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
status&=LoadLocaleCache(cache,(const char *)
GetStringInfoDatum(option),GetStringInfoPath(option),locale,0,
exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyLocaleOptions(options);
}
}
#endif
if (GetNumberOfNodesInSplayTree(cache) == 0)
status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0,
exception);
return(cache);
}
#if defined(MAGICKCORE_LOCALE_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y C L o c a l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyCLocale() releases the resources allocated for a locale object
% returned by a call to the AcquireCLocale() method.
%
% The format of the DestroyCLocale method is:
%
% void DestroyCLocale(void)
%
*/
static void DestroyCLocale(void)
{
if (c_locale != (locale_t) NULL)
freelocale(c_locale);
c_locale=(locale_t) NULL;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y L o c a l e O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyLocaleOptions() releases memory associated with an locale
% messages.
%
% The format of the DestroyProfiles method is:
%
% LinkedListInfo *DestroyLocaleOptions(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void *DestroyOptions(void *message)
{
return(DestroyStringInfo((StringInfo *) message));
}
MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages)
{
assert(messages != (LinkedListInfo *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
return(DestroyLinkedList(messages,DestroyOptions));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F o r m a t L o c a l e F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatLocaleFile() prints formatted output of a variable argument list to a
% file in the "C" locale.
%
% The format of the FormatLocaleFile method is:
%
% ssize_t FormatLocaleFile(FILE *file,const char *format,...)
%
% A description of each parameter follows.
%
% o file: the file.
%
% o format: A file describing the format to use to write the remaining
% arguments.
%
*/
MagickPrivate ssize_t FormatLocaleFileList(FILE *file,
const char *magick_restrict format,va_list operands)
{
ssize_t
n;
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L)
{
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vfprintf(file,format,operands);
else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
n=(ssize_t) vfprintf_l(file,format,locale,operands);
#else
n=(ssize_t) vfprintf_l(file,locale,format,operands);
#endif
}
#else
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE)
{
locale_t
locale,
previous_locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vfprintf(file,format,operands);
else
{
previous_locale=uselocale(locale);
n=(ssize_t) vfprintf(file,format,operands);
uselocale(previous_locale);
}
}
#else
n=(ssize_t) vfprintf(file,format,operands);
#endif
#endif
return(n);
}
MagickExport ssize_t FormatLocaleFile(FILE *file,
const char *magick_restrict format,...)
{
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleFileList(file,format,operands);
va_end(operands);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F o r m a t L o c a l e S t r i n g %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatLocaleString() prints formatted output of a variable argument list to
% a string buffer in the "C" locale.
%
% The format of the FormatLocaleString method is:
%
% ssize_t FormatLocaleString(char *string,const size_t length,
% const char *format,...)
%
% A description of each parameter follows.
%
% o string: FormatLocaleString() returns the formatted string in this
% character buffer.
%
% o length: the maximum length of the string.
%
% o format: A string describing the format to use to write the remaining
% arguments.
%
*/
MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string,
const size_t length,const char *magick_restrict format,va_list operands)
{
ssize_t
n;
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L)
{
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vsnprintf(string,length,format,operands);
else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
n=(ssize_t) vsnprintf_l(string,length,format,locale,operands);
#else
n=(ssize_t) vsnprintf_l(string,length,locale,format,operands);
#endif
}
#elif defined(MAGICKCORE_HAVE_VSNPRINTF)
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE)
{
locale_t
locale,
previous_locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vsnprintf(string,length,format,operands);
else
{
previous_locale=uselocale(locale);
n=(ssize_t) vsnprintf(string,length,format,operands);
uselocale(previous_locale);
}
}
#else
n=(ssize_t) vsnprintf(string,length,format,operands);
#endif
#else
n=(ssize_t) vsprintf(string,format,operands);
#endif
if (n < 0)
string[length-1]='\0';
return(n);
}
MagickExport ssize_t FormatLocaleString(char *magick_restrict string,
const size_t length,const char *magick_restrict format,...)
{
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleStringList(string,length,format,operands);
va_end(operands);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t L o c a l e I n f o _ %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleInfo_() searches the locale list for the specified tag and if
% found returns attributes for that element.
%
% The format of the GetLocaleInfo method is:
%
% const LocaleInfo *GetLocaleInfo_(const char *tag,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o tag: the locale tag.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag,
ExceptionInfo *exception)
{
const LocaleInfo
*locale_info;
assert(exception != (ExceptionInfo *) NULL);
if (IsLocaleTreeInstantiated(exception) == MagickFalse)
return((const LocaleInfo *) NULL);
LockSemaphoreInfo(locale_semaphore);
if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0))
{
ResetSplayTreeIterator(locale_cache);
locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
UnlockSemaphoreInfo(locale_semaphore);
return(locale_info);
}
locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag);
UnlockSemaphoreInfo(locale_semaphore);
return(locale_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e I n f o L i s t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleInfoList() returns any locale messages that match the
% specified pattern.
%
% The format of the GetLocaleInfoList function is:
%
% const LocaleInfo **GetLocaleInfoList(const char *pattern,
% size_t *number_messages,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o pattern: Specifies a pointer to a text string containing a pattern.
%
% o number_messages: This integer returns the number of locale messages in
% the list.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int LocaleInfoCompare(const void *x,const void *y)
{
const LocaleInfo
**p,
**q;
p=(const LocaleInfo **) x,
q=(const LocaleInfo **) y;
if (LocaleCompare((*p)->path,(*q)->path) == 0)
return(LocaleCompare((*p)->tag,(*q)->tag));
return(LocaleCompare((*p)->path,(*q)->path));
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern,
size_t *number_messages,ExceptionInfo *exception)
{
const LocaleInfo
**messages;
register const LocaleInfo
*p;
register ssize_t
i;
/*
Allocate locale list.
*/
assert(pattern != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
assert(number_messages != (size_t *) NULL);
*number_messages=0;
p=GetLocaleInfo_("*",exception);
if (p == (const LocaleInfo *) NULL)
return((const LocaleInfo **) NULL);
messages=(const LocaleInfo **) AcquireQuantumMemory((size_t)
GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages));
if (messages == (const LocaleInfo **) NULL)
return((const LocaleInfo **) NULL);
/*
Generate locale list.
*/
LockSemaphoreInfo(locale_semaphore);
ResetSplayTreeIterator(locale_cache);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
for (i=0; p != (const LocaleInfo *) NULL; )
{
if ((p->stealth == MagickFalse) &&
(GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse))
messages[i++]=p;
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
}
UnlockSemaphoreInfo(locale_semaphore);
qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare);
messages[i]=(LocaleInfo *) NULL;
*number_messages=(size_t) i;
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e L i s t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleList() returns any locale messages that match the specified
% pattern.
%
% The format of the GetLocaleList function is:
%
% char **GetLocaleList(const char *pattern,size_t *number_messages,
% Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o pattern: Specifies a pointer to a text string containing a pattern.
%
% o number_messages: This integer returns the number of messages in the
% list.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int LocaleTagCompare(const void *x,const void *y)
{
register char
**p,
**q;
p=(char **) x;
q=(char **) y;
return(LocaleCompare(*p,*q));
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages,
ExceptionInfo *exception)
{
char
**messages;
register const LocaleInfo
*p;
register ssize_t
i;
/*
Allocate locale list.
*/
assert(pattern != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
assert(number_messages != (size_t *) NULL);
*number_messages=0;
p=GetLocaleInfo_("*",exception);
if (p == (const LocaleInfo *) NULL)
return((char **) NULL);
messages=(char **) AcquireQuantumMemory((size_t)
GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages));
if (messages == (char **) NULL)
return((char **) NULL);
LockSemaphoreInfo(locale_semaphore);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
for (i=0; p != (const LocaleInfo *) NULL; )
{
if ((p->stealth == MagickFalse) &&
(GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse))
messages[i++]=ConstantString(p->tag);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
}
UnlockSemaphoreInfo(locale_semaphore);
qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare);
messages[i]=(char *) NULL;
*number_messages=(size_t) i;
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e M e s s a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleMessage() returns a message in the current locale that matches the
% supplied tag.
%
% The format of the GetLocaleMessage method is:
%
% const char *GetLocaleMessage(const char *tag)
%
% A description of each parameter follows:
%
% o tag: Return a message that matches this tag in the current locale.
%
*/
MagickExport const char *GetLocaleMessage(const char *tag)
{
char
name[MagickLocaleExtent];
const LocaleInfo
*locale_info;
ExceptionInfo
*exception;
if ((tag == (const char *) NULL) || (*tag == '\0'))
return(tag);
exception=AcquireExceptionInfo();
(void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag);
locale_info=GetLocaleInfo_(name,exception);
exception=DestroyExceptionInfo(exception);
if (locale_info != (const LocaleInfo *) NULL)
return(locale_info->message);
return(tag);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleOptions() returns any Magick configuration messages associated
% with the specified filename.
%
% The format of the GetLocaleOptions method is:
%
% LinkedListInfo *GetLocaleOptions(const char *filename,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o filename: the locale file tag.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport LinkedListInfo *GetLocaleOptions(const char *filename,
ExceptionInfo *exception)
{
char
path[MagickPathExtent];
const char
*element;
LinkedListInfo
*messages,
*paths;
StringInfo
*xml;
assert(filename != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
assert(exception != (ExceptionInfo *) NULL);
(void) CopyMagickString(path,filename,MagickPathExtent);
/*
Load XML from configuration files to linked-list.
*/
messages=NewLinkedList(0);
paths=GetConfigurePaths(filename,exception);
if (paths != (LinkedListInfo *) NULL)
{
ResetLinkedListIterator(paths);
element=(const char *) GetNextValueInLinkedList(paths);
while (element != (const char *) NULL)
{
(void) FormatLocaleString(path,MagickPathExtent,"%s%s",element,
filename);
(void) LogMagickEvent(LocaleEvent,GetMagickModule(),
"Searching for locale file: \"%s\"",path);
xml=ConfigureFileToStringInfo(path);
if (xml != (StringInfo *) NULL)
(void) AppendValueToLinkedList(messages,xml);
element=(const char *) GetNextValueInLinkedList(paths);
}
paths=DestroyLinkedList(paths,RelinquishMagickMemory);
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
char
*blob;
blob=(char *) NTResourceToBlob(filename);
if (blob != (char *) NULL)
{
xml=AcquireStringInfo(0);
SetStringInfoLength(xml,strlen(blob)+1);
SetStringInfoDatum(xml,(const unsigned char *) blob);
blob=(char *) RelinquishMagickMemory(blob);
SetStringInfoPath(xml,filename);
(void) AppendValueToLinkedList(messages,xml);
}
}
#endif
ResetLinkedListIterator(messages);
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e V a l u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleValue() returns the message associated with the locale info.
%
% The format of the GetLocaleValue method is:
%
% const char *GetLocaleValue(const LocaleInfo *locale_info)
%
% A description of each parameter follows:
%
% o locale_info: The locale info.
%
*/
MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(locale_info != (LocaleInfo *) NULL);
assert(locale_info->signature == MagickCoreSignature);
return(locale_info->message);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I s L o c a l e T r e e I n s t a n t i a t e d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsLocaleTreeInstantiated() determines if the locale tree is instantiated.
% If not, it instantiates the tree and returns it.
%
% The format of the IsLocaleInstantiated method is:
%
% MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception)
{
if (locale_cache == (SplayTreeInfo *) NULL)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&locale_semaphore);
LockSemaphoreInfo(locale_semaphore);
if (locale_cache == (SplayTreeInfo *) NULL)
{
char
*locale;
register const char
*p;
locale=(char *) NULL;
p=setlocale(LC_CTYPE,(const char *) NULL);
if (p != (const char *) NULL)
locale=ConstantString(p);
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_ALL");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_MESSAGES");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_CTYPE");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LANG");
if (locale == (char *) NULL)
locale=ConstantString("C");
locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception);
locale=DestroyString(locale);
}
UnlockSemaphoreInfo(locale_semaphore);
}
return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n t e r p r e t L o c a l e V a l u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretLocaleValue() interprets the string as a floating point number in
% the "C" locale and returns its value as a double. If sentinal is not a null
% pointer, the method also sets the value pointed by sentinal to point to the
% first character after the number.
%
% The format of the InterpretLocaleValue method is:
%
% double InterpretLocaleValue(const char *value,char **sentinal)
%
% A description of each parameter follows:
%
% o value: the string value.
%
% o sentinal: if sentinal is not NULL, a pointer to the character after the
% last character used in the conversion is stored in the location
% referenced by sentinal.
%
*/
MagickExport double InterpretLocaleValue(const char *magick_restrict string,
char **magick_restrict sentinal)
{
char
*q;
double
value;
if ((*string == '0') && ((string[1] | 0x20)=='x'))
value=(double) strtoul(string,&q,16);
else
{
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L)
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
value=strtod(string,&q);
else
value=strtod_l(string,&q,locale);
#else
value=strtod(string,&q);
#endif
}
if (sentinal != (char **) NULL)
*sentinal=q;
return(value);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t L o c a l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListLocaleInfo() lists the locale info to a file.
%
% The format of the ListLocaleInfo method is:
%
% MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to a FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListLocaleInfo(FILE *file,
ExceptionInfo *exception)
{
const char
*path;
const LocaleInfo
**locale_info;
register ssize_t
i;
size_t
number_messages;
if (file == (const FILE *) NULL)
file=stdout;
number_messages=0;
locale_info=GetLocaleInfoList("*",&number_messages,exception);
if (locale_info == (const LocaleInfo **) NULL)
return(MagickFalse);
path=(const char *) NULL;
for (i=0; i < (ssize_t) number_messages; i++)
{
if (locale_info[i]->stealth != MagickFalse)
continue;
if ((path == (const char *) NULL) ||
(LocaleCompare(path,locale_info[i]->path) != 0))
{
if (locale_info[i]->path != (char *) NULL)
(void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path);
(void) FormatLocaleFile(file,"Tag/Message\n");
(void) FormatLocaleFile(file,
"-------------------------------------------------"
"------------------------------\n");
}
path=locale_info[i]->path;
(void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag);
if (locale_info[i]->message != (char *) NULL)
(void) FormatLocaleFile(file," %s",locale_info[i]->message);
(void) FormatLocaleFile(file,"\n");
}
(void) fflush(file);
locale_info=(const LocaleInfo **)
RelinquishMagickMemory((void *) locale_info);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o a d L o c a l e C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LoadLocaleCache() loads the locale configurations which provides a mapping
% between locale attributes and a locale name.
%
% The format of the LoadLocaleCache method is:
%
% MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml,
% const char *filename,const size_t depth,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o xml: The locale list in XML format.
%
% o filename: The locale list filename.
%
% o depth: depth of <include /> statements.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void ChopLocaleComponents(char *path,const size_t components)
{
register char
*p;
ssize_t
count;
if (*path == '\0')
return;
p=path+strlen(path)-1;
if (*p == '/')
*p='\0';
for (count=0; (count < (ssize_t) components) && (p > path); p--)
if (*p == '/')
{
*p='\0';
count++;
}
if (count < (ssize_t) components)
*path='\0';
}
static void LocaleFatalErrorHandler(
const ExceptionType magick_unused(severity),
const char *reason,const char *description)
{
magick_unreferenced(severity);
if (reason == (char *) NULL)
return;
(void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason);
if (description != (char *) NULL)
(void) FormatLocaleFile(stderr," (%s)",description);
(void) FormatLocaleFile(stderr,".\n");
(void) fflush(stderr);
exit(1);
}
static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml,
const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception)
{
char
keyword[MagickLocaleExtent],
message[MagickLocaleExtent],
tag[MagickLocaleExtent],
*token;
const char
*q;
FatalErrorHandler
fatal_handler;
LocaleInfo
*locale_info;
MagickStatusType
status;
register char
*p;
size_t
extent;
/*
Read the locale configure file.
*/
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading locale configure file \"%s\" ...",filename);
if (xml == (const char *) NULL)
return(MagickFalse);
status=MagickTrue;
locale_info=(LocaleInfo *) NULL;
*tag='\0';
*message='\0';
*keyword='\0';
fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler);
token=AcquireString(xml);
extent=strlen(token)+MagickPathExtent;
for (q=(char *) xml; *q != '\0'; )
{
/*
Interpret XML.
*/
GetNextToken(q,&q,extent,token);
if (*token == '\0')
break;
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0)
{
/*
Doctype element.
*/
while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0'))
{
GetNextToken(q,&q,extent,token);
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
}
continue;
}
if (LocaleNCompare(keyword,"<!--",4) == 0)
{
/*
Comment element.
*/
while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0'))
{
GetNextToken(q,&q,extent,token);
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
}
continue;
}
if (LocaleCompare(keyword,"<include") == 0)
{
/*
Include element.
*/
while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
if (LocaleCompare(keyword,"locale") == 0)
{
if (LocaleCompare(locale,token) != 0)
break;
continue;
}
if (LocaleCompare(keyword,"file") == 0)
{
if (depth > MagickMaxRecursionDepth)
(void) ThrowMagickException(exception,GetMagickModule(),
ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token);
else
{
char
path[MagickPathExtent],
*file_xml;
*path='\0';
GetPathComponent(filename,HeadPath,path);
if (*path != '\0')
(void) ConcatenateMagickString(path,DirectorySeparator,
MagickPathExtent);
if (*token == *DirectorySeparator)
(void) CopyMagickString(path,token,MagickPathExtent);
else
(void) ConcatenateMagickString(path,token,MagickPathExtent);
file_xml=FileToXML(path,~0UL);
if (file_xml != (char *) NULL)
{
status&=LoadLocaleCache(cache,file_xml,path,locale,
depth+1,exception);
file_xml=DestroyString(file_xml);
}
}
}
}
continue;
}
if (LocaleCompare(keyword,"<locale") == 0)
{
/*
Locale element.
*/
while ((*token != '>') && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
}
continue;
}
if (LocaleCompare(keyword,"</locale>") == 0)
{
ChopLocaleComponents(tag,1);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
if (LocaleCompare(keyword,"<localemap>") == 0)
continue;
if (LocaleCompare(keyword,"</localemap>") == 0)
continue;
if (LocaleCompare(keyword,"<message") == 0)
{
/*
Message element.
*/
while ((*token != '>') && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
if (LocaleCompare(keyword,"name") == 0)
{
(void) ConcatenateMagickString(tag,token,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
}
}
for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
q--;
while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p))
q--;
(void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2),
MagickLocaleExtent));
locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info));
(void) memset(locale_info,0,sizeof(*locale_info));
locale_info->path=ConstantString(filename);
locale_info->tag=ConstantString(tag);
locale_info->message=ConstantString(message);
locale_info->signature=MagickCoreSignature;
status=AddValueToSplayTree(cache,locale_info->tag,locale_info);
if (status == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
locale_info->tag);
(void) ConcatenateMagickString(tag,message,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent);
q++;
continue;
}
if (LocaleCompare(keyword,"</message>") == 0)
{
ChopLocaleComponents(tag,2);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
if (*keyword == '<')
{
/*
Subpath element.
*/
if (*(keyword+1) == '?')
continue;
if (*(keyword+1) == '/')
{
ChopLocaleComponents(tag,1);
if (*tag != '\0')
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
token[strlen(token)-1]='\0';
(void) CopyMagickString(token,token+1,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,token,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
GetNextToken(q,(const char **) NULL,extent,token);
if (*token != '=')
continue;
}
token=(char *) RelinquishMagickMemory(token);
(void) SetFatalErrorHandler(fatal_handler);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e C o m p a r e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleCompare() performs a case-insensitive comparison of two strings
% byte-by-byte, according to the ordering of the current locale encoding.
% LocaleCompare returns an integer greater than, equal to, or less than 0,
% if the string pointed to by p is greater than, equal to, or less than the
% string pointed to by q respectively. The sign of a non-zero return value
% is determined by the sign of the difference between the values of the first
% pair of bytes that differ in the strings being compared.
%
% The format of the LocaleCompare method is:
%
% int LocaleCompare(const char *p,const char *q)
%
% A description of each parameter follows:
%
% o p: A pointer to a character string.
%
% o q: A pointer to a character string to compare to p.
%
*/
MagickExport int LocaleCompare(const char *p,const char *q)
{
if (p == (char *) NULL)
{
if (q == (char *) NULL)
return(0);
return(-1);
}
if (q == (char *) NULL)
return(1);
#if defined(MAGICKCORE_HAVE_STRCASECMP)
return(strcasecmp(p,q));
#else
{
register int
c,
d;
for ( ; ; )
{
c=(int) *((unsigned char *) p);
d=(int) *((unsigned char *) q);
if ((c == 0) || (AsciiMap[c] != AsciiMap[d]))
break;
p++;
q++;
}
return(AsciiMap[c]-(int) AsciiMap[d]);
}
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e L o w e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleLower() transforms all of the characters in the supplied
% null-terminated string, changing all uppercase letters to lowercase.
%
% The format of the LocaleLower method is:
%
% void LocaleLower(char *string)
%
% A description of each parameter follows:
%
% o string: A pointer to the string to convert to lower-case Locale.
%
*/
MagickExport void LocaleLower(char *string)
{
register char
*q;
assert(string != (char *) NULL);
for (q=string; *q != '\0'; q++)
*q=(char) LocaleLowercase((int) *q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e L o w e r c a s e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleLowercase() convert to lowercase.
%
% The format of the LocaleLowercase method is:
%
% void LocaleLowercase(const int c)
%
% A description of each parameter follows:
%
% o If c is a uppercase letter, return its lowercase equivalent.
%
*/
MagickExport int LocaleLowercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e N C o m p a r e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleNCompare() performs a case-insensitive comparison of two strings
% byte-by-byte, according to the ordering of the current locale encoding.
%
% LocaleNCompare returns an integer greater than, equal to, or less than 0,
% if the string pointed to by p is greater than, equal to, or less than the
% string pointed to by q respectively. The sign of a non-zero return value
% is determined by the sign of the difference between the values of the first
% pair of bytes that differ in the strings being compared.
%
% The LocaleNCompare method makes the same comparison as LocaleCompare but
% looks at a maximum of n bytes. Bytes following a null byte are not
% compared.
%
% The format of the LocaleNCompare method is:
%
% int LocaleNCompare(const char *p,const char *q,const size_t n)
%
% A description of each parameter follows:
%
% o p: A pointer to a character string.
%
% o q: A pointer to a character string to compare to p.
%
% o length: the number of characters to compare in strings p and q.
%
*/
MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length)
{
if (p == (char *) NULL)
{
if (q == (char *) NULL)
return(0);
return(-1);
}
if (q == (char *) NULL)
return(1);
#if defined(MAGICKCORE_HAVE_STRNCASECMP)
return(strncasecmp(p,q,length));
#else
{
register int
c,
d;
register size_t
i;
for (i=length; i != 0; i--)
{
c=(int) *((unsigned char *) p);
d=(int) *((unsigned char *) q);
if (AsciiMap[c] != AsciiMap[d])
return(AsciiMap[c]-(int) AsciiMap[d]);
if (c == 0)
return(0);
p++;
q++;
}
return(0);
}
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e U p p e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleUpper() transforms all of the characters in the supplied
% null-terminated string, changing all lowercase letters to uppercase.
%
% The format of the LocaleUpper method is:
%
% void LocaleUpper(char *string)
%
% A description of each parameter follows:
%
% o string: A pointer to the string to convert to upper-case Locale.
%
*/
MagickExport void LocaleUpper(char *string)
{
register char
*q;
assert(string != (char *) NULL);
for (q=string; *q != '\0'; q++)
*q=(char) LocaleUppercase((int) *q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e U p p e r c a s e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleUppercase() convert to uppercase.
%
% The format of the LocaleUppercase method is:
%
% void LocaleUppercase(const int c)
%
% A description of each parameter follows:
%
% o If c is a lowercase letter, return its uppercase equivalent.
%
*/
MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o c a l e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleComponentGenesis() instantiates the locale component.
%
% The format of the LocaleComponentGenesis method is:
%
% MagickBooleanType LocaleComponentGenesis(void)
%
*/
MagickPrivate MagickBooleanType LocaleComponentGenesis(void)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
locale_semaphore=AcquireSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o c a l e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleComponentTerminus() destroys the locale component.
%
% The format of the LocaleComponentTerminus method is:
%
% LocaleComponentTerminus(void)
%
*/
MagickPrivate void LocaleComponentTerminus(void)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&locale_semaphore);
LockSemaphoreInfo(locale_semaphore);
if (locale_cache != (SplayTreeInfo *) NULL)
locale_cache=DestroySplayTree(locale_cache);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
DestroyCLocale();
#endif
UnlockSemaphoreInfo(locale_semaphore);
RelinquishSemaphoreInfo(&locale_semaphore);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_767_0 |
crossvul-cpp_data_good_3186_0 | /*
* Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2007-2008 Sourcefire, Inc.
*
* Authors: Nigel Horne
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* TODO: Optimise messageExport, decodeLine, messageIsEncoding
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#ifdef CL_THREAD_SAFE
#ifndef _REENTRANT
#define _REENTRANT /* for Solaris 2.8 */
#endif
#endif
#ifdef C_DARWIN
#include <sys/types.h>
#endif
#include <stdlib.h>
#include <string.h>
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#ifdef CL_THREAD_SAFE
#include <pthread.h>
#endif
#include "others.h"
#include "str.h"
#include "filetypes.h"
#include "mbox.h"
#include "clamav.h"
#include "json_api.h"
#ifndef isblank
#define isblank(c) (((c) == ' ') || ((c) == '\t'))
#endif
#define RFC2045LENGTH 76 /* maximum number of characters on a line */
#ifdef HAVE_STDBOOL_H
#include <stdbool.h>
#else
#ifdef FALSE
typedef unsigned char bool;
#else
typedef enum { FALSE = 0, TRUE = 1 } bool;
#endif
#endif
static int messageHasArgument(const message *m, const char *variable);
static void messageIsEncoding(message *m);
static unsigned char *decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)(char), bool isFast);
static void sanitiseBase64(char *s);
#ifdef __GNUC__
static unsigned char hex(char c) __attribute__((const));
static unsigned char base64(char c) __attribute__((const));
static unsigned char uudecode(char c) __attribute__((const));
#else
static unsigned char hex(char c);
static unsigned char base64(char c);
static unsigned char uudecode(char c);
#endif
static const char *messageGetArgument(const message *m, int arg);
static void *messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy)(void *), void (*setFilename)(void *, const char *, const char *), void (*addData)(void *, const unsigned char *, size_t), void *(*exportText)(text *, void *, int), void (*setCTX)(void *, cli_ctx *), int destroy_text);
static int usefulArg(const char *arg);
static void messageDedup(message *m);
static char *rfc2231(const char *in);
static int simil(const char *str1, const char *str2);
/*
* These maps are ordered in decreasing likelyhood of their appearance
* in an e-mail. Probably these should be in a table...
*/
static const struct encoding_map {
const char *string;
encoding_type type;
} encoding_map[] = { /* rfc2045 */
{ "7bit", NOENCODING },
{ "text/plain", NOENCODING },
{ "quoted-printable", QUOTEDPRINTABLE }, /* rfc2045 */
{ "base64", BASE64 }, /* rfc2045 */
{ "8bit", EIGHTBIT },
{ "binary", BINARY },
{ "x-uuencode", UUENCODE }, /* uuencode(5) */
{ "x-yencode", YENCODE },
{ "x-binhex", BINHEX },
{ "us-ascii", NOENCODING }, /* incorrect */
{ "x-uue", UUENCODE }, /* incorrect */
{ "uuencode", UUENCODE }, /* incorrect */
{ NULL, NOENCODING }
};
static const struct mime_map {
const char *string;
mime_type type;
} mime_map[] = {
{ "text", TEXT },
{ "multipart", MULTIPART },
{ "application", APPLICATION },
{ "audio", AUDIO },
{ "image", IMAGE },
{ "message", MESSAGE },
{ "video", VIDEO },
{ NULL, TEXT }
};
/*
* See RFC2045, section 6.8, table 1
*/
static const unsigned char base64Table[256] = {
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,62,255,255,255,63,
52,53,54,55,56,57,58,59,60,61,255,255,255,0,255,255,
255,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
15,16,17,18,19,20,21,22,23,24,25,255,255,255,255,255,
255,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
41,42,43,44,45,46,47,48,49,50,51,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255
};
message *
messageCreate(void)
{
message *m = (message *)cli_calloc(1, sizeof(message));
if(m)
m->mimeType = NOMIME;
return m;
}
void
messageDestroy(message *m)
{
assert(m != NULL);
messageReset(m);
free(m);
}
void
messageReset(message *m)
{
int i;
assert(m != NULL);
if(m->mimeSubtype)
free(m->mimeSubtype);
if(m->mimeDispositionType)
free(m->mimeDispositionType);
if(m->mimeArguments) {
for(i = 0; i < m->numberOfArguments; i++)
free(m->mimeArguments[i]);
free(m->mimeArguments);
}
if(m->body_first)
textDestroy(m->body_first);
assert(m->base64chars == 0);
if(m->encodingTypes) {
assert(m->numberOfEncTypes > 0);
free(m->encodingTypes);
}
#if HAVE_JSON
if(m->jobj)
cli_json_delobj(m->jobj);
#endif
memset(m, '\0', sizeof(message));
m->mimeType = NOMIME;
}
/*
* Handle the Content-Type header. The syntax is in RFC1341.
* Return success (1) or failure (0). Failure only happens when it's an
* unknown type and we've already received a known type, or we've received an
* empty type. If we receive an unknown type by itself we default to application
*/
int
messageSetMimeType(message *mess, const char *type)
{
#ifdef CL_THREAD_SAFE
static pthread_mutex_t mime_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif
const struct mime_map *m;
int typeval;
static table_t *mime_table;
assert(mess != NULL);
if(type == NULL) {
cli_dbgmsg("Empty content-type field\n");
return 0;
}
cli_dbgmsg("messageSetMimeType: '%s'\n", type);
/* Ignore leading spaces */
while(!isalpha(*type))
if(*type++ == '\0')
return 0;
#ifdef CL_THREAD_SAFE
pthread_mutex_lock(&mime_mutex);
#endif
if(mime_table == NULL) {
mime_table = tableCreate();
if(mime_table == NULL) {
#ifdef CL_THREAD_SAFE
pthread_mutex_unlock(&mime_mutex);
#endif
return 0;
}
for(m = mime_map; m->string; m++)
if(!tableInsert(mime_table, m->string, m->type)) {
tableDestroy(mime_table);
mime_table = NULL;
#ifdef CL_THREAD_SAFE
pthread_mutex_unlock(&mime_mutex);
#endif
return 0;
}
}
#ifdef CL_THREAD_SAFE
pthread_mutex_unlock(&mime_mutex);
#endif
typeval = tableFind(mime_table, type);
if(typeval != -1) {
mess->mimeType = (mime_type)typeval;
return 1;
}
if(mess->mimeType == NOMIME) {
if(strncasecmp(type, "x-", 2) == 0)
mess->mimeType = MEXTENSION;
else {
/*
* Force scanning of strange messages
*/
if(strcasecmp(type, "plain") == 0) {
cli_dbgmsg("Incorrect MIME type: `plain', set to Text\n");
mess->mimeType = TEXT;
} else {
/*
* Don't handle broken e-mail probably sending
* Content-Type: plain/text
* instead of
* Content-Type: text/plain
* as an attachment
*/
int highestSimil = 0, t = -1;
const char *closest = NULL;
for(m = mime_map; m->string; m++) {
const int s = simil(m->string, type);
if(s > highestSimil) {
highestSimil = s;
closest = m->string;
t = m->type;
}
}
if(highestSimil >= 50) {
cli_dbgmsg("Unknown MIME type \"%s\" - guessing as %s (%d%% certainty)\n",
type, closest,
highestSimil);
mess->mimeType = (mime_type)t;
} else {
cli_dbgmsg("Unknown MIME type: `%s', set to Application - if you believe this file contains a virus, submit it to www.clamav.net\n", type);
mess->mimeType = APPLICATION;
}
}
}
return 1;
}
return 0;
}
mime_type
messageGetMimeType(const message *m)
{
assert(m != NULL);
return m->mimeType;
}
void
messageSetMimeSubtype(message *m, const char *subtype)
{
assert(m != NULL);
if(subtype == NULL) {
/*
* Handle broken content-type lines, e.g.
* Content-Type: text/
*/
cli_dbgmsg("Empty content subtype\n");
subtype = "";
}
if(m->mimeSubtype)
free(m->mimeSubtype);
m->mimeSubtype = cli_strdup(subtype);
}
const char *
messageGetMimeSubtype(const message *m)
{
return (m->mimeSubtype) ? m->mimeSubtype : "";
}
void
messageSetDispositionType(message *m, const char *disptype)
{
assert(m != NULL);
if(m->mimeDispositionType)
free(m->mimeDispositionType);
if(disptype == NULL) {
m->mimeDispositionType = NULL;
return;
}
/*
* It's broken for there to be an entry such as "Content-Disposition:"
* However some spam and viruses are rather broken, it's a sign
* that something is wrong if we get that - maybe we should force a
* scan of this part
*/
while(*disptype && isspace((int)*disptype))
disptype++;
if(*disptype) {
m->mimeDispositionType = cli_strdup(disptype);
if(m->mimeDispositionType)
strstrip(m->mimeDispositionType);
} else
m->mimeDispositionType = NULL;
}
const char *
messageGetDispositionType(const message *m)
{
return (m->mimeDispositionType) ? m->mimeDispositionType : "";
}
/*
* TODO:
* Arguments are held on a per message basis, they should be held on
* a per section basis. Otherwise what happens if two sections have two
* different values for charset? Probably doesn't matter for the use this
* code will be given, but will need fixing if this code is used elsewhere
*/
void
messageAddArgument(message *m, const char *arg)
{
int offset;
char *p;
assert(m != NULL);
if(arg == NULL)
return; /* Note: this is not an error condition */
while(isspace(*arg))
arg++;
if(*arg == '\0')
/* Empty argument? Probably a broken mail client... */
return;
cli_dbgmsg("messageAddArgument, arg='%s'\n", arg);
if(!usefulArg(arg))
return;
for(offset = 0; offset < m->numberOfArguments; offset++)
if(m->mimeArguments[offset] == NULL)
break;
else if(strcasecmp(arg, m->mimeArguments[offset]) == 0)
return; /* already in there */
if(offset == m->numberOfArguments) {
char **q;
m->numberOfArguments++;
q = (char **)cli_realloc(m->mimeArguments, m->numberOfArguments * sizeof(char *));
if(q == NULL) {
m->numberOfArguments--;
return;
}
m->mimeArguments = q;
}
p = m->mimeArguments[offset] = rfc2231(arg);
if(!p) {
/* problem inside rfc2231() */
cli_dbgmsg("messageAddArgument, error from rfc2231()\n");
return;
}
if(strchr(p, '=') == NULL) {
if(strncmp(p, "filename", 8) == 0) {
/*
* FIXME: Bounce message handling is corrupting the in
* core copies of headers
*/
if (strlen(p) > 8) {
cli_dbgmsg("Possible data corruption fixed\n");
p[8] = '=';
} else {
cli_dbgmsg("Possible data corruption not fixed\n");
}
} else {
if(*p)
cli_dbgmsg("messageAddArgument, '%s' contains no '='\n", p);
free(m->mimeArguments[offset]);
m->mimeArguments[offset] = NULL;
return;
}
}
/*
* This is terribly broken from an RFC point of view but is useful
* for catching viruses which have a filename but no type of
* mime. By pretending defaulting to an application rather than
* to nomime we can ensure they're saved and scanned
*/
if((strncasecmp(p, "filename=", 9) == 0) || (strncasecmp(p, "name=", 5) == 0))
if(messageGetMimeType(m) == NOMIME) {
cli_dbgmsg("Force mime encoding to application\n");
messageSetMimeType(m, "application");
}
}
/*
* Add in all the arguments.
* Cope with:
* name="foo bar.doc"
* charset=foo name=bar
*/
void
messageAddArguments(message *m, const char *s)
{
const char *string = s;
cli_dbgmsg("Add arguments '%s'\n", string);
assert(string != NULL);
while(*string) {
const char *key, *cptr;
char *data, *field;
size_t datasz=0;
if(isspace(*string & 0xff) || (*string == ';')) {
string++;
continue;
}
key = string;
data = strchr(string, '=');
/*
* Some spam breaks RFC2045 by using ':' instead of '='
* e.g.:
* Content-Type: text/html; charset:ISO-8859-1
* should be:
* Content-type: text/html; charset=ISO-8859-1
*
* We give up with lines that are completely broken because
* we don't have ESP and don't know what was meant to be there.
* It's unlikely to really be a problem.
*/
if(data == NULL)
data = strchr(string, ':');
if(data == NULL) {
/*
* Completely broken, give up
*/
cli_dbgmsg("Can't parse header \"%s\"\n", s);
return;
}
string = &data[1];
/*
* Handle white space to the right of the equals sign
* This breaks RFC2045 which has:
* parameter := attribute "=" value
* attribute := token ; case-insensitive
* token := 1*<any (ASCII) CHAR except SPACE, CTLs,
* or tspecials>
* But too many MUAs ignore this
*/
while(isspace(*string) && (*string != '\0'))
string++;
cptr = string++;
if(strlen(key) == 0)
continue;
if(*cptr == '"') {
char *ptr, *kcopy;
/*
* The field is in quotes, so look for the
* closing quotes
*/
kcopy = cli_strdup(key);
if(kcopy == NULL)
return;
ptr = strchr(kcopy, '=');
if(ptr == NULL) {
ptr = strchr(kcopy, ':');
if (ptr == NULL) {
cli_dbgmsg("Can't parse header \"%s\"\n", s);
free(kcopy);
return;
}
}
*ptr = '\0';
string = strchr(++cptr, '"');
if(string == NULL) {
cli_dbgmsg("Unbalanced quote character in \"%s\"\n", s);
string = "";
} else
string++;
if(!usefulArg(kcopy)) {
free(kcopy);
continue;
}
data = cli_strdup(cptr);
ptr = (data) ? strchr(data, '"') : NULL;
if(ptr == NULL) {
/*
* Weird e-mail header such as:
* Content-Type: application/octet-stream; name="
* "
* Content-Transfer-Encoding: base64
* Content-Disposition: attachment; filename="
* "
*
* TODO: the file should still be saved and
* virus checked
*/
cli_dbgmsg("Can't parse header \"%s\" - if you believe this file contains a virus, submit it to www.clamav.net\n", s);
if(data)
free(data);
free(kcopy);
return;
}
*ptr = '\0';
datasz = strlen(kcopy) + strlen(data) + 2;
field = cli_realloc(kcopy, strlen(kcopy) + strlen(data) + 2);
if(field) {
cli_strlcat(field, "=", datasz);
cli_strlcat(field, data, datasz);
} else {
free(kcopy);
}
free(data);
} else {
size_t len;
if(*cptr == '\0') {
cli_dbgmsg("Ignoring empty field in \"%s\"\n", s);
return;
}
/*
* The field is not in quotes, so look for the closing
* white space
*/
while((*string != '\0') && !isspace(*string))
string++;
len = (size_t)string - (size_t)key + 1;
field = cli_malloc(len);
if(field) {
memcpy(field, key, len - 1);
field[len - 1] = '\0';
}
}
if(field) {
messageAddArgument(m, field);
free(field);
}
}
}
static const char *
messageGetArgument(const message *m, int arg)
{
assert(m != NULL);
assert(arg >= 0);
assert(arg < m->numberOfArguments);
return (m->mimeArguments[arg]) ? m->mimeArguments[arg] : "";
}
/*
* Find a MIME variable from the header and return a COPY to the value of that
* variable. The caller must free the copy
*/
char *
messageFindArgument(const message *m, const char *variable)
{
int i;
size_t len;
assert(m != NULL);
assert(variable != NULL);
len = strlen(variable);
for(i = 0; i < m->numberOfArguments; i++) {
const char *ptr;
ptr = messageGetArgument(m, i);
if((ptr == NULL) || (*ptr == '\0'))
continue;
#ifdef CL_DEBUG
cli_dbgmsg("messageFindArgument: compare %lu bytes of %s with %s\n",
(unsigned long)len, variable, ptr);
#endif
if(strncasecmp(ptr, variable, len) == 0) {
ptr = &ptr[len];
while(isspace(*ptr))
ptr++;
if(*ptr != '=') {
cli_dbgmsg("messageFindArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i));
return NULL;
}
if((strlen(ptr) > 2) && (*++ptr == '"') && (strchr(&ptr[1], '"') != NULL)) {
/* Remove any quote characters */
char *ret = cli_strdup(++ptr);
char *p;
if(ret == NULL)
return NULL;
/*
* fix un-quoting of boundary strings from
* header, occurs if boundary was given as
* 'boundary="_Test_";'
*
* At least two quotes in string, assume
* quoted argument
* end string at next quote
*/
if((p = strchr(ret, '"')) != NULL) {
ret[strlen(ret) - 1] = '\0';
*p = '\0';
}
return ret;
}
return cli_strdup(ptr);
}
}
return NULL;
}
char *
messageGetFilename(const message *m)
{
char *filename = (char *)messageFindArgument(m, "filename");
if(filename)
return filename;
return (char *)messageFindArgument(m, "name");
}
/* Returns true or false */
static int
messageHasArgument(const message *m, const char *variable)
{
int i;
size_t len;
assert(m != NULL);
assert(variable != NULL);
len = strlen(variable);
for(i = 0; i < m->numberOfArguments; i++) {
const char *ptr;
ptr = messageGetArgument(m, i);
if((ptr == NULL) || (*ptr == '\0'))
continue;
#ifdef CL_DEBUG
cli_dbgmsg("messageHasArgument: compare %lu bytes of %s with %s\n",
(unsigned long)len, variable, ptr);
#endif
if(strncasecmp(ptr, variable, len) == 0) {
ptr = &ptr[len];
while(isspace(*ptr))
ptr++;
if(*ptr != '=') {
cli_dbgmsg("messageHasArgument: no '=' sign found in MIME header '%s' (%s)\n", variable, messageGetArgument(m, i));
return 0;
}
return 1;
}
}
return 0;
}
int
messageHasFilename(const message *m)
{
return messageHasArgument(m, "filename") || messageHasArgument(m, "file");
}
void
messageSetEncoding(message *m, const char *enctype)
{
const struct encoding_map *e;
int i;
char *type;
assert(m != NULL);
assert(enctype != NULL);
/*m->encodingType = EEXTENSION;*/
while(isblank(*enctype))
enctype++;
cli_dbgmsg("messageSetEncoding: '%s'\n", enctype);
if(strcasecmp(enctype, "8 bit") == 0) {
cli_dbgmsg("Broken content-transfer-encoding: '8 bit' changed to '8bit'\n");
enctype = "8bit";
}
/*
* Iterate through
* Content-Transfer-Encoding: base64 binary
* cli_strtok's fieldno counts from 0
*/
i = 0;
while((type = cli_strtok(enctype, i++, " \t")) != NULL) {
int highestSimil = 0;
const char *closest = NULL;
for(e = encoding_map; e->string; e++) {
int sim;
const char lowertype = tolower(type[0]);
if((lowertype != tolower(e->string[0])) && (lowertype != 'x'))
/*
* simil is expensive, I'm yet to encounter only
* one example of a missent encoding when the
* first character was wrong, so lets assume no
* match to save the call.
*
* That example was quoted-printable sent as
* X-quoted-printable.
*/
continue;
if(strcmp(e->string, "uuencode") == 0)
/*
* No need to test here - fast track visa will have
* handled uuencoded files
*/
continue;
sim = simil(type, e->string);
if(sim == 100) {
int j;
encoding_type *et;
for(j = 0; j < m->numberOfEncTypes; j++)
if(m->encodingTypes[j] == e->type)
break;
if(j < m->numberOfEncTypes) {
cli_dbgmsg("Ignoring duplicate encoding mechanism '%s'\n",
type);
break;
}
et = (encoding_type *)cli_realloc(m->encodingTypes, (m->numberOfEncTypes + 1) * sizeof(encoding_type));
if(et == NULL)
break;
m->encodingTypes = et;
m->encodingTypes[m->numberOfEncTypes++] = e->type;
cli_dbgmsg("Encoding type %d is \"%s\"\n", m->numberOfEncTypes, type);
break;
} else if(sim > highestSimil) {
closest = e->string;
highestSimil = sim;
}
}
if(e->string == NULL) {
/*
* The stated encoding type is illegal, so we
* use a best guess of what it should be.
*
* 50% is arbitary. For example 7bi will match as
* 66% certain to be 7bit
*/
if(highestSimil >= 50) {
cli_dbgmsg("Unknown encoding type \"%s\" - guessing as %s (%u%% certainty)\n",
type, closest, highestSimil);
messageSetEncoding(m, closest);
} else {
cli_dbgmsg("Unknown encoding type \"%s\" - if you believe this file contains a virus, submit it to www.clamav.net\n", type);
/*
* Err on the side of safety, enable all
* decoding modules
*/
messageSetEncoding(m, "base64");
messageSetEncoding(m, "quoted-printable");
}
}
free(type);
}
}
encoding_type
messageGetEncoding(const message *m)
{
assert(m != NULL);
if(m->numberOfEncTypes == 0)
return NOENCODING;
return m->encodingTypes[0];
}
int
messageAddLine(message *m, line_t *line)
{
assert(m != NULL);
if(m->body_first == NULL)
m->body_last = m->body_first = (text *)cli_malloc(sizeof(text));
else {
m->body_last->t_next = (text *)cli_malloc(sizeof(text));
m->body_last = m->body_last->t_next;
}
if(m->body_last == NULL) {
cli_errmsg("messageAddLine: out of memory for m->body_last\n");
return -1;
}
m->body_last->t_next = NULL;
if(line && lineGetData(line)) {
m->body_last->t_line = lineLink(line);
messageIsEncoding(m);
} else
m->body_last->t_line = NULL;
return 1;
}
/*
* Add the given line to the end of the given message
* If needed a copy of the given line is taken which the caller must free
* Line must not be terminated by a \n
*/
int
messageAddStr(message *m, const char *data)
{
line_t *repeat = NULL;
assert(m != NULL);
if(data) {
if(*data == '\0')
data = NULL;
else {
/*
* If it's only white space, just store one space to
* save memory. You must store something since it may
* be a header line
*/
int iswhite = 1;
const char *p;
for(p = data; *p; p++)
if(((*p) & 0x80) || !isspace(*p)) {
iswhite = 0;
break;
}
if(iswhite) {
/*cli_dbgmsg("messageAddStr: empty line: '%s'\n", data);*/
data = " ";
}
}
}
if(m->body_first == NULL)
m->body_last = m->body_first = (text *)cli_malloc(sizeof(text));
else {
assert(m->body_last != NULL);
if((data == NULL) && (m->body_last->t_line == NULL))
/*
* Although this would save time and RAM, some
* phish signatures have been built which need the
* blank lines
*/
if(messageGetMimeType(m) != TEXT)
/* don't save two blank lines in sucession */
return 1;
m->body_last->t_next = (text *)cli_malloc(sizeof(text));
if(m->body_last->t_next == NULL) {
messageDedup(m);
m->body_last->t_next = (text *)cli_malloc(sizeof(text));
if(m->body_last->t_next == NULL) {
cli_errmsg("messageAddStr: out of memory\n");
return -1;
}
}
if(data && m->body_last->t_line && (strcmp(data, lineGetData(m->body_last->t_line)) == 0))
repeat = m->body_last->t_line;
m->body_last = m->body_last->t_next;
}
if(m->body_last == NULL) {
cli_errmsg("messageAddStr: out of memory\n");
return -1;
}
m->body_last->t_next = NULL;
if(data && *data) {
if(repeat)
m->body_last->t_line = lineLink(repeat);
else {
m->body_last->t_line = lineCreate(data);
if(m->body_last->t_line == NULL) {
messageDedup(m);
m->body_last->t_line = lineCreate(data);
if(m->body_last->t_line == NULL) {
cli_errmsg("messageAddStr: out of memory\n");
return -1;
}
}
/* cli_chomp(m->body_last->t_text); */
messageIsEncoding(m);
}
} else
m->body_last->t_line = NULL;
return 1;
}
/*
* Add the given line to the start of the given message
* A copy of the given line is taken which the caller must free
* Line must not be terminated by a \n
*/
int
messageAddStrAtTop(message *m, const char *data)
{
text *oldfirst;
assert(m != NULL);
if(m->body_first == NULL)
return messageAddLine(m, lineCreate(data));
oldfirst = m->body_first;
m->body_first = (text *)cli_malloc(sizeof(text));
if(m->body_first == NULL) {
m->body_first = oldfirst;
return -1;
}
m->body_first->t_next = oldfirst;
m->body_first->t_line = lineCreate((data) ? data : "");
if(m->body_first->t_line == NULL) {
cli_errmsg("messageAddStrAtTop: out of memory\n");
return -1;
}
return 1;
}
/*
* Put the contents of the given text at the end of the current object.
* Can be used either to move a text object into a message, or to move a
* message's text into another message only moving from a given offset.
* The given text emptied; it can be used again if needed, though be warned that
* it will have an empty line at the start.
* Returns 0 for failure, 1 for success
*/
int
messageMoveText(message *m, text *t, message *old_message)
{
int rc;
if(m->body_first == NULL) {
if(old_message) {
text *u;
/*
* t is within old_message which is about to be
* destroyed
*/
assert(old_message->body_first != NULL);
m->body_first = t;
for(u = old_message->body_first; u != t;) {
text *next;
if(u->t_line)
lineUnlink(u->t_line);
next = u->t_next;
free(u);
u = next;
if(u == NULL) {
cli_dbgmsg("messageMoveText sanity check: t not within old_message\n");
return -1;
}
}
assert(old_message->body_last->t_next == NULL);
m->body_last = old_message->body_last;
old_message->body_first = old_message->body_last = NULL;
/* Do any pointers need to be reset? */
if((old_message->bounce == NULL) &&
(old_message->encoding == NULL) &&
(old_message->binhex == NULL) &&
(old_message->yenc == NULL))
return 0;
m->body_last = m->body_first;
rc = 0;
} else {
m->body_last = m->body_first = textMove(NULL, t);
if(m->body_first == NULL)
return -1;
else
rc = 0;
}
} else {
m->body_last = textMove(m->body_last, t);
if(m->body_last == NULL) {
rc = -1;
m->body_last = m->body_first;
} else
rc = 0;
}
while(m->body_last->t_next) {
m->body_last = m->body_last->t_next;
if(m->body_last->t_line)
messageIsEncoding(m);
}
return rc;
}
/*
* See if the last line marks the start of a non MIME inclusion that
* will need to be scanned
*/
static void
messageIsEncoding(message *m)
{
static const char encoding[] = "Content-Transfer-Encoding";
static const char binhex[] = "(This file must be converted with BinHex 4.0)";
const char *line = lineGetData(m->body_last->t_line);
/*if(m->ctx == NULL)
cli_dbgmsg("messageIsEncoding, ctx == NULL\n");*/
if((m->encoding == NULL) &&
(strncasecmp(line, encoding, sizeof(encoding) - 1) == 0) &&
(strstr(line, "7bit") == NULL))
m->encoding = m->body_last;
else if((m->bounce == NULL) && m->ctx &&
(strncasecmp(line, "Received: ", 10) == 0) &&
(cli_filetype((const unsigned char *)line, strlen(line), m->ctx->engine) == CL_TYPE_MAIL))
m->bounce = m->body_last;
/* Not needed with fast track visa technology */
/*else if((m->uuencode == NULL) && isuuencodebegin(line))
m->uuencode = m->body_last;*/
else if((m->binhex == NULL) &&
strstr(line, "BinHex") &&
(simil(line, binhex) > 90))
/*
* Look for close matches for BinHex, but
* simil() is expensive so only do it if it's
* likely to be found
*/
m->binhex = m->body_last;
else if((m->yenc == NULL) && (strncmp(line, "=ybegin line=", 13) == 0))
m->yenc = m->body_last;
}
/*
* Returns a pointer to the body of the message. Note that it does NOT return
* a copy of the data
*/
text *
messageGetBody(message *m)
{
assert(m != NULL);
return m->body_first;
}
/*
* Export a message using the given export routines
*
* TODO: It really should export into an array, one
* for each encoding algorithm. However, what it does is it returns the
* last item that was exported. That's sufficient for now.
*/
static void *
messageExport(message *m, const char *dir, void *(*create)(void), void (*destroy)(void *), void (*setFilename)(void *, const char *, const char *), void (*addData)(void *, const unsigned char *, size_t), void *(*exportText)(text *, void *, int), void(*setCTX)(void *, cli_ctx *), int destroy_text)
{
void *ret;
text *t_line;
char *filename;
int i;
assert(m != NULL);
if(messageGetBody(m) == NULL)
return NULL;
ret = (*create)();
if(ret == NULL)
return NULL;
cli_dbgmsg("messageExport: numberOfEncTypes == %d\n", m->numberOfEncTypes);
if(m->numberOfEncTypes == 0) {
/*
* Fast copy
*/
cli_dbgmsg("messageExport: Entering fast copy mode\n");
#if 0
filename = messageGetFilename(m);
if(filename == NULL) {
cli_dbgmsg("Unencoded attachment sent with no filename\n");
messageAddArgument(m, "name=attachment");
} else if((strcmp(filename, "textportion") != 0) && (strcmp(filename, "mixedtextportion") != 0))
/*
* Some virus attachments don't say how they've
* been encoded. We assume base64
*/
messageSetEncoding(m, "base64");
#else
filename = (char *)messageFindArgument(m, "filename");
if(filename == NULL) {
filename = (char *)messageFindArgument(m, "name");
if(filename == NULL) {
cli_dbgmsg("Unencoded attachment sent with no filename\n");
messageAddArgument(m, "name=attachment");
} else
/*
* Some virus attachments don't say how they've
* been encoded. We assume base64.
* RFC says encoding should be 7-bit.
*/
messageSetEncoding(m, "7-bit");
}
#endif
(*setFilename)(ret, dir, (filename && *filename) ? filename : "attachment");
if(filename)
free((char *)filename);
if(m->numberOfEncTypes == 0)
return exportText(messageGetBody(m), ret, destroy_text);
}
if(setCTX && m->ctx)
(*setCTX)(ret, m->ctx);
for(i = 0; i < m->numberOfEncTypes; i++) {
encoding_type enctype = m->encodingTypes[i];
size_t size;
if(i > 0) {
void *newret;
newret = (*create)();
if(newret == NULL) {
cli_dbgmsg("Not all decoding algorithms were run\n");
return ret;
}
(*destroy)(ret);
ret = newret;
}
cli_dbgmsg("messageExport: enctype %d is %d\n", i, (int)enctype);
/*
* Find the filename to decode
*/
if(((enctype == YENCODE) || (i == 0)) && yEncBegin(m)) {
const char *f;
/*
* TODO: handle multipart yEnc encoded files
*/
t_line = yEncBegin(m);
f = lineGetData(t_line->t_line);
if((filename = strstr(f, " name=")) != NULL) {
filename = cli_strdup(&filename[6]);
if(filename) {
cli_chomp(filename);
strstrip(filename);
cli_dbgmsg("Set yEnc filename to \"%s\"\n", filename);
}
}
(*setFilename)(ret, dir, (filename && *filename) ? filename : "attachment");
if(filename) {
free((char *)filename);
filename = NULL;
}
t_line = t_line->t_next;
enctype = YENCODE;
m->yenc = NULL;
} else {
if(enctype == UUENCODE) {
/*
* The body will have been stripped out by the
* fast track visa system. Treat as plain/text,
* which means we'll still scan for funnies
* outside of the uuencoded portion.
*/
cli_dbgmsg("messageExport: treat uuencode as text/plain\n");
enctype = m->encodingTypes[i] = NOENCODING;
}
filename = messageGetFilename(m);
if(filename == NULL) {
cli_dbgmsg("Attachment sent with no filename\n");
messageAddArgument(m, "name=attachment");
} else if(enctype == NOENCODING)
/*
* Some virus attachments don't say how
* they've been encoded. We assume
* base64.
*
* FIXME: don't do this if it's a fall
* through from uuencode
*/
messageSetEncoding(m, "base64");
(*setFilename)(ret, dir, (filename && *filename) ? filename : "attachment");
t_line = messageGetBody(m);
}
if(filename)
free((char *)filename);
/*
* t_line should now point to the first (encoded) line of the
* message
*/
if(t_line == NULL) {
cli_dbgmsg("Empty attachment not saved\n");
(*destroy)(ret);
return NULL;
}
if(enctype == NOENCODING) {
/*
* Fast copy
*/
if(i == m->numberOfEncTypes - 1) {
/* last one */
(void)exportText(t_line, ret, destroy_text);
break;
}
(void)exportText(t_line, ret, 0);
continue;
}
size = 0;
do {
unsigned char smallbuf[1024];
unsigned char *uptr, *data;
const char *line = lineGetData(t_line->t_line);
unsigned char *bigbuf;
size_t datasize;
if(enctype == YENCODE) {
if(line == NULL)
continue;
if(strncmp(line, "=yend ", 6) == 0)
break;
}
/*
* Add two bytes for '\n' and '\0'
*/
datasize = (line) ? strlen(line) + 2 : 0;
if(datasize >= sizeof(smallbuf))
data = bigbuf = (unsigned char *)cli_malloc(datasize);
else {
bigbuf = NULL;
data = smallbuf;
datasize = sizeof(smallbuf);
}
uptr = decodeLine(m, enctype, line, data, datasize);
if(uptr == NULL) {
if(data == bigbuf)
free(data);
break;
}
if(uptr != data) {
assert((size_t)(uptr - data) < datasize);
(*addData)(ret, data, (size_t)(uptr - data));
size += (size_t)(uptr - data);
}
if(data == bigbuf)
free(data);
/*
* According to RFC2045, '=' is used to pad out
* the last byte and should be used as evidence
* of the end of the data. Some mail clients
* annoyingly then put plain text after the '='
* byte and viruses exploit this bug. Sigh
*/
/*if(enctype == BASE64)
if(strchr(line, '='))
break;*/
if(line && destroy_text && (i == m->numberOfEncTypes - 1)) {
lineUnlink(t_line->t_line);
t_line->t_line = NULL;
}
} while((t_line = t_line->t_next) != NULL);
cli_dbgmsg("Exported %lu bytes using enctype %d\n",
(unsigned long)size, (int)enctype);
/* Verify we have nothing left to flush out */
if(m->base64chars) {
unsigned char data[4];
unsigned char *ptr;
ptr = base64Flush(m, data);
if(ptr)
(*addData)(ret, data, (size_t)(ptr - data));
}
}
return ret;
}
unsigned char *
base64Flush(message *m, unsigned char *buf)
{
cli_dbgmsg("%d trailing bytes to export\n", m->base64chars);
if(m->base64chars) {
unsigned char *ret = decode(m, NULL, buf, base64, FALSE);
m->base64chars = 0;
return ret;
}
return NULL;
}
int messageSavePartial(message *m, const char *dir, const char *md5id, unsigned part)
{
char fullname[1024];
fileblob *fb;
unsigned long time_val;
cli_dbgmsg("messageSavePartial\n");
time_val = time(NULL);
snprintf(fullname, 1024, "%s"PATHSEP"clamav-partial-%lu_%s-%u", dir, time_val, md5id, part);
fb = messageExport(m, fullname,
(void *(*)(void))fileblobCreate,
(void(*)(void *))fileblobDestroy,
(void(*)(void *, const char *, const char *))fileblobPartialSet,
(void(*)(void *, const unsigned char *, size_t))fileblobAddData,
(void *(*)(text *, void *, int))textToFileblob,
(void(*)(void *, cli_ctx *))fileblobSetCTX,
0);
if(!fb)
return CL_EFORMAT;
fileblobDestroy(fb);
return CL_SUCCESS;
}
/*
* Decode and transfer the contents of the message into a fileblob
* The caller must free the returned fileblob
*/
fileblob *
messageToFileblob(message *m, const char *dir, int destroy)
{
fileblob *fb;
cli_dbgmsg("messageToFileblob\n");
fb = messageExport(m, dir,
(void *(*)(void))fileblobCreate,
(void(*)(void *))fileblobDestroy,
(void(*)(void *, const char *, const char *))fileblobSetFilename,
(void(*)(void *, const unsigned char *, size_t))fileblobAddData,
(void *(*)(text *, void *, int))textToFileblob,
(void(*)(void *, cli_ctx *))fileblobSetCTX,
destroy);
if(destroy && m->body_first) {
textDestroy(m->body_first);
m->body_first = m->body_last = NULL;
}
return fb;
}
/*
* Decode and transfer the contents of the message into a closed blob
* The caller must free the returned blob
*/
blob *
messageToBlob(message *m, int destroy)
{
blob *b;
cli_dbgmsg("messageToBlob\n");
b = messageExport(m, NULL,
(void *(*)(void))blobCreate,
(void(*)(void *))blobDestroy,
(void(*)(void *, const char *, const char *))blobSetFilename,
(void(*)(void *, const unsigned char *, size_t))blobAddData,
(void *(*)(text *, void *, int))textToBlob,
(void(*)(void *, cli_ctx *))NULL,
destroy);
if(destroy && m->body_first) {
textDestroy(m->body_first);
m->body_first = m->body_last = NULL;
}
return b;
}
/*
* Decode and transfer the contents of the message into a text area
* The caller must free the returned text
*/
text *
messageToText(message *m)
{
int i;
text *first = NULL, *last = NULL;
const text *t_line;
assert(m != NULL);
if(m->numberOfEncTypes == 0) {
/*
* Fast copy
*/
for(t_line = messageGetBody(m); t_line; t_line = t_line->t_next) {
if(first == NULL)
first = last = cli_malloc(sizeof(text));
else {
last->t_next = cli_malloc(sizeof(text));
last = last->t_next;
}
if(last == NULL) {
if(first)
textDestroy(first);
return NULL;
}
if(t_line->t_line)
last->t_line = lineLink(t_line->t_line);
else
last->t_line = NULL; /* empty line */
}
if(last)
last->t_next = NULL;
return first;
}
/*
* Scan over the data a number of times once for each claimed encoding
* type
*/
for(i = 0; i < m->numberOfEncTypes; i++) {
const encoding_type enctype = m->encodingTypes[i];
cli_dbgmsg("messageToText: export transfer method %d = %d\n",
i, (int)enctype);
switch(enctype) {
case NOENCODING:
case BINARY:
case EIGHTBIT:
/*
* Fast copy
*/
for(t_line = messageGetBody(m); t_line; t_line = t_line->t_next) {
if(first == NULL)
first = last = cli_malloc(sizeof(text));
else if (last) {
last->t_next = cli_malloc(sizeof(text));
last = last->t_next;
}
if(last == NULL) {
if(first) {
textDestroy(first);
}
return NULL;
}
if(t_line->t_line)
last->t_line = lineLink(t_line->t_line);
else
last->t_line = NULL; /* empty line */
}
continue;
case UUENCODE:
cli_warnmsg("messageToText: Unexpected attempt to handle uuencoded file\n");
if(first) {
if(last)
last->t_next = NULL;
textDestroy(first);
}
return NULL;
case YENCODE:
t_line = yEncBegin(m);
if(t_line == NULL) {
/*cli_warnmsg("YENCODED attachment is missing begin statement\n");*/
if(first) {
if(last)
last->t_next = NULL;
textDestroy(first);
}
return NULL;
}
t_line = t_line->t_next;
default:
if((i == 0) && binhexBegin(m))
cli_warnmsg("Binhex messages not supported yet.\n");
t_line = messageGetBody(m);
}
for(; t_line; t_line = t_line->t_next) {
unsigned char data[1024];
unsigned char *uptr;
const char *line = lineGetData(t_line->t_line);
if(enctype == BASE64)
/*
* ignore blanks - breaks RFC which is
* probably the point!
*/
if(line == NULL)
continue;
assert((line == NULL) || (strlen(line) <= sizeof(data)));
uptr = decodeLine(m, enctype, line, data, sizeof(data));
if(uptr == NULL)
break;
assert(uptr <= &data[sizeof(data)]);
if(first == NULL)
first = last = cli_malloc(sizeof(text));
else if (last) {
last->t_next = cli_malloc(sizeof(text));
last = last->t_next;
}
if(last == NULL)
break;
/*
* If the decoded line is the same as the encoded
* there's no need to take a copy, just link it.
* Note that the comparison is done without the
* trailing newline that the decoding routine may have
* added - that's why there's a strncmp rather than a
* strcmp - that'd be bad for MIME decoders, but is OK
* for AV software
*/
if((data[0] == '\n') || (data[0] == '\0'))
last->t_line = NULL;
else if(line && (strncmp((const char *)data, line, strlen(line)) == 0)) {
#ifdef CL_DEBUG
cli_dbgmsg("messageToText: decoded line is the same(%s)\n", data);
#endif
last->t_line = lineLink(t_line->t_line);
} else
last->t_line = lineCreate((char *)data);
if(line && enctype == BASE64)
if(strchr(line, '='))
break;
}
if(m->base64chars) {
unsigned char data[4];
memset(data, '\0', sizeof(data));
if(decode(m, NULL, data, base64, FALSE) && data[0]) {
if(first == NULL)
first = last = cli_malloc(sizeof(text));
else if (last) {
last->t_next = cli_malloc(sizeof(text));
last = last->t_next;
}
if(last != NULL)
last->t_line = lineCreate((char *)data);
}
m->base64chars = 0;
}
}
if(last)
last->t_next = NULL;
return first;
}
text *
yEncBegin(message *m)
{
return m->yenc;
}
/*
* Scan to find the BINHEX message (if any)
*/
#if 0
const text *
binhexBegin(message *m)
{
const text *t_line;
for(t_line = messageGetBody(m); t_line; t_line = t_line->t_next)
if(strcasecmp(t_line->t_text, "(This file must be converted with BinHex 4.0)") == 0)
return t_line;
return NULL;
}
#else
text *
binhexBegin(message *m)
{
return m->binhex;
}
#endif
/*
* Scan to find a bounce message. There is no standard for these, not
* even a convention, so don't expect this to be foolproof
*/
#if 0
text *
bounceBegin(message *m)
{
const text *t_line;
for(t_line = messageGetBody(m); t_line; t_line = t_line->t_next)
if(cli_filetype(t_line->t_text, strlen(t_line->t_text)) == CL_TYPE_MAIL)
return t_line;
return NULL;
}
#else
text *
bounceBegin(message *m)
{
return m->bounce;
}
#endif
/*
* If a message doesn't not contain another message which could be harmful
* it is deemed to be safe.
*
* TODO: ensure nothing can get through this
*
* TODO: check to see if we need to
* find anything else, perhaps anything
* from the RFC821 table?
*/
#if 0
int
messageIsAllText(const message *m)
{
const text *t;
for(t = messageGetBody(m); t; t = t->t_next)
if(strncasecmp(t->t_text,
"Content-Transfer-Encoding",
strlen("Content-Transfer-Encoding")) == 0)
return 0;
return 1;
}
#else
text *
encodingLine(message *m)
{
return m->encoding;
}
#endif
/*
* Decode a line and add it to a buffer, return the end of the buffer
* to help appending callers. There is no new line at the end of "line"
*
* len is sizeof(ptr)
*/
unsigned char *
decodeLine(message *m, encoding_type et, const char *line, unsigned char *buf, size_t buflen)
{
size_t len, reallen;
bool softbreak;
char *p2, *copy;
char base64buf[RFC2045LENGTH + 1];
/*cli_dbgmsg("decodeLine(et = %d buflen = %u)\n", (int)et, buflen);*/
assert(m != NULL);
assert(buf != NULL);
switch(et) {
case BINARY:
/*
* TODO: find out what this is, encoded as binary??
*/
/* fall through */
case NOENCODING:
case EIGHTBIT:
default: /* unknown encoding type - try our best */
if(line) /* empty line? */
buf = (unsigned char *)cli_strrcpy((char *)buf, line);
/* Put the new line back in */
return (unsigned char *)cli_strrcpy((char *)buf, "\n");
case QUOTEDPRINTABLE:
if(line == NULL) { /* empty line */
*buf++ = '\n';
break;
}
softbreak = FALSE;
while(buflen && *line) {
if(*line == '=') {
unsigned char byte;
if((*++line == '\0') || (*line == '\n')) {
softbreak = TRUE;
/* soft line break */
break;
}
byte = hex(*line);
if((*++line == '\0') || (*line == '\n')) {
/*
* broken e-mail, not
* adhering to RFC2045
*/
*buf++ = byte;
break;
}
/*
* Handle messages that use a broken
* quoted-printable encoding of
* href=\"http://, instead of =3D
*/
if(byte != '=')
byte = (byte << 4) | hex(*line);
else
line -= 2;
*buf++ = byte;
} else
*buf++ = *line;
++line;
--buflen;
}
if(!softbreak)
/* Put the new line back in */
*buf++ = '\n';
break;
case BASE64:
if(line == NULL)
break;
/*
* RFC2045 sets the maximum length to 76 bytes
* but many e-mail clients ignore that
*/
if(strlen(line) < sizeof(base64buf)) {
strcpy(base64buf, line);
copy = base64buf;
} else {
copy = cli_strdup(line);
if(copy == NULL)
break;
}
p2 = strchr(copy, '=');
if(p2)
*p2 = '\0';
sanitiseBase64(copy);
/*
* Klez doesn't always put "=" on the last line
*/
buf = decode(m, copy, buf, base64, (p2 == NULL) && ((strlen(copy) & 3) == 0));
if(copy != base64buf)
free(copy);
break;
case UUENCODE:
assert(m->base64chars == 0);
if((line == NULL) || (*line == '\0')) /* empty line */
break;
if(strcasecmp(line, "end") == 0)
break;
if(isuuencodebegin(line))
break;
if((line[0] & 0x3F) == ' ')
break;
/*
* reallen contains the number of bytes that were
* encoded
*/
reallen = (size_t)uudecode(*line++);
if(reallen <= 0)
break;
if(reallen > 62)
break;
len = strlen(line);
if((len > buflen) || (reallen > len))
/*
* In practice this should never occur since
* the maximum length of a uuencoded line is
* 62 characters
*/
cli_dbgmsg("uudecode: buffer overflow stopped, attempting to ignore but decoding may fail\n");
else {
(void)decode(m, line, buf, uudecode, (len & 3) == 0);
buf = &buf[reallen];
}
m->base64chars = 0; /* this happens with broken uuencoded files */
break;
case YENCODE:
if((line == NULL) || (*line == '\0')) /* empty line */
break;
if(strncmp(line, "=yend ", 6) == 0)
break;
while(*line)
if(*line == '=') {
if(*++line == '\0')
break;
*buf++ = ((*line++ - 64) & 255);
} else
*buf++ = ((*line++ - 42) & 255);
break;
}
*buf = '\0';
return buf;
}
/*
* Remove the non base64 characters such as spaces from a string. Spaces
* shouldn't appear mid string in base64 files, but some broken mail clients
* ignore such errors rather than discarding the mail, and virus writers
* exploit this bug
*/
static void
sanitiseBase64(char *s)
{
cli_dbgmsg("sanitiseBase64 '%s'\n", s);
while(*s)
if(base64Table[(unsigned int)(*s & 0xFF)] == 255) {
char *p1;
for(p1 = s; p1[0] != '\0'; p1++)
p1[0] = p1[1];
} else
s++;
}
/*
* Returns one byte after the end of the decoded data in "out"
*
* Update m->base64chars with the last few bytes of data that we haven't
* decoded. After the last line is found, decode will be called with in = NULL
* to flush these out
*/
static unsigned char *
decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)(char), bool isFast)
{
unsigned char b1, b2, b3, b4;
unsigned char cb1, cb2, cb3; /* carried over from last line */
/*cli_dbgmsg("decode %s (len %d isFast %d base64chars %d)\n", in,
in ? strlen(in) : 0,
isFast, m->base64chars);*/
cb1 = cb2 = cb3 = '\0';
switch(m->base64chars) {
case 3:
cb3 = m->base64_3;
/* FALLTHROUGH */
case 2:
cb2 = m->base64_2;
/* FALLTHROUGH */
case 1:
cb1 = m->base64_1;
isFast = FALSE;
break;
default:
assert(m->base64chars <= 3);
}
if(isFast)
/* Fast decoding if not last line */
while(*in) {
b1 = (*decoder)(*in++);
b2 = (*decoder)(*in++);
b3 = (*decoder)(*in++);
/*
* Put this line here to help on some compilers which
* can make use of some architecure's ability to
* multiprocess when different variables can be
* updated at the same time - here b3 is used in
* one line, b1/b2 in the next and b4 in the next after
* that, b3 and b4 rely on in but b1/b2 don't
*/
*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);
b4 = (*decoder)(*in++);
*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);
*out++ = (b3 << 6) | (b4 & 0x3F);
}
else if(in == NULL) { /* flush */
int nbytes;
if(m->base64chars == 0)
return out;
cli_dbgmsg("base64chars = %d (%c %c %c)\n", m->base64chars,
isalnum(cb1) ? cb1 : '@',
isalnum(cb2) ? cb2 : '@',
isalnum(cb3) ? cb3 : '@');
m->base64chars--;
b1 = cb1;
nbytes = 1;
if(m->base64chars) {
m->base64chars--;
b2 = cb2;
if(m->base64chars) {
nbytes = 2;
m->base64chars--;
b3 = cb3;
nbytes = 3;
} else if(b2)
nbytes = 2;
}
switch(nbytes) {
case 3:
b4 = '\0';
/* fall through */
case 4:
*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);
*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);
if((nbytes == 4) || (b3&0x3))
*out++ = (b3 << 6) | (b4 & 0x3F);
break;
case 2:
*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);
if((b2 << 4) & 0xFF)
*out++ = b2 << 4;
break;
case 1:
*out++ = b1 << 2;
break;
default:
assert(0);
}
} else while(*in) {
int nbytes;
if(m->base64chars) {
m->base64chars--;
b1 = cb1;
} else
b1 = (*decoder)(*in++);
if(*in == '\0') {
b2 = '\0';
nbytes = 1;
} else {
if(m->base64chars) {
m->base64chars--;
b2 = cb2;
} else
b2 = (*decoder)(*in++);
if(*in == '\0') {
b3 = '\0';
nbytes = 2;
} else {
if(m->base64chars) {
m->base64chars--;
b3 = cb3;
} else
b3 = (*decoder)(*in++);
if(*in == '\0') {
b4 = '\0';
nbytes = 3;
} else {
b4 = (*decoder)(*in++);
nbytes = 4;
}
}
}
switch(nbytes) {
case 4:
*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);
*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);
*out++ = (b3 << 6) | (b4 & 0x3F);
continue;
case 3:
m->base64_3 = b3;
case 2:
m->base64_2 = b2;
case 1:
m->base64_1 = b1;
m->base64chars = nbytes;
break;
default:
assert(0);
}
break; /* nbytes != 4 => EOL */
}
return out;
}
static unsigned char
hex(char c)
{
if(isdigit(c))
return c - '0';
if((c >= 'A') && (c <= 'F'))
return c - 'A' + 10;
if((c >= 'a') && (c <= 'f'))
return c - 'a' + 10;
cli_dbgmsg("Illegal hex character '%c'\n", c);
/*
* Some mails (notably some spam) break RFC2045 by failing to encode
* the '=' character
*/
return '=';
}
static unsigned char
base64(char c)
{
const unsigned char ret = base64Table[(unsigned int)(c & 0xFF)];
if(ret == 255) {
/*cli_dbgmsg("Illegal character <%c> in base64 encoding\n", c);*/
return 63;
}
return ret;
}
static unsigned char
uudecode(char c)
{
return c - ' ';
}
/*
* These are the only arguments we're interested in.
* Do 'fgrep messageFindArgument *.c' if you don't believe me!
* It's probably not good doing this since each time a new
* messageFindArgument is added I need to remember to look here,
* but it can save a lot of memory...
*/
static int
usefulArg(const char *arg)
{
if((strncasecmp(arg, "name", 4) != 0) &&
(strncasecmp(arg, "filename", 8) != 0) &&
(strncasecmp(arg, "boundary", 8) != 0) &&
(strncasecmp(arg, "protocol", 8) != 0) &&
(strncasecmp(arg, "id", 2) != 0) &&
(strncasecmp(arg, "number", 6) != 0) &&
(strncasecmp(arg, "total", 5) != 0) &&
(strncasecmp(arg, "type", 4) != 0)) {
cli_dbgmsg("Discarding unwanted argument '%s'\n", arg);
return 0;
}
return 1;
}
void
messageSetCTX(message *m, cli_ctx *ctx)
{
m->ctx = ctx;
}
int
messageContainsVirus(const message *m)
{
return m->isInfected ? TRUE : FALSE;
}
/*
* We've run out of memory. Try to recover some by
* deduping the message
*
* FIXME: this can take a long time. The real solution is for system admins
* to refrain from setting ulimits too low, then this routine won't be
* called
*/
static void
messageDedup(message *m)
{
const text *t1;
size_t saved = 0;
cli_dbgmsg("messageDedup\n");
t1 = m->dedupedThisFar ? m->dedupedThisFar : m->body_first;
for(t1 = m->body_first; t1; t1 = t1->t_next) {
const char *d1;
text *t2;
line_t *l1;
unsigned int r1;
if(saved >= 100*1000)
break; /* that's enough */
l1 = t1->t_line;
if(l1 == NULL)
continue;
d1 = lineGetData(l1);
if(strlen(d1) < 8)
continue; /* wouldn't recover many bytes */
r1 = (unsigned int)lineGetRefCount(l1);
if(r1 == 255)
continue;
/*
* We don't want to foul up any pointers
*/
if(t1 == m->encoding)
continue;
if(t1 == m->bounce)
continue;
if(t1 == m->binhex)
continue;
if(t1 == m->yenc)
continue;
for(t2 = t1->t_next; t2; t2 = t2->t_next) {
const char *d2;
line_t *l2 = t2->t_line;
if(l2 == NULL)
continue;
d2 = lineGetData(l2);
if(d1 == d2)
/* already linked */
continue;
if(strcmp(d1, d2) == 0) {
if(lineUnlink(l2) == NULL)
saved += strlen(d1) + 1;
t2->t_line = lineLink(l1);
if(t2->t_line == NULL) {
cli_errmsg("messageDedup: out of memory\n");
return;
}
if(++r1 == 255)
break;
}
}
}
cli_dbgmsg("messageDedup reclaimed %lu bytes\n", (unsigned long)saved);
m->dedupedThisFar = t1;
}
/*
* Handle RFC2231 encoding. Returns a malloc'd buffer that the caller must
* free, or NULL on error.
*
* TODO: Currently only handles paragraph 4 of RFC2231 e.g.
* protocol*=ansi-x3.4-1968''application%2Fpgp-signature;
*/
static char *
rfc2231(const char *in)
{
const char *ptr;
char *ret, *out;
enum { LANGUAGE, CHARSET, CONTENTS } field;
if(strstr(in, "*0*=") != NULL) {
char *p;
/* Don't handle continuations, decode what we can */
p = ret = cli_malloc(strlen(in) + 16);
if(ret == NULL) {
cli_errmsg("rfc2331: out of memory, unable to proceed\n");
return NULL;
}
do {
switch(*in) {
default:
*p++ = *in++;
continue;
case '*':
do
in++;
while((*in != '*') && *in);
if(*in) {
in++;
continue;
}
*p = '\0';
break;
case '=':
/*strcpy(p, in);*/
strcpy(p, "=rfc2231failure");
break;
}
break;
} while(*in);
cli_dbgmsg("RFC2231 parameter continuations are not yet handled, returning \"%s\"\n",
ret);
return ret;
}
ptr = strstr(in, "*0=");
if(ptr != NULL)
/*
* Parameter continuation, with no continuation
* Thunderbird 1.5 (and possibly other versions) does this
*/
field = CONTENTS;
else {
ptr = strstr(in, "*=");
field = LANGUAGE;
}
if(ptr == NULL) { /* quick return */
out = ret = cli_strdup(in);
while(*out)
*out++ &= 0x7F;
return ret;
}
cli_dbgmsg("rfc2231 '%s'\n", in);
ret = cli_malloc(strlen(in) + 1);
if(ret == NULL) {
cli_errmsg("rfc2331: out of memory for ret\n");
return NULL;
}
/*
* memcpy(out, in, (ptr - in));
* out = &out[ptr - in];
* in = ptr;
*/
out = ret;
while(in != ptr)
*out++ = *in++;
*out++ = '=';
while(*ptr++ != '=')
;
/*
* We don't do anything with the language and character set, just skip
* over them!
*/
while(*ptr) {
switch(field) {
case LANGUAGE:
if(*ptr == '\'')
field = CHARSET;
break;
case CHARSET:
if(*ptr == '\'')
field = CONTENTS;
break;
case CONTENTS:
if(*ptr == '%') {
unsigned char byte;
if((*++ptr == '\0') || (*ptr == '\n'))
break;
byte = hex(*ptr);
if((*++ptr == '\0') || (*ptr == '\n')) {
*out++ = byte;
break;
}
byte <<= 4;
byte += hex(*ptr);
*out++ = byte;
} else
*out++ = *ptr;
}
if(*ptr++ == '\0')
/*
* Incorrect message that has just one character after
* a '%'.
* FIXME: stash something in out that would, for example
* treat %2 as %02, assuming field == CONTENTS
*/
break;
}
if(field != CONTENTS) {
free(ret);
cli_dbgmsg("Invalid RFC2231 header: '%s'\n", in);
return cli_strdup("");
}
*out = '\0';
cli_dbgmsg("rfc2231 returns '%s'\n", ret);
return ret;
}
/*
* common/simil:
* From Computing Magazine 20/8/92
* Returns %ge number from 0 to 100 - how similar are 2 strings?
* 100 for exact match, < for error
*/
struct pstr_list { /* internal stack */
char *d1;
struct pstr_list *next;
};
#define OUT_OF_MEMORY (-2)
#define FAILURE (-3)
#define SUCCESS (-4)
#define ARRAY_OVERFLOW (-5)
typedef struct pstr_list ELEMENT1;
typedef ELEMENT1 *LINK1;
static int push(LINK1 *top, const char *string);
static int pop(LINK1 *top, char *buffer);
static unsigned int compare(char *ls1, char **rs1, char *ls2, char **rs2);
#define MAX_PATTERN_SIZ 50 /* maximum string lengths */
static int
simil(const char *str1, const char *str2)
{
LINK1 top = NULL;
unsigned int score = 0;
size_t common, total;
size_t len1, len2;
char *rs1 = NULL, *rs2 = NULL;
char *s1, *s2;
char ls1[MAX_PATTERN_SIZ], ls2[MAX_PATTERN_SIZ];
if(strcasecmp(str1, str2) == 0)
return 100;
if((s1 = cli_strdup(str1)) == NULL)
return OUT_OF_MEMORY;
if((s2 = cli_strdup(str2)) == NULL) {
free(s1);
return OUT_OF_MEMORY;
}
if(((total = strstrip(s1)) > MAX_PATTERN_SIZ - 1) || ((len2 = strstrip(s2)) > MAX_PATTERN_SIZ - 1)) {
free(s1);
free(s2);
return ARRAY_OVERFLOW;
}
total += len2;
if((push(&top, s1) == OUT_OF_MEMORY) ||
(push(&top, s2) == OUT_OF_MEMORY)) {
free(s1);
free(s2);
return OUT_OF_MEMORY;
}
while(pop(&top, ls2) == SUCCESS) {
pop(&top, ls1);
common = compare(ls1, &rs1, ls2, &rs2);
if(common > 0) {
score += (unsigned int)common;
len1 = strlen(ls1);
len2 = strlen(ls2);
if((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1))
if((push(&top, ls1) == OUT_OF_MEMORY) || (push(&top, ls2) == OUT_OF_MEMORY)) {
free(s1);
free(s2);
return OUT_OF_MEMORY;
}
len1 = strlen(rs1);
len2 = strlen(rs2);
if((len1 > 1 && len2 >= 1) || (len2 > 1 && len1 >= 1))
if((push(&top, rs1) == OUT_OF_MEMORY) || (push(&top, rs2) == OUT_OF_MEMORY)) {
free(s1);
free(s2);
return OUT_OF_MEMORY;
}
}
}
free(s1);
free(s2);
return (total > 0) ? ((score * 200) / total) : 0;
}
static unsigned int
compare(char *ls1, char **rs1, char *ls2, char **rs2)
{
unsigned int common, maxchars = 0;
bool some_similarity = FALSE;
char *s1, *s2;
char *maxs1 = NULL, *maxs2 = NULL, *maxe1 = NULL, *maxe2 = NULL;
char *cs1, *cs2, *start1, *end1, *end2;
end1 = ls1 + strlen(ls1);
end2 = ls2 + strlen(ls2);
start1 = ls1;
for(;;) {
s1 = start1;
s2 = ls2;
if(s1 < end1) {
while(s1 < end1 && s2 < end2) {
if(tolower(*s1) == tolower(*s2)) {
some_similarity = TRUE;
cs1 = s1;
cs2 = s2;
common = 0;
do
if(s1 == end1 || s2 == end2)
break;
else {
s1++;
s2++;
common++;
}
while(tolower(*s1) == tolower(*s2));
if(common > maxchars) {
unsigned int diff = common - maxchars;
maxchars = common;
maxs1 = cs1;
maxs2 = cs2;
maxe1 = s1;
maxe2 = s2;
end1 -= diff;
end2 -= diff;
} else
s1 -= common;
} else
s2++;
}
start1++;
} else
break;
}
if(some_similarity) {
*maxs1 = '\0';
*maxs2 = '\0';
*rs1 = maxe1;
*rs2 = maxe2;
}
return maxchars;
}
static int
push(LINK1 *top, const char *string)
{
LINK1 element;
if((element = (LINK1)cli_malloc(sizeof(ELEMENT1))) == NULL)
return OUT_OF_MEMORY;
if((element->d1 = cli_strdup(string)) == NULL) {
free (element);
return OUT_OF_MEMORY;
}
element->next = *top;
*top = element;
return SUCCESS;
}
static int
pop(LINK1 *top, char *buffer)
{
LINK1 t1;
if((t1 = *top) != NULL) {
(void)strcpy(buffer, t1->d1);
*top = t1->next;
free(t1->d1);
free((char *)t1);
return SUCCESS;
}
return FAILURE;
}
/*
* Have we found a line that is a start of a uuencoded file (see uuencode(5))?
*/
int
isuuencodebegin(const char *line)
{
if(line[0] != 'b') /* quick check */
return 0;
if(strlen(line) < 10)
return 0;
return (strncasecmp(line, "begin ", 6) == 0) &&
isdigit(line[6]) && isdigit(line[7]) &&
isdigit(line[8]) && (line[9] == ' ');
}
#if HAVE_JSON
json_object *messageGetJObj(message *m)
{
assert(m != NULL);
if(m->jobj == NULL)
m->jobj = cli_jsonobj(NULL, NULL);
return m->jobj;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3186_0 |
crossvul-cpp_data_good_215_0 | /*
* MOV, 3GP, MP4 muxer
* Copyright (c) 2003 Thomas Raivio
* Copyright (c) 2004 Gildas Bazin <gbazin at videolan dot org>
* Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com>
*
* 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 <stdint.h>
#include <inttypes.h>
#include "movenc.h"
#include "avformat.h"
#include "avio_internal.h"
#include "riff.h"
#include "avio.h"
#include "isom.h"
#include "avc.h"
#include "libavcodec/ac3_parser_internal.h"
#include "libavcodec/dnxhddata.h"
#include "libavcodec/flac.h"
#include "libavcodec/get_bits.h"
#include "libavcodec/internal.h"
#include "libavcodec/put_bits.h"
#include "libavcodec/vc1_common.h"
#include "libavcodec/raw.h"
#include "internal.h"
#include "libavutil/avstring.h"
#include "libavutil/intfloat.h"
#include "libavutil/mathematics.h"
#include "libavutil/libm.h"
#include "libavutil/opt.h"
#include "libavutil/dict.h"
#include "libavutil/pixdesc.h"
#include "libavutil/stereo3d.h"
#include "libavutil/timecode.h"
#include "libavutil/color_utils.h"
#include "hevc.h"
#include "rtpenc.h"
#include "mov_chan.h"
#include "vpcc.h"
static const AVOption options[] = {
{ "movflags", "MOV muxer flags", offsetof(MOVMuxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "rtphint", "Add RTP hint tracks", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_RTP_HINT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "moov_size", "maximum moov size so it can be placed at the begin", offsetof(MOVMuxContext, reserved_moov_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, 0 },
{ "empty_moov", "Make the initial moov atom empty", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_EMPTY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_keyframe", "Fragment at video keyframes", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_KEYFRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_every_frame", "Fragment at every frame", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_EVERY_FRAME}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "separate_moof", "Write separate moof/mdat atoms for each track", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SEPARATE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_custom", "Flush fragments on caller requests", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_CUSTOM}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "isml", "Create a live smooth streaming feed (for pushing to a publishing point)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_ISML}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "faststart", "Run a second pass to put the index (moov atom) at the beginning of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FASTSTART}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "omit_tfhd_offset", "Omit the base data offset in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_OMIT_TFHD_OFFSET}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "disable_chpl", "Disable Nero chapter atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DISABLE_CHPL}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "default_base_moof", "Set the default-base-is-moof flag in tfhd atoms", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DEFAULT_BASE_MOOF}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "dash", "Write DASH compatible fragmented MP4", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DASH}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "frag_discont", "Signal that the next fragment is discontinuous from earlier ones", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_FRAG_DISCONT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "delay_moov", "Delay writing the initial moov until the first fragment is cut, or until the first fragment flush", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_DELAY_MOOV}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "global_sidx", "Write a global sidx index at the start of the file", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_GLOBAL_SIDX}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "write_colr", "Write colr atom (Experimental, may be renamed or changed, do not use from scripts)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_COLR}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "write_gama", "Write deprecated gama atom", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_WRITE_GAMA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "use_metadata_tags", "Use mdta atom for metadata.", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_USE_MDTA}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "skip_trailer", "Skip writing the mfra/tfra/mfro trailer for fragmented files", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_SKIP_TRAILER}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
{ "negative_cts_offsets", "Use negative CTS offsets (reducing the need for edit lists)", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "movflags" },
FF_RTP_FLAG_OPTS(MOVMuxContext, rtp_flags),
{ "skip_iods", "Skip writing iods atom.", offsetof(MOVMuxContext, iods_skip), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "iods_audio_profile", "iods audio profile atom.", offsetof(MOVMuxContext, iods_audio_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
{ "iods_video_profile", "iods video profile atom.", offsetof(MOVMuxContext, iods_video_profile), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 255, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_duration", "Maximum fragment duration", offsetof(MOVMuxContext, max_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "min_frag_duration", "Minimum fragment duration", offsetof(MOVMuxContext, min_fragment_duration), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_size", "Maximum fragment size", offsetof(MOVMuxContext, max_fragment_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "ism_lookahead", "Number of lookahead entries for ISM files", offsetof(MOVMuxContext, ism_lookahead), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "video_track_timescale", "set timescale of all video tracks", offsetof(MOVMuxContext, video_track_timescale), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "brand", "Override major brand", offsetof(MOVMuxContext, major_brand), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "use_editlist", "use edit list", offsetof(MOVMuxContext, use_editlist), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "fragment_index", "Fragment number of the next fragment", offsetof(MOVMuxContext, fragments), AV_OPT_TYPE_INT, {.i64 = 1}, 1, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM},
{ "mov_gamma", "gamma value for gama atom", offsetof(MOVMuxContext, gamma), AV_OPT_TYPE_FLOAT, {.dbl = 0.0 }, 0.0, 10, AV_OPT_FLAG_ENCODING_PARAM},
{ "frag_interleave", "Interleave samples within fragments (max number of consecutive samples, lower is tighter interleaving, but with more overhead)", offsetof(MOVMuxContext, frag_interleave), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_scheme", "Configures the encryption scheme, allowed values are none, cenc-aes-ctr", offsetof(MOVMuxContext, encryption_scheme_str), AV_OPT_TYPE_STRING, {.str = NULL}, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_key", "The media encryption key (hex)", offsetof(MOVMuxContext, encryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "encryption_kid", "The media encryption key identifier (hex)", offsetof(MOVMuxContext, encryption_kid), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_ENCODING_PARAM },
{ "use_stream_ids_as_track_ids", "use stream ids as track ids", offsetof(MOVMuxContext, use_stream_ids_as_track_ids), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "write_tmcd", "force or disable writing tmcd", offsetof(MOVMuxContext, write_tmcd), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ "write_prft", "Write producer reference time box with specified time source", offsetof(MOVMuxContext, write_prft), AV_OPT_TYPE_INT, {.i64 = MOV_PRFT_NONE}, 0, MOV_PRFT_NB-1, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "wallclock", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_WALLCLOCK}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "pts", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = MOV_PRFT_SRC_PTS}, 0, 0, AV_OPT_FLAG_ENCODING_PARAM, "prft"},
{ "empty_hdlr_name", "write zero-length name string in hdlr atoms within mdia and minf atoms", offsetof(MOVMuxContext, empty_hdlr_name), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM},
{ NULL },
};
#define MOV_CLASS(flavor)\
static const AVClass flavor ## _muxer_class = {\
.class_name = #flavor " muxer",\
.item_name = av_default_item_name,\
.option = options,\
.version = LIBAVUTIL_VERSION_INT,\
};
static int get_moov_size(AVFormatContext *s);
static int utf8len(const uint8_t *b)
{
int len = 0;
int val;
while (*b) {
GET_UTF8(val, *b++, return -1;)
len++;
}
return len;
}
//FIXME support 64 bit variant with wide placeholders
static int64_t update_size(AVIOContext *pb, int64_t pos)
{
int64_t curpos = avio_tell(pb);
avio_seek(pb, pos, SEEK_SET);
avio_wb32(pb, curpos - pos); /* rewrite size */
avio_seek(pb, curpos, SEEK_SET);
return curpos - pos;
}
static int co64_required(const MOVTrack *track)
{
if (track->entry > 0 && track->cluster[track->entry - 1].pos + track->data_offset > UINT32_MAX)
return 1;
return 0;
}
static int is_cover_image(const AVStream *st)
{
/* Eg. AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS
* is encoded as sparse video track */
return st && st->disposition == AV_DISPOSITION_ATTACHED_PIC;
}
static int rtp_hinting_needed(const AVStream *st)
{
/* Add hint tracks for each real audio and video stream */
if (is_cover_image(st))
return 0;
return st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ||
st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
}
/* Chunk offset atom */
static int mov_write_stco_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
int mode64 = co64_required(track); // use 32 bit size variant if possible
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
if (mode64)
ffio_wfourcc(pb, "co64");
else
ffio_wfourcc(pb, "stco");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, track->chunkCount); /* entry count */
for (i = 0; i < track->entry; i++) {
if (!track->cluster[i].chunkNum)
continue;
if (mode64 == 1)
avio_wb64(pb, track->cluster[i].pos + track->data_offset);
else
avio_wb32(pb, track->cluster[i].pos + track->data_offset);
}
return update_size(pb, pos);
}
/* Sample size atom */
static int mov_write_stsz_tag(AVIOContext *pb, MOVTrack *track)
{
int equalChunks = 1;
int i, j, entries = 0, tst = -1, oldtst = -1;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsz");
avio_wb32(pb, 0); /* version & flags */
for (i = 0; i < track->entry; i++) {
tst = track->cluster[i].size / track->cluster[i].entries;
if (oldtst != -1 && tst != oldtst)
equalChunks = 0;
oldtst = tst;
entries += track->cluster[i].entries;
}
if (equalChunks && track->entry) {
int sSize = track->entry ? track->cluster[0].size / track->cluster[0].entries : 0;
sSize = FFMAX(1, sSize); // adpcm mono case could make sSize == 0
avio_wb32(pb, sSize); // sample size
avio_wb32(pb, entries); // sample count
} else {
avio_wb32(pb, 0); // sample size
avio_wb32(pb, entries); // sample count
for (i = 0; i < track->entry; i++) {
for (j = 0; j < track->cluster[i].entries; j++) {
avio_wb32(pb, track->cluster[i].size /
track->cluster[i].entries);
}
}
}
return update_size(pb, pos);
}
/* Sample to chunk atom */
static int mov_write_stsc_tag(AVIOContext *pb, MOVTrack *track)
{
int index = 0, oldval = -1, i;
int64_t entryPos, curpos;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsc");
avio_wb32(pb, 0); // version & flags
entryPos = avio_tell(pb);
avio_wb32(pb, track->chunkCount); // entry count
for (i = 0; i < track->entry; i++) {
if (oldval != track->cluster[i].samples_in_chunk && track->cluster[i].chunkNum) {
avio_wb32(pb, track->cluster[i].chunkNum); // first chunk
avio_wb32(pb, track->cluster[i].samples_in_chunk); // samples per chunk
avio_wb32(pb, 0x1); // sample description index
oldval = track->cluster[i].samples_in_chunk;
index++;
}
}
curpos = avio_tell(pb);
avio_seek(pb, entryPos, SEEK_SET);
avio_wb32(pb, index); // rewrite size
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
/* Sync sample atom */
static int mov_write_stss_tag(AVIOContext *pb, MOVTrack *track, uint32_t flag)
{
int64_t curpos, entryPos;
int i, index = 0;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, flag == MOV_SYNC_SAMPLE ? "stss" : "stps");
avio_wb32(pb, 0); // version & flags
entryPos = avio_tell(pb);
avio_wb32(pb, track->entry); // entry count
for (i = 0; i < track->entry; i++) {
if (track->cluster[i].flags & flag) {
avio_wb32(pb, i + 1);
index++;
}
}
curpos = avio_tell(pb);
avio_seek(pb, entryPos, SEEK_SET);
avio_wb32(pb, index); // rewrite size
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
/* Sample dependency atom */
static int mov_write_sdtp_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
uint8_t leading, dependent, reference, redundancy;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "sdtp");
avio_wb32(pb, 0); // version & flags
for (i = 0; i < track->entry; i++) {
dependent = MOV_SAMPLE_DEPENDENCY_YES;
leading = reference = redundancy = MOV_SAMPLE_DEPENDENCY_UNKNOWN;
if (track->cluster[i].flags & MOV_DISPOSABLE_SAMPLE) {
reference = MOV_SAMPLE_DEPENDENCY_NO;
}
if (track->cluster[i].flags & MOV_SYNC_SAMPLE) {
dependent = MOV_SAMPLE_DEPENDENCY_NO;
}
avio_w8(pb, (leading << 6) | (dependent << 4) |
(reference << 2) | redundancy);
}
return update_size(pb, pos);
}
static int mov_write_amr_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 0x11); /* size */
if (track->mode == MODE_MOV) ffio_wfourcc(pb, "samr");
else ffio_wfourcc(pb, "damr");
ffio_wfourcc(pb, "FFMP");
avio_w8(pb, 0); /* decoder version */
avio_wb16(pb, 0x81FF); /* Mode set (all modes for AMR_NB) */
avio_w8(pb, 0x00); /* Mode change period (no restriction) */
avio_w8(pb, 0x01); /* Frames per sample */
return 0x11;
}
static int mov_write_ac3_tag(AVIOContext *pb, MOVTrack *track)
{
GetBitContext gbc;
PutBitContext pbc;
uint8_t buf[3];
int fscod, bsid, bsmod, acmod, lfeon, frmsizecod;
if (track->vos_len < 7)
return -1;
avio_wb32(pb, 11);
ffio_wfourcc(pb, "dac3");
init_get_bits(&gbc, track->vos_data + 4, (track->vos_len - 4) * 8);
fscod = get_bits(&gbc, 2);
frmsizecod = get_bits(&gbc, 6);
bsid = get_bits(&gbc, 5);
bsmod = get_bits(&gbc, 3);
acmod = get_bits(&gbc, 3);
if (acmod == 2) {
skip_bits(&gbc, 2); // dsurmod
} else {
if ((acmod & 1) && acmod != 1)
skip_bits(&gbc, 2); // cmixlev
if (acmod & 4)
skip_bits(&gbc, 2); // surmixlev
}
lfeon = get_bits1(&gbc);
init_put_bits(&pbc, buf, sizeof(buf));
put_bits(&pbc, 2, fscod);
put_bits(&pbc, 5, bsid);
put_bits(&pbc, 3, bsmod);
put_bits(&pbc, 3, acmod);
put_bits(&pbc, 1, lfeon);
put_bits(&pbc, 5, frmsizecod >> 1); // bit_rate_code
put_bits(&pbc, 5, 0); // reserved
flush_put_bits(&pbc);
avio_write(pb, buf, sizeof(buf));
return 11;
}
struct eac3_info {
AVPacket pkt;
uint8_t ec3_done;
uint8_t num_blocks;
/* Layout of the EC3SpecificBox */
/* maximum bitrate */
uint16_t data_rate;
/* number of independent substreams */
uint8_t num_ind_sub;
struct {
/* sample rate code (see ff_ac3_sample_rate_tab) 2 bits */
uint8_t fscod;
/* bit stream identification 5 bits */
uint8_t bsid;
/* one bit reserved */
/* audio service mixing (not supported yet) 1 bit */
/* bit stream mode 3 bits */
uint8_t bsmod;
/* audio coding mode 3 bits */
uint8_t acmod;
/* sub woofer on 1 bit */
uint8_t lfeon;
/* 3 bits reserved */
/* number of dependent substreams associated with this substream 4 bits */
uint8_t num_dep_sub;
/* channel locations of the dependent substream(s), if any, 9 bits */
uint16_t chan_loc;
/* if there is no dependent substream, then one bit reserved instead */
} substream[1]; /* TODO: support 8 independent substreams */
};
#if CONFIG_AC3_PARSER
static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
//info->num_ind_sub++;
avpriv_request_sample(mov->fc, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
} else {
if (hdr->substreamid != 0) {
avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
#endif
static int mov_write_eac3_tag(AVIOContext *pb, MOVTrack *track)
{
PutBitContext pbc;
uint8_t *buf;
struct eac3_info *info;
int size, i;
if (!track->eac3_priv)
return AVERROR(EINVAL);
info = track->eac3_priv;
size = 2 + 4 * (info->num_ind_sub + 1);
buf = av_malloc(size);
if (!buf) {
size = AVERROR(ENOMEM);
goto end;
}
init_put_bits(&pbc, buf, size);
put_bits(&pbc, 13, info->data_rate);
put_bits(&pbc, 3, info->num_ind_sub);
for (i = 0; i <= info->num_ind_sub; i++) {
put_bits(&pbc, 2, info->substream[i].fscod);
put_bits(&pbc, 5, info->substream[i].bsid);
put_bits(&pbc, 1, 0); /* reserved */
put_bits(&pbc, 1, 0); /* asvc */
put_bits(&pbc, 3, info->substream[i].bsmod);
put_bits(&pbc, 3, info->substream[i].acmod);
put_bits(&pbc, 1, info->substream[i].lfeon);
put_bits(&pbc, 5, 0); /* reserved */
put_bits(&pbc, 4, info->substream[i].num_dep_sub);
if (!info->substream[i].num_dep_sub) {
put_bits(&pbc, 1, 0); /* reserved */
size--;
} else {
put_bits(&pbc, 9, info->substream[i].chan_loc);
}
}
flush_put_bits(&pbc);
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "dec3");
avio_write(pb, buf, size);
av_free(buf);
end:
av_packet_unref(&info->pkt);
av_freep(&track->eac3_priv);
return size;
}
/**
* This function writes extradata "as is".
* Extradata must be formatted like a valid atom (with size and tag).
*/
static int mov_write_extradata_tag(AVIOContext *pb, MOVTrack *track)
{
avio_write(pb, track->par->extradata, track->par->extradata_size);
return track->par->extradata_size;
}
static int mov_write_enda_tag(AVIOContext *pb)
{
avio_wb32(pb, 10);
ffio_wfourcc(pb, "enda");
avio_wb16(pb, 1); /* little endian */
return 10;
}
static int mov_write_enda_tag_be(AVIOContext *pb)
{
avio_wb32(pb, 10);
ffio_wfourcc(pb, "enda");
avio_wb16(pb, 0); /* big endian */
return 10;
}
static void put_descr(AVIOContext *pb, int tag, unsigned int size)
{
int i = 3;
avio_w8(pb, tag);
for (; i > 0; i--)
avio_w8(pb, (size >> (7 * i)) | 0x80);
avio_w8(pb, size & 0x7F);
}
static unsigned compute_avg_bitrate(MOVTrack *track)
{
uint64_t size = 0;
int i;
if (!track->track_duration)
return 0;
for (i = 0; i < track->entry; i++)
size += track->cluster[i].size;
return size * 8 * track->timescale / track->track_duration;
}
static int mov_write_esds_tag(AVIOContext *pb, MOVTrack *track) // Basic
{
AVCPBProperties *props;
int64_t pos = avio_tell(pb);
int decoder_specific_info_len = track->vos_len ? 5 + track->vos_len : 0;
unsigned avg_bitrate;
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "esds");
avio_wb32(pb, 0); // Version
// ES descriptor
put_descr(pb, 0x03, 3 + 5+13 + decoder_specific_info_len + 5+1);
avio_wb16(pb, track->track_id);
avio_w8(pb, 0x00); // flags (= no flags)
// DecoderConfig descriptor
put_descr(pb, 0x04, 13 + decoder_specific_info_len);
// Object type indication
if ((track->par->codec_id == AV_CODEC_ID_MP2 ||
track->par->codec_id == AV_CODEC_ID_MP3) &&
track->par->sample_rate > 24000)
avio_w8(pb, 0x6B); // 11172-3
else
avio_w8(pb, ff_codec_get_tag(ff_mp4_obj_type, track->par->codec_id));
// the following fields is made of 6 bits to identify the streamtype (4 for video, 5 for audio)
// plus 1 bit to indicate upstream and 1 bit set to 1 (reserved)
if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
avio_w8(pb, (0x38 << 2) | 1); // flags (= NeroSubpicStream)
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
avio_w8(pb, 0x15); // flags (= Audiostream)
else
avio_w8(pb, 0x11); // flags (= Visualstream)
props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES,
NULL);
avio_wb24(pb, props ? props->buffer_size / 8 : 0); // Buffersize DB
avg_bitrate = compute_avg_bitrate(track);
avio_wb32(pb, props ? FFMAX3(props->max_bitrate, props->avg_bitrate, avg_bitrate) : FFMAX(track->par->bit_rate, avg_bitrate)); // maxbitrate (FIXME should be max rate in any 1 sec window)
avio_wb32(pb, avg_bitrate);
if (track->vos_len) {
// DecoderSpecific info descriptor
put_descr(pb, 0x05, track->vos_len);
avio_write(pb, track->vos_data, track->vos_len);
}
// SL descriptor
put_descr(pb, 0x06, 1);
avio_w8(pb, 0x02);
return update_size(pb, pos);
}
static int mov_pcm_le_gt16(enum AVCodecID codec_id)
{
return codec_id == AV_CODEC_ID_PCM_S24LE ||
codec_id == AV_CODEC_ID_PCM_S32LE ||
codec_id == AV_CODEC_ID_PCM_F32LE ||
codec_id == AV_CODEC_ID_PCM_F64LE;
}
static int mov_pcm_be_gt16(enum AVCodecID codec_id)
{
return codec_id == AV_CODEC_ID_PCM_S24BE ||
codec_id == AV_CODEC_ID_PCM_S32BE ||
codec_id == AV_CODEC_ID_PCM_F32BE ||
codec_id == AV_CODEC_ID_PCM_F64BE;
}
static int mov_write_ms_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int ret;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
avio_wl32(pb, track->tag); // store it byteswapped
track->par->codec_tag = av_bswap16(track->tag >> 16);
if ((ret = ff_put_wav_header(s, pb, track->par, 0)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_wfex_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int ret;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "wfex");
if ((ret = ff_put_wav_header(s, pb, track->st->codecpar, FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_dfla_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "dfLa");
avio_w8(pb, 0); /* version */
avio_wb24(pb, 0); /* flags */
/* Expect the encoder to pass a METADATA_BLOCK_TYPE_STREAMINFO. */
if (track->par->extradata_size != FLAC_STREAMINFO_SIZE)
return AVERROR_INVALIDDATA;
/* TODO: Write other METADATA_BLOCK_TYPEs if the encoder makes them available. */
avio_w8(pb, 1 << 7 | FLAC_METADATA_TYPE_STREAMINFO); /* LastMetadataBlockFlag << 7 | BlockType */
avio_wb24(pb, track->par->extradata_size); /* Length */
avio_write(pb, track->par->extradata, track->par->extradata_size); /* BlockData[Length] */
return update_size(pb, pos);
}
static int mov_write_dops_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "dOps");
avio_w8(pb, 0); /* Version */
if (track->par->extradata_size < 19) {
av_log(pb, AV_LOG_ERROR, "invalid extradata size\n");
return AVERROR_INVALIDDATA;
}
/* extradata contains an Ogg OpusHead, other than byte-ordering and
OpusHead's preceeding magic/version, OpusSpecificBox is currently
identical. */
avio_w8(pb, AV_RB8(track->par->extradata + 9)); /* OuputChannelCount */
avio_wb16(pb, AV_RL16(track->par->extradata + 10)); /* PreSkip */
avio_wb32(pb, AV_RL32(track->par->extradata + 12)); /* InputSampleRate */
avio_wb16(pb, AV_RL16(track->par->extradata + 16)); /* OutputGain */
/* Write the rest of the header out without byte-swapping. */
avio_write(pb, track->par->extradata + 18, track->par->extradata_size - 18);
return update_size(pb, pos);
}
static int mov_write_chan_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
uint32_t layout_tag, bitmap;
int64_t pos = avio_tell(pb);
layout_tag = ff_mov_get_channel_layout_tag(track->par->codec_id,
track->par->channel_layout,
&bitmap);
if (!layout_tag) {
av_log(s, AV_LOG_WARNING, "not writing 'chan' tag due to "
"lack of channel information\n");
return 0;
}
if (track->multichannel_as_mono)
return 0;
avio_wb32(pb, 0); // Size
ffio_wfourcc(pb, "chan"); // Type
avio_w8(pb, 0); // Version
avio_wb24(pb, 0); // Flags
avio_wb32(pb, layout_tag); // mChannelLayoutTag
avio_wb32(pb, bitmap); // mChannelBitmap
avio_wb32(pb, 0); // mNumberChannelDescriptions
return update_size(pb, pos);
}
static int mov_write_wave_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "wave");
if (track->par->codec_id != AV_CODEC_ID_QDM2) {
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "frma");
avio_wl32(pb, track->tag);
}
if (track->par->codec_id == AV_CODEC_ID_AAC) {
/* useless atom needed by mplayer, ipod, not needed by quicktime */
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "mp4a");
avio_wb32(pb, 0);
mov_write_esds_tag(pb, track);
} else if (mov_pcm_le_gt16(track->par->codec_id)) {
mov_write_enda_tag(pb);
} else if (mov_pcm_be_gt16(track->par->codec_id)) {
mov_write_enda_tag_be(pb);
} else if (track->par->codec_id == AV_CODEC_ID_AMR_NB) {
mov_write_amr_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_AC3) {
mov_write_ac3_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_EAC3) {
mov_write_eac3_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_ALAC ||
track->par->codec_id == AV_CODEC_ID_QDM2) {
mov_write_extradata_tag(pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
mov_write_ms_tag(s, pb, track);
}
avio_wb32(pb, 8); /* size */
avio_wb32(pb, 0); /* null tag */
return update_size(pb, pos);
}
static int mov_write_dvc1_structs(MOVTrack *track, uint8_t *buf)
{
uint8_t *unescaped;
const uint8_t *start, *next, *end = track->vos_data + track->vos_len;
int unescaped_size, seq_found = 0;
int level = 0, interlace = 0;
int packet_seq = track->vc1_info.packet_seq;
int packet_entry = track->vc1_info.packet_entry;
int slices = track->vc1_info.slices;
PutBitContext pbc;
if (track->start_dts == AV_NOPTS_VALUE) {
/* No packets written yet, vc1_info isn't authoritative yet. */
/* Assume inline sequence and entry headers. */
packet_seq = packet_entry = 1;
av_log(NULL, AV_LOG_WARNING,
"moov atom written before any packets, unable to write correct "
"dvc1 atom. Set the delay_moov flag to fix this.\n");
}
unescaped = av_mallocz(track->vos_len + AV_INPUT_BUFFER_PADDING_SIZE);
if (!unescaped)
return AVERROR(ENOMEM);
start = find_next_marker(track->vos_data, end);
for (next = start; next < end; start = next) {
GetBitContext gb;
int size;
next = find_next_marker(start + 4, end);
size = next - start - 4;
if (size <= 0)
continue;
unescaped_size = vc1_unescape_buffer(start + 4, size, unescaped);
init_get_bits(&gb, unescaped, 8 * unescaped_size);
if (AV_RB32(start) == VC1_CODE_SEQHDR) {
int profile = get_bits(&gb, 2);
if (profile != PROFILE_ADVANCED) {
av_free(unescaped);
return AVERROR(ENOSYS);
}
seq_found = 1;
level = get_bits(&gb, 3);
/* chromaformat, frmrtq_postproc, bitrtq_postproc, postprocflag,
* width, height */
skip_bits_long(&gb, 2 + 3 + 5 + 1 + 2*12);
skip_bits(&gb, 1); /* broadcast */
interlace = get_bits1(&gb);
skip_bits(&gb, 4); /* tfcntrflag, finterpflag, reserved, psf */
}
}
if (!seq_found) {
av_free(unescaped);
return AVERROR(ENOSYS);
}
init_put_bits(&pbc, buf, 7);
/* VC1DecSpecStruc */
put_bits(&pbc, 4, 12); /* profile - advanced */
put_bits(&pbc, 3, level);
put_bits(&pbc, 1, 0); /* reserved */
/* VC1AdvDecSpecStruc */
put_bits(&pbc, 3, level);
put_bits(&pbc, 1, 0); /* cbr */
put_bits(&pbc, 6, 0); /* reserved */
put_bits(&pbc, 1, !interlace); /* no interlace */
put_bits(&pbc, 1, !packet_seq); /* no multiple seq */
put_bits(&pbc, 1, !packet_entry); /* no multiple entry */
put_bits(&pbc, 1, !slices); /* no slice code */
put_bits(&pbc, 1, 0); /* no bframe */
put_bits(&pbc, 1, 0); /* reserved */
/* framerate */
if (track->st->avg_frame_rate.num > 0 && track->st->avg_frame_rate.den > 0)
put_bits32(&pbc, track->st->avg_frame_rate.num / track->st->avg_frame_rate.den);
else
put_bits32(&pbc, 0xffffffff);
flush_put_bits(&pbc);
av_free(unescaped);
return 0;
}
static int mov_write_dvc1_tag(AVIOContext *pb, MOVTrack *track)
{
uint8_t buf[7] = { 0 };
int ret;
if ((ret = mov_write_dvc1_structs(track, buf)) < 0)
return ret;
avio_wb32(pb, track->vos_len + 8 + sizeof(buf));
ffio_wfourcc(pb, "dvc1");
avio_write(pb, buf, sizeof(buf));
avio_write(pb, track->vos_data, track->vos_len);
return 0;
}
static int mov_write_glbl_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, track->vos_len + 8);
ffio_wfourcc(pb, "glbl");
avio_write(pb, track->vos_data, track->vos_len);
return 8 + track->vos_len;
}
/**
* Compute flags for 'lpcm' tag.
* See CoreAudioTypes and AudioStreamBasicDescription at Apple.
*/
static int mov_get_lpcm_flags(enum AVCodecID codec_id)
{
switch (codec_id) {
case AV_CODEC_ID_PCM_F32BE:
case AV_CODEC_ID_PCM_F64BE:
return 11;
case AV_CODEC_ID_PCM_F32LE:
case AV_CODEC_ID_PCM_F64LE:
return 9;
case AV_CODEC_ID_PCM_U8:
return 10;
case AV_CODEC_ID_PCM_S16BE:
case AV_CODEC_ID_PCM_S24BE:
case AV_CODEC_ID_PCM_S32BE:
return 14;
case AV_CODEC_ID_PCM_S8:
case AV_CODEC_ID_PCM_S16LE:
case AV_CODEC_ID_PCM_S24LE:
case AV_CODEC_ID_PCM_S32LE:
return 12;
default:
return 0;
}
}
static int get_cluster_duration(MOVTrack *track, int cluster_idx)
{
int64_t next_dts;
if (cluster_idx >= track->entry)
return 0;
if (cluster_idx + 1 == track->entry)
next_dts = track->track_duration + track->start_dts;
else
next_dts = track->cluster[cluster_idx + 1].dts;
next_dts -= track->cluster[cluster_idx].dts;
av_assert0(next_dts >= 0);
av_assert0(next_dts <= INT_MAX);
return next_dts;
}
static int get_samples_per_packet(MOVTrack *track)
{
int i, first_duration;
// return track->par->frame_size;
/* use 1 for raw PCM */
if (!track->audio_vbr)
return 1;
/* check to see if duration is constant for all clusters */
if (!track->entry)
return 0;
first_duration = get_cluster_duration(track, 0);
for (i = 1; i < track->entry; i++) {
if (get_cluster_duration(track, i) != first_duration)
return 0;
}
return first_duration;
}
static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int version = 0;
uint32_t tag = track->tag;
if (track->mode == MODE_MOV) {
if (track->timescale > UINT16_MAX) {
if (mov_get_lpcm_flags(track->par->codec_id))
tag = AV_RL32("lpcm");
version = 2;
} else if (track->audio_vbr || mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id) ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2) {
version = 1;
}
}
avio_wb32(pb, 0); /* size */
if (mov->encryption_scheme != MOV_ENC_NONE) {
ffio_wfourcc(pb, "enca");
} else {
avio_wl32(pb, tag); // store it byteswapped
}
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index, XXX == 1 */
/* SoundDescription */
avio_wb16(pb, version); /* Version */
avio_wb16(pb, 0); /* Revision level */
avio_wb32(pb, 0); /* Reserved */
if (version == 2) {
avio_wb16(pb, 3);
avio_wb16(pb, 16);
avio_wb16(pb, 0xfffe);
avio_wb16(pb, 0);
avio_wb32(pb, 0x00010000);
avio_wb32(pb, 72);
avio_wb64(pb, av_double2int(track->par->sample_rate));
avio_wb32(pb, track->par->channels);
avio_wb32(pb, 0x7F000000);
avio_wb32(pb, av_get_bits_per_sample(track->par->codec_id));
avio_wb32(pb, mov_get_lpcm_flags(track->par->codec_id));
avio_wb32(pb, track->sample_size);
avio_wb32(pb, get_samples_per_packet(track));
} else {
if (track->mode == MODE_MOV) {
avio_wb16(pb, track->par->channels);
if (track->par->codec_id == AV_CODEC_ID_PCM_U8 ||
track->par->codec_id == AV_CODEC_ID_PCM_S8)
avio_wb16(pb, 8); /* bits per sample */
else if (track->par->codec_id == AV_CODEC_ID_ADPCM_G726)
avio_wb16(pb, track->par->bits_per_coded_sample);
else
avio_wb16(pb, 16);
avio_wb16(pb, track->audio_vbr ? -2 : 0); /* compression ID */
} else { /* reserved for mp4/3gp */
if (track->par->codec_id == AV_CODEC_ID_FLAC ||
track->par->codec_id == AV_CODEC_ID_OPUS) {
avio_wb16(pb, track->par->channels);
} else {
avio_wb16(pb, 2);
}
if (track->par->codec_id == AV_CODEC_ID_FLAC) {
avio_wb16(pb, track->par->bits_per_raw_sample);
} else {
avio_wb16(pb, 16);
}
avio_wb16(pb, 0);
}
avio_wb16(pb, 0); /* packet size (= 0) */
if (track->par->codec_id == AV_CODEC_ID_OPUS)
avio_wb16(pb, 48000);
else
avio_wb16(pb, track->par->sample_rate <= UINT16_MAX ?
track->par->sample_rate : 0);
avio_wb16(pb, 0); /* Reserved */
}
if (version == 1) { /* SoundDescription V1 extended info */
if (mov_pcm_le_gt16(track->par->codec_id) ||
mov_pcm_be_gt16(track->par->codec_id))
avio_wb32(pb, 1); /* must be 1 for uncompressed formats */
else
avio_wb32(pb, track->par->frame_size); /* Samples per packet */
avio_wb32(pb, track->sample_size / track->par->channels); /* Bytes per packet */
avio_wb32(pb, track->sample_size); /* Bytes per frame */
avio_wb32(pb, 2); /* Bytes per sample */
}
if (track->mode == MODE_MOV &&
(track->par->codec_id == AV_CODEC_ID_AAC ||
track->par->codec_id == AV_CODEC_ID_AC3 ||
track->par->codec_id == AV_CODEC_ID_EAC3 ||
track->par->codec_id == AV_CODEC_ID_AMR_NB ||
track->par->codec_id == AV_CODEC_ID_ALAC ||
track->par->codec_id == AV_CODEC_ID_ADPCM_MS ||
track->par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
track->par->codec_id == AV_CODEC_ID_QDM2 ||
(mov_pcm_le_gt16(track->par->codec_id) && version==1) ||
(mov_pcm_be_gt16(track->par->codec_id) && version==1)))
mov_write_wave_tag(s, pb, track);
else if (track->tag == MKTAG('m','p','4','a'))
mov_write_esds_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AMR_NB)
mov_write_amr_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_AC3)
mov_write_ac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_EAC3)
mov_write_eac3_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_ALAC)
mov_write_extradata_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_WMAPRO)
mov_write_wfex_tag(s, pb, track);
else if (track->par->codec_id == AV_CODEC_ID_FLAC)
mov_write_dfla_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_OPUS)
mov_write_dops_tag(pb, track);
else if (track->vos_len > 0)
mov_write_glbl_tag(pb, track);
if (track->mode == MODE_MOV && track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_chan_tag(s, pb, track);
if (mov->encryption_scheme != MOV_ENC_NONE) {
ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
}
return update_size(pb, pos);
}
static int mov_write_d263_tag(AVIOContext *pb)
{
avio_wb32(pb, 0xf); /* size */
ffio_wfourcc(pb, "d263");
ffio_wfourcc(pb, "FFMP");
avio_w8(pb, 0); /* decoder version */
/* FIXME use AVCodecContext level/profile, when encoder will set values */
avio_w8(pb, 0xa); /* level */
avio_w8(pb, 0); /* profile */
return 0xf;
}
static int mov_write_avcc_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "avcC");
ff_isom_write_avcc(pb, track->vos_data, track->vos_len);
return update_size(pb, pos);
}
static int mov_write_vpcc_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "vpcC");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0); /* flags */
ff_isom_write_vpcc(s, pb, track->par);
return update_size(pb, pos);
}
static int mov_write_hvcc_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "hvcC");
if (track->tag == MKTAG('h','v','c','1'))
ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 1);
else
ff_isom_write_hvcc(pb, track->vos_data, track->vos_len, 0);
return update_size(pb, pos);
}
/* also used by all avid codecs (dv, imx, meridien) and their variants */
static int mov_write_avid_tag(AVIOContext *pb, MOVTrack *track)
{
int i;
int interlaced;
int cid;
int display_width = track->par->width;
if (track->vos_data && track->vos_len > 0x29) {
if (ff_dnxhd_parse_header_prefix(track->vos_data) != 0) {
/* looks like a DNxHD bit stream */
interlaced = (track->vos_data[5] & 2);
cid = AV_RB32(track->vos_data + 0x28);
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream in vos_data\n");
return 0;
}
} else {
av_log(NULL, AV_LOG_WARNING, "Could not locate DNxHD bit stream, vos_data too small\n");
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "ACLR");
ffio_wfourcc(pb, "0001");
if (track->par->color_range == AVCOL_RANGE_MPEG || /* Legal range (16-235) */
track->par->color_range == AVCOL_RANGE_UNSPECIFIED) {
avio_wb32(pb, 1); /* Corresponds to 709 in official encoder */
} else { /* Full range (0-255) */
avio_wb32(pb, 2); /* Corresponds to RGB in official encoder */
}
avio_wb32(pb, 0); /* unknown */
if (track->tag == MKTAG('A','V','d','h')) {
avio_wb32(pb, 32);
ffio_wfourcc(pb, "ADHR");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid);
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 0); /* unknown */
return 0;
}
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "APRG");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 120); /* size */
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "ARES");
ffio_wfourcc(pb, "0001");
avio_wb32(pb, cid); /* dnxhd cid, some id ? */
if ( track->par->sample_aspect_ratio.num > 0
&& track->par->sample_aspect_ratio.den > 0)
display_width = display_width * track->par->sample_aspect_ratio.num / track->par->sample_aspect_ratio.den;
avio_wb32(pb, display_width);
/* values below are based on samples created with quicktime and avid codecs */
if (interlaced) {
avio_wb32(pb, track->par->height / 2);
avio_wb32(pb, 2); /* unknown */
avio_wb32(pb, 0); /* unknown */
avio_wb32(pb, 4); /* unknown */
} else {
avio_wb32(pb, track->par->height);
avio_wb32(pb, 1); /* unknown */
avio_wb32(pb, 0); /* unknown */
if (track->par->height == 1080)
avio_wb32(pb, 5); /* unknown */
else
avio_wb32(pb, 6); /* unknown */
}
/* padding */
for (i = 0; i < 10; i++)
avio_wb64(pb, 0);
return 0;
}
static int mov_write_dpxe_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 12);
ffio_wfourcc(pb, "DpxE");
if (track->par->extradata_size >= 12 &&
!memcmp(&track->par->extradata[4], "DpxE", 4)) {
avio_wb32(pb, track->par->extradata[11]);
} else {
avio_wb32(pb, 1);
}
return 0;
}
static int mov_get_dv_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag;
if (track->par->width == 720) { /* SD */
if (track->par->height == 480) { /* NTSC */
if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','n');
else tag = MKTAG('d','v','c',' ');
}else if (track->par->format == AV_PIX_FMT_YUV422P) tag = MKTAG('d','v','5','p');
else if (track->par->format == AV_PIX_FMT_YUV420P) tag = MKTAG('d','v','c','p');
else tag = MKTAG('d','v','p','p');
} else if (track->par->height == 720) { /* HD 720 line */
if (track->st->time_base.den == 50) tag = MKTAG('d','v','h','q');
else tag = MKTAG('d','v','h','p');
} else if (track->par->height == 1080) { /* HD 1080 line */
if (track->st->time_base.den == 25) tag = MKTAG('d','v','h','5');
else tag = MKTAG('d','v','h','6');
} else {
av_log(s, AV_LOG_ERROR, "unsupported height for dv codec\n");
return 0;
}
return tag;
}
static AVRational find_fps(AVFormatContext *s, AVStream *st)
{
AVRational rate = st->avg_frame_rate;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
rate = av_inv_q(st->codec->time_base);
if (av_timecode_check_frame_rate(rate) < 0) {
av_log(s, AV_LOG_DEBUG, "timecode: tbc=%d/%d invalid, fallback on %d/%d\n",
rate.num, rate.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
rate = st->avg_frame_rate;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
return rate;
}
static int defined_frame_rate(AVFormatContext *s, AVStream *st)
{
AVRational rational_framerate = find_fps(s, st);
int rate = 0;
if (rational_framerate.den != 0)
rate = av_q2d(rational_framerate);
return rate;
}
static int mov_get_mpeg2_xdcam_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(s, st);
if (!tag)
tag = MKTAG('m', '2', 'v', '1'); //fallback tag
if (track->par->format == AV_PIX_FMT_YUV420P) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','4');
else if (rate == 25) tag = MKTAG('x','d','v','5');
else if (rate == 30) tag = MKTAG('x','d','v','1');
else if (rate == 50) tag = MKTAG('x','d','v','a');
else if (rate == 60) tag = MKTAG('x','d','v','9');
}
} else if (track->par->width == 1440 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','6');
else if (rate == 25) tag = MKTAG('x','d','v','7');
else if (rate == 30) tag = MKTAG('x','d','v','8');
} else {
if (rate == 25) tag = MKTAG('x','d','v','3');
else if (rate == 30) tag = MKTAG('x','d','v','2');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','v','d');
else if (rate == 25) tag = MKTAG('x','d','v','e');
else if (rate == 30) tag = MKTAG('x','d','v','f');
} else {
if (rate == 25) tag = MKTAG('x','d','v','c');
else if (rate == 30) tag = MKTAG('x','d','v','b');
}
}
} else if (track->par->format == AV_PIX_FMT_YUV422P) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','5','4');
else if (rate == 25) tag = MKTAG('x','d','5','5');
else if (rate == 30) tag = MKTAG('x','d','5','1');
else if (rate == 50) tag = MKTAG('x','d','5','a');
else if (rate == 60) tag = MKTAG('x','d','5','9');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('x','d','5','d');
else if (rate == 25) tag = MKTAG('x','d','5','e');
else if (rate == 30) tag = MKTAG('x','d','5','f');
} else {
if (rate == 25) tag = MKTAG('x','d','5','c');
else if (rate == 30) tag = MKTAG('x','d','5','b');
}
}
}
return tag;
}
static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(s, st);
if (!tag)
tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag
if (track->par->format == AV_PIX_FMT_YUV420P10) {
if (track->par->width == 960 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','5','p');
else if (rate == 25) tag = MKTAG('a','i','5','q');
else if (rate == 30) tag = MKTAG('a','i','5','p');
else if (rate == 50) tag = MKTAG('a','i','5','q');
else if (rate == 60) tag = MKTAG('a','i','5','p');
}
} else if (track->par->width == 1440 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','5','3');
else if (rate == 25) tag = MKTAG('a','i','5','2');
else if (rate == 30) tag = MKTAG('a','i','5','3');
} else {
if (rate == 50) tag = MKTAG('a','i','5','5');
else if (rate == 60) tag = MKTAG('a','i','5','6');
}
}
} else if (track->par->format == AV_PIX_FMT_YUV422P10) {
if (track->par->width == 1280 && track->par->height == 720) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','1','p');
else if (rate == 25) tag = MKTAG('a','i','1','q');
else if (rate == 30) tag = MKTAG('a','i','1','p');
else if (rate == 50) tag = MKTAG('a','i','1','q');
else if (rate == 60) tag = MKTAG('a','i','1','p');
}
} else if (track->par->width == 1920 && track->par->height == 1080) {
if (!interlaced) {
if (rate == 24) tag = MKTAG('a','i','1','3');
else if (rate == 25) tag = MKTAG('a','i','1','2');
else if (rate == 30) tag = MKTAG('a','i','1','3');
} else {
if (rate == 25) tag = MKTAG('a','i','1','5');
else if (rate == 50) tag = MKTAG('a','i','1','5');
else if (rate == 60) tag = MKTAG('a','i','1','6');
}
} else if ( track->par->width == 4096 && track->par->height == 2160
|| track->par->width == 3840 && track->par->height == 2160
|| track->par->width == 2048 && track->par->height == 1080) {
tag = MKTAG('a','i','v','x');
}
}
return tag;
}
static const struct {
enum AVPixelFormat pix_fmt;
uint32_t tag;
unsigned bps;
} mov_pix_fmt_tags[] = {
{ AV_PIX_FMT_YUYV422, MKTAG('y','u','v','2'), 0 },
{ AV_PIX_FMT_YUYV422, MKTAG('y','u','v','s'), 0 },
{ AV_PIX_FMT_UYVY422, MKTAG('2','v','u','y'), 0 },
{ AV_PIX_FMT_RGB555BE,MKTAG('r','a','w',' '), 16 },
{ AV_PIX_FMT_RGB555LE,MKTAG('L','5','5','5'), 16 },
{ AV_PIX_FMT_RGB565LE,MKTAG('L','5','6','5'), 16 },
{ AV_PIX_FMT_RGB565BE,MKTAG('B','5','6','5'), 16 },
{ AV_PIX_FMT_GRAY16BE,MKTAG('b','1','6','g'), 16 },
{ AV_PIX_FMT_RGB24, MKTAG('r','a','w',' '), 24 },
{ AV_PIX_FMT_BGR24, MKTAG('2','4','B','G'), 24 },
{ AV_PIX_FMT_ARGB, MKTAG('r','a','w',' '), 32 },
{ AV_PIX_FMT_BGRA, MKTAG('B','G','R','A'), 32 },
{ AV_PIX_FMT_RGBA, MKTAG('R','G','B','A'), 32 },
{ AV_PIX_FMT_ABGR, MKTAG('A','B','G','R'), 32 },
{ AV_PIX_FMT_RGB48BE, MKTAG('b','4','8','r'), 48 },
};
static int mov_get_dnxhd_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = MKTAG('A','V','d','n');
if (track->par->profile != FF_PROFILE_UNKNOWN &&
track->par->profile != FF_PROFILE_DNXHD)
tag = MKTAG('A','V','d','h');
return tag;
}
static int mov_get_rawvideo_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
int i;
enum AVPixelFormat pix_fmt;
for (i = 0; i < FF_ARRAY_ELEMS(mov_pix_fmt_tags); i++) {
if (track->par->format == mov_pix_fmt_tags[i].pix_fmt) {
tag = mov_pix_fmt_tags[i].tag;
track->par->bits_per_coded_sample = mov_pix_fmt_tags[i].bps;
if (track->par->codec_tag == mov_pix_fmt_tags[i].tag)
break;
}
}
pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_mov,
track->par->bits_per_coded_sample);
if (tag == MKTAG('r','a','w',' ') &&
track->par->format != pix_fmt &&
track->par->format != AV_PIX_FMT_GRAY8 &&
track->par->format != AV_PIX_FMT_NONE)
av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to mov, output file will be unreadable\n",
av_get_pix_fmt_name(track->par->format));
return tag;
}
static int mov_get_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag = track->par->codec_tag;
if (!tag || (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL &&
(track->par->codec_id == AV_CODEC_ID_DVVIDEO ||
track->par->codec_id == AV_CODEC_ID_RAWVIDEO ||
track->par->codec_id == AV_CODEC_ID_H263 ||
track->par->codec_id == AV_CODEC_ID_H264 ||
track->par->codec_id == AV_CODEC_ID_DNXHD ||
track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO ||
av_get_bits_per_sample(track->par->codec_id)))) { // pcm audio
if (track->par->codec_id == AV_CODEC_ID_DVVIDEO)
tag = mov_get_dv_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO)
tag = mov_get_rawvideo_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO)
tag = mov_get_mpeg2_xdcam_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_H264)
tag = mov_get_h264_codec_tag(s, track);
else if (track->par->codec_id == AV_CODEC_ID_DNXHD)
tag = mov_get_dnxhd_codec_tag(s, track);
else if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
tag = ff_codec_get_tag(ff_codec_movvideo_tags, track->par->codec_id);
if (!tag) { // if no mac fcc found, try with Microsoft tags
tag = ff_codec_get_tag(ff_codec_bmp_tags, track->par->codec_id);
if (tag)
av_log(s, AV_LOG_WARNING, "Using MS style video codec tag, "
"the file may be unplayable!\n");
}
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
tag = ff_codec_get_tag(ff_codec_movaudio_tags, track->par->codec_id);
if (!tag) { // if no mac fcc found, try with Microsoft tags
int ms_tag = ff_codec_get_tag(ff_codec_wav_tags, track->par->codec_id);
if (ms_tag) {
tag = MKTAG('m', 's', ((ms_tag >> 8) & 0xff), (ms_tag & 0xff));
av_log(s, AV_LOG_WARNING, "Using MS style audio codec tag, "
"the file may be unplayable!\n");
}
}
} else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
tag = ff_codec_get_tag(ff_codec_movsubtitle_tags, track->par->codec_id);
}
return tag;
}
static const AVCodecTag codec_cover_image_tags[] = {
{ AV_CODEC_ID_MJPEG, 0xD },
{ AV_CODEC_ID_PNG, 0xE },
{ AV_CODEC_ID_BMP, 0x1B },
{ AV_CODEC_ID_NONE, 0 },
};
static int mov_find_codec_tag(AVFormatContext *s, MOVTrack *track)
{
int tag;
if (is_cover_image(track->st))
return ff_codec_get_tag(codec_cover_image_tags, track->par->codec_id);
if (track->mode == MODE_MP4 || track->mode == MODE_PSP)
tag = track->par->codec_tag;
else if (track->mode == MODE_ISM)
tag = track->par->codec_tag;
else if (track->mode == MODE_IPOD) {
if (!av_match_ext(s->url, "m4a") &&
!av_match_ext(s->url, "m4v") &&
!av_match_ext(s->url, "m4b"))
av_log(s, AV_LOG_WARNING, "Warning, extension is not .m4a nor .m4v "
"Quicktime/Ipod might not play the file\n");
tag = track->par->codec_tag;
} else if (track->mode & MODE_3GP)
tag = track->par->codec_tag;
else if (track->mode == MODE_F4V)
tag = track->par->codec_tag;
else
tag = mov_get_codec_tag(s, track);
return tag;
}
/** Write uuid atom.
* Needed to make file play in iPods running newest firmware
* goes after avcC atom in moov.trak.mdia.minf.stbl.stsd.avc1
*/
static int mov_write_uuid_tag_ipod(AVIOContext *pb)
{
avio_wb32(pb, 28);
ffio_wfourcc(pb, "uuid");
avio_wb32(pb, 0x6b6840f2);
avio_wb32(pb, 0x5f244fc5);
avio_wb32(pb, 0xba39a51b);
avio_wb32(pb, 0xcf0323f3);
avio_wb32(pb, 0x0);
return 28;
}
static const uint16_t fiel_data[] = {
0x0000, 0x0100, 0x0201, 0x0206, 0x0209, 0x020e
};
static int mov_write_fiel_tag(AVIOContext *pb, MOVTrack *track, int field_order)
{
unsigned mov_field_order = 0;
if (field_order < FF_ARRAY_ELEMS(fiel_data))
mov_field_order = fiel_data[field_order];
else
return 0;
avio_wb32(pb, 10);
ffio_wfourcc(pb, "fiel");
avio_wb16(pb, mov_field_order);
return 10;
}
static int mov_write_subtitle_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
avio_wl32(pb, track->tag); // store it byteswapped
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
if (track->par->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
mov_write_esds_tag(pb, track);
else if (track->par->extradata_size)
avio_write(pb, track->par->extradata, track->par->extradata_size);
return update_size(pb, pos);
}
static int mov_write_st3d_tag(AVIOContext *pb, AVStereo3D *stereo_3d)
{
int8_t stereo_mode;
if (stereo_3d->flags != 0) {
av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d flags %x. st3d not written.\n", stereo_3d->flags);
return 0;
}
switch (stereo_3d->type) {
case AV_STEREO3D_2D:
stereo_mode = 0;
break;
case AV_STEREO3D_TOPBOTTOM:
stereo_mode = 1;
break;
case AV_STEREO3D_SIDEBYSIDE:
stereo_mode = 2;
break;
default:
av_log(pb, AV_LOG_WARNING, "Unsupported stereo_3d type %s. st3d not written.\n", av_stereo3d_type_name(stereo_3d->type));
return 0;
}
avio_wb32(pb, 13); /* size */
ffio_wfourcc(pb, "st3d");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_w8(pb, stereo_mode);
return 13;
}
static int mov_write_sv3d_tag(AVFormatContext *s, AVIOContext *pb, AVSphericalMapping *spherical_mapping)
{
int64_t sv3d_pos, svhd_pos, proj_pos;
const char* metadata_source = s->flags & AVFMT_FLAG_BITEXACT ? "Lavf" : LIBAVFORMAT_IDENT;
if (spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR &&
spherical_mapping->projection != AV_SPHERICAL_EQUIRECTANGULAR_TILE &&
spherical_mapping->projection != AV_SPHERICAL_CUBEMAP) {
av_log(pb, AV_LOG_WARNING, "Unsupported projection %d. sv3d not written.\n", spherical_mapping->projection);
return 0;
}
sv3d_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "sv3d");
svhd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "svhd");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_put_str(pb, metadata_source);
update_size(pb, svhd_pos);
proj_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "proj");
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "prhd");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, spherical_mapping->yaw);
avio_wb32(pb, spherical_mapping->pitch);
avio_wb32(pb, spherical_mapping->roll);
switch (spherical_mapping->projection) {
case AV_SPHERICAL_EQUIRECTANGULAR:
case AV_SPHERICAL_EQUIRECTANGULAR_TILE:
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "equi");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, spherical_mapping->bound_top);
avio_wb32(pb, spherical_mapping->bound_bottom);
avio_wb32(pb, spherical_mapping->bound_left);
avio_wb32(pb, spherical_mapping->bound_right);
break;
case AV_SPHERICAL_CUBEMAP:
avio_wb32(pb, 20); /* size */
ffio_wfourcc(pb, "cbmp");
avio_wb32(pb, 0); /* version = 0 & flags = 0 */
avio_wb32(pb, 0); /* layout */
avio_wb32(pb, spherical_mapping->padding); /* padding */
break;
}
update_size(pb, proj_pos);
return update_size(pb, sv3d_pos);
}
static int mov_write_clap_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 40);
ffio_wfourcc(pb, "clap");
avio_wb32(pb, track->par->width); /* apertureWidth_N */
avio_wb32(pb, 1); /* apertureWidth_D (= 1) */
avio_wb32(pb, track->height); /* apertureHeight_N */
avio_wb32(pb, 1); /* apertureHeight_D (= 1) */
avio_wb32(pb, 0); /* horizOff_N (= 0) */
avio_wb32(pb, 1); /* horizOff_D (= 1) */
avio_wb32(pb, 0); /* vertOff_N (= 0) */
avio_wb32(pb, 1); /* vertOff_D (= 1) */
return 40;
}
static int mov_write_pasp_tag(AVIOContext *pb, MOVTrack *track)
{
AVRational sar;
av_reduce(&sar.num, &sar.den, track->par->sample_aspect_ratio.num,
track->par->sample_aspect_ratio.den, INT_MAX);
avio_wb32(pb, 16);
ffio_wfourcc(pb, "pasp");
avio_wb32(pb, sar.num);
avio_wb32(pb, sar.den);
return 16;
}
static int mov_write_gama_tag(AVIOContext *pb, MOVTrack *track, double gamma)
{
uint32_t gama = 0;
if (gamma <= 0.0)
{
gamma = avpriv_get_gamma_from_trc(track->par->color_trc);
}
av_log(pb, AV_LOG_DEBUG, "gamma value %g\n", gamma);
if (gamma > 1e-6) {
gama = (uint32_t)lrint((double)(1<<16) * gamma);
av_log(pb, AV_LOG_DEBUG, "writing gama value %"PRId32"\n", gama);
av_assert0(track->mode == MODE_MOV);
avio_wb32(pb, 12);
ffio_wfourcc(pb, "gama");
avio_wb32(pb, gama);
return 12;
}
else {
av_log(pb, AV_LOG_WARNING, "gamma value unknown, unable to write gama atom\n");
}
return 0;
}
static int mov_write_colr_tag(AVIOContext *pb, MOVTrack *track)
{
// Ref (MOV): https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG9
// Ref (MP4): ISO/IEC 14496-12:2012
if (track->par->color_primaries == AVCOL_PRI_UNSPECIFIED &&
track->par->color_trc == AVCOL_TRC_UNSPECIFIED &&
track->par->color_space == AVCOL_SPC_UNSPECIFIED) {
if ((track->par->width >= 1920 && track->par->height >= 1080)
|| (track->par->width == 1280 && track->par->height == 720)) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt709\n");
track->par->color_primaries = AVCOL_PRI_BT709;
} else if (track->par->width == 720 && track->height == 576) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming bt470bg\n");
track->par->color_primaries = AVCOL_PRI_BT470BG;
} else if (track->par->width == 720 &&
(track->height == 486 || track->height == 480)) {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, assuming smpte170\n");
track->par->color_primaries = AVCOL_PRI_SMPTE170M;
} else {
av_log(NULL, AV_LOG_WARNING, "color primaries unspecified, unable to assume anything\n");
}
switch (track->par->color_primaries) {
case AVCOL_PRI_BT709:
track->par->color_trc = AVCOL_TRC_BT709;
track->par->color_space = AVCOL_SPC_BT709;
break;
case AVCOL_PRI_SMPTE170M:
case AVCOL_PRI_BT470BG:
track->par->color_trc = AVCOL_TRC_BT709;
track->par->color_space = AVCOL_SPC_SMPTE170M;
break;
}
}
/* We should only ever be called by MOV or MP4. */
av_assert0(track->mode == MODE_MOV || track->mode == MODE_MP4);
avio_wb32(pb, 18 + (track->mode == MODE_MP4));
ffio_wfourcc(pb, "colr");
if (track->mode == MODE_MP4)
ffio_wfourcc(pb, "nclx");
else
ffio_wfourcc(pb, "nclc");
switch (track->par->color_primaries) {
case AVCOL_PRI_BT709: avio_wb16(pb, 1); break;
case AVCOL_PRI_BT470BG: avio_wb16(pb, 5); break;
case AVCOL_PRI_SMPTE170M:
case AVCOL_PRI_SMPTE240M: avio_wb16(pb, 6); break;
case AVCOL_PRI_BT2020: avio_wb16(pb, 9); break;
case AVCOL_PRI_SMPTE431: avio_wb16(pb, 11); break;
case AVCOL_PRI_SMPTE432: avio_wb16(pb, 12); break;
default: avio_wb16(pb, 2);
}
switch (track->par->color_trc) {
case AVCOL_TRC_BT709: avio_wb16(pb, 1); break;
case AVCOL_TRC_SMPTE170M: avio_wb16(pb, 1); break; // remapped
case AVCOL_TRC_SMPTE240M: avio_wb16(pb, 7); break;
case AVCOL_TRC_SMPTEST2084: avio_wb16(pb, 16); break;
case AVCOL_TRC_SMPTE428: avio_wb16(pb, 17); break;
case AVCOL_TRC_ARIB_STD_B67: avio_wb16(pb, 18); break;
default: avio_wb16(pb, 2);
}
switch (track->par->color_space) {
case AVCOL_SPC_BT709: avio_wb16(pb, 1); break;
case AVCOL_SPC_BT470BG:
case AVCOL_SPC_SMPTE170M: avio_wb16(pb, 6); break;
case AVCOL_SPC_SMPTE240M: avio_wb16(pb, 7); break;
case AVCOL_SPC_BT2020_NCL: avio_wb16(pb, 9); break;
default: avio_wb16(pb, 2);
}
if (track->mode == MODE_MP4) {
int full_range = track->par->color_range == AVCOL_RANGE_JPEG;
avio_w8(pb, full_range << 7);
return 19;
} else {
return 18;
}
}
static void find_compressor(char * compressor_name, int len, MOVTrack *track)
{
AVDictionaryEntry *encoder;
int xdcam_res = (track->par->width == 1280 && track->par->height == 720)
|| (track->par->width == 1440 && track->par->height == 1080)
|| (track->par->width == 1920 && track->par->height == 1080);
if (track->mode == MODE_MOV &&
(encoder = av_dict_get(track->st->metadata, "encoder", NULL, 0))) {
av_strlcpy(compressor_name, encoder->value, 32);
} else if (track->par->codec_id == AV_CODEC_ID_MPEG2VIDEO && xdcam_res) {
int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;
AVStream *st = track->st;
int rate = defined_frame_rate(NULL, st);
av_strlcatf(compressor_name, len, "XDCAM");
if (track->par->format == AV_PIX_FMT_YUV422P) {
av_strlcatf(compressor_name, len, " HD422");
} else if(track->par->width == 1440) {
av_strlcatf(compressor_name, len, " HD");
} else
av_strlcatf(compressor_name, len, " EX");
av_strlcatf(compressor_name, len, " %d%c", track->par->height, interlaced ? 'i' : 'p');
av_strlcatf(compressor_name, len, "%d", rate * (interlaced + 1));
}
}
static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
char compressor_name[32] = { 0 };
int avid = 0;
int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422)
|| (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422)
|| track->par->codec_id == AV_CODEC_ID_V308
|| track->par->codec_id == AV_CODEC_ID_V408
|| track->par->codec_id == AV_CODEC_ID_V410
|| track->par->codec_id == AV_CODEC_ID_V210);
avio_wb32(pb, 0); /* size */
if (mov->encryption_scheme != MOV_ENC_NONE) {
ffio_wfourcc(pb, "encv");
} else {
avio_wl32(pb, track->tag); // store it byteswapped
}
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
if (uncompressed_ycbcr) {
avio_wb16(pb, 2); /* Codec stream version */
} else {
avio_wb16(pb, 0); /* Codec stream version */
}
avio_wb16(pb, 0); /* Codec stream revision (=0) */
if (track->mode == MODE_MOV) {
ffio_wfourcc(pb, "FFMP"); /* Vendor */
if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) {
avio_wb32(pb, 0); /* Temporal Quality */
avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/
} else {
avio_wb32(pb, 0x200); /* Temporal Quality = normal */
avio_wb32(pb, 0x200); /* Spatial Quality = normal */
}
} else {
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 0); /* Reserved */
}
avio_wb16(pb, track->par->width); /* Video width */
avio_wb16(pb, track->height); /* Video height */
avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */
avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */
avio_wb32(pb, 0); /* Data size (= 0) */
avio_wb16(pb, 1); /* Frame count (= 1) */
/* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */
find_compressor(compressor_name, 32, track);
avio_w8(pb, strlen(compressor_name));
avio_write(pb, compressor_name, 31);
if (track->mode == MODE_MOV &&
(track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210))
avio_wb16(pb, 0x18);
else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample)
avio_wb16(pb, track->par->bits_per_coded_sample |
(track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0));
else
avio_wb16(pb, 0x18); /* Reserved */
if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) {
int pal_size = 1 << track->par->bits_per_coded_sample;
int i;
avio_wb16(pb, 0); /* Color table ID */
avio_wb32(pb, 0); /* Color table seed */
avio_wb16(pb, 0x8000); /* Color table flags */
avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */
for (i = 0; i < pal_size; i++) {
uint32_t rgb = track->palette[i];
uint16_t r = (rgb >> 16) & 0xff;
uint16_t g = (rgb >> 8) & 0xff;
uint16_t b = rgb & 0xff;
avio_wb16(pb, 0);
avio_wb16(pb, (r << 8) | r);
avio_wb16(pb, (g << 8) | g);
avio_wb16(pb, (b << 8) | b);
}
} else
avio_wb16(pb, 0xffff); /* Reserved */
if (track->tag == MKTAG('m','p','4','v'))
mov_write_esds_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_H263)
mov_write_d263_tag(pb);
else if (track->par->codec_id == AV_CODEC_ID_AVUI ||
track->par->codec_id == AV_CODEC_ID_SVQ3) {
mov_write_extradata_tag(pb, track);
avio_wb32(pb, 0);
} else if (track->par->codec_id == AV_CODEC_ID_DNXHD) {
mov_write_avid_tag(pb, track);
avid = 1;
} else if (track->par->codec_id == AV_CODEC_ID_HEVC)
mov_write_hvcc_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) {
mov_write_avcc_tag(pb, track);
if (track->mode == MODE_IPOD)
mov_write_uuid_tag_ipod(pb);
} else if (track->par->codec_id == AV_CODEC_ID_VP9) {
mov_write_vpcc_tag(mov->fc, pb, track);
} else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0)
mov_write_dvc1_tag(pb, track);
else if (track->par->codec_id == AV_CODEC_ID_VP6F ||
track->par->codec_id == AV_CODEC_ID_VP6A) {
/* Don't write any potential extradata here - the cropping
* is signalled via the normal width/height fields. */
} else if (track->par->codec_id == AV_CODEC_ID_R10K) {
if (track->par->codec_tag == MKTAG('R','1','0','k'))
mov_write_dpxe_tag(pb, track);
} else if (track->vos_len > 0)
mov_write_glbl_tag(pb, track);
if (track->par->codec_id != AV_CODEC_ID_H264 &&
track->par->codec_id != AV_CODEC_ID_MPEG4 &&
track->par->codec_id != AV_CODEC_ID_DNXHD) {
int field_order = track->par->field_order;
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN)
field_order = track->st->codec->field_order;
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (field_order != AV_FIELD_UNKNOWN)
mov_write_fiel_tag(pb, track, field_order);
}
if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) {
if (track->mode == MODE_MOV)
mov_write_gama_tag(pb, track, mov->gamma);
else
av_log(mov->fc, AV_LOG_WARNING, "Not writing 'gama' atom. Format is not MOV.\n");
}
if (mov->flags & FF_MOV_FLAG_WRITE_COLR) {
if (track->mode == MODE_MOV || track->mode == MODE_MP4)
mov_write_colr_tag(pb, track);
else
av_log(mov->fc, AV_LOG_WARNING, "Not writing 'colr' atom. Format is not MOV or MP4.\n");
}
if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) {
AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL);
AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL);
if (stereo_3d)
mov_write_st3d_tag(pb, stereo_3d);
if (spherical_mapping)
mov_write_sv3d_tag(mov->fc, pb, spherical_mapping);
}
if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) {
mov_write_pasp_tag(pb, track);
}
if (uncompressed_ycbcr){
mov_write_clap_tag(pb, track);
}
if (mov->encryption_scheme != MOV_ENC_NONE) {
ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid);
}
/* extra padding for avid stsd */
/* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */
if (avid)
avio_wb32(pb, 0);
return update_size(pb, pos);
}
static int mov_write_rtp_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "rtp ");
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
avio_wb16(pb, 1); /* Hint track version */
avio_wb16(pb, 1); /* Highest compatible version */
avio_wb32(pb, track->max_packet_size); /* Max packet size */
avio_wb32(pb, 12); /* size */
ffio_wfourcc(pb, "tims");
avio_wb32(pb, track->timescale);
return update_size(pb, pos);
}
static int mov_write_source_reference_tag(AVIOContext *pb, MOVTrack *track, const char *reel_name)
{
uint64_t str_size =strlen(reel_name);
int64_t pos = avio_tell(pb);
if (str_size >= UINT16_MAX){
av_log(NULL, AV_LOG_ERROR, "reel_name length %"PRIu64" is too large\n", str_size);
avio_wb16(pb, 0);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "name"); /* Data format */
avio_wb16(pb, str_size); /* string size */
avio_wb16(pb, track->language); /* langcode */
avio_write(pb, reel_name, str_size); /* reel name */
return update_size(pb,pos);
}
static int mov_write_tmcd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
#if 1
int frame_duration;
int nb_frames;
AVDictionaryEntry *t = NULL;
if (!track->st->avg_frame_rate.num || !track->st->avg_frame_rate.den) {
#if FF_API_LAVF_AVCTX
FF_DISABLE_DEPRECATION_WARNINGS
frame_duration = av_rescale(track->timescale, track->st->codec->time_base.num, track->st->codec->time_base.den);
nb_frames = ROUNDED_DIV(track->st->codec->time_base.den, track->st->codec->time_base.num);
FF_ENABLE_DEPRECATION_WARNINGS
#else
av_log(NULL, AV_LOG_ERROR, "avg_frame_rate not set for tmcd track.\n");
return AVERROR(EINVAL);
#endif
} else {
frame_duration = av_rescale(track->timescale, track->st->avg_frame_rate.num, track->st->avg_frame_rate.den);
nb_frames = ROUNDED_DIV(track->st->avg_frame_rate.den, track->st->avg_frame_rate.num);
}
if (nb_frames > 255) {
av_log(NULL, AV_LOG_ERROR, "fps %d is too large\n", nb_frames);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd"); /* Data format */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 1); /* Data reference index */
avio_wb32(pb, 0); /* Flags */
avio_wb32(pb, track->timecode_flags); /* Flags (timecode) */
avio_wb32(pb, track->timescale); /* Timescale */
avio_wb32(pb, frame_duration); /* Frame duration */
avio_w8(pb, nb_frames); /* Number of frames */
avio_w8(pb, 0); /* Reserved */
t = av_dict_get(track->st->metadata, "reel_name", NULL, 0);
if (t && utf8len(t->value) && track->mode != MODE_MP4)
mov_write_source_reference_tag(pb, track, t->value);
else
avio_wb16(pb, 0); /* zero size */
#else
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd"); /* Data format */
avio_wb32(pb, 0); /* Reserved */
avio_wb32(pb, 1); /* Data reference index */
if (track->par->extradata_size)
avio_write(pb, track->par->extradata, track->par->extradata_size);
#endif
return update_size(pb, pos);
}
static int mov_write_gpmd_tag(AVIOContext *pb, const MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gpmd");
avio_wb32(pb, 0); /* Reserved */
avio_wb16(pb, 0); /* Reserved */
avio_wb16(pb, 1); /* Data-reference index */
avio_wb32(pb, 0); /* Reserved */
return update_size(pb, pos);
}
static int mov_write_stsd_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stsd");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, 1); /* entry count */
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
mov_write_video_tag(pb, mov, track);
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_audio_tag(s, pb, mov, track);
else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)
mov_write_subtitle_tag(pb, track);
else if (track->par->codec_tag == MKTAG('r','t','p',' '))
mov_write_rtp_tag(pb, track);
else if (track->par->codec_tag == MKTAG('t','m','c','d'))
mov_write_tmcd_tag(pb, track);
else if (track->par->codec_tag == MKTAG('g','p','m','d'))
mov_write_gpmd_tag(pb, track);
return update_size(pb, pos);
}
static int mov_write_ctts_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
MOVStts *ctts_entries;
uint32_t entries = 0;
uint32_t atom_size;
int i;
ctts_entries = av_malloc_array((track->entry + 1), sizeof(*ctts_entries)); /* worst case */
if (!ctts_entries)
return AVERROR(ENOMEM);
ctts_entries[0].count = 1;
ctts_entries[0].duration = track->cluster[0].cts;
for (i = 1; i < track->entry; i++) {
if (track->cluster[i].cts == ctts_entries[entries].duration) {
ctts_entries[entries].count++; /* compress */
} else {
entries++;
ctts_entries[entries].duration = track->cluster[i].cts;
ctts_entries[entries].count = 1;
}
}
entries++; /* last one */
atom_size = 16 + (entries * 8);
avio_wb32(pb, atom_size); /* size */
ffio_wfourcc(pb, "ctts");
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
avio_w8(pb, 1); /* version */
else
avio_w8(pb, 0); /* version */
avio_wb24(pb, 0); /* flags */
avio_wb32(pb, entries); /* entry count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, ctts_entries[i].count);
avio_wb32(pb, ctts_entries[i].duration);
}
av_free(ctts_entries);
return atom_size;
}
/* Time to sample atom */
static int mov_write_stts_tag(AVIOContext *pb, MOVTrack *track)
{
MOVStts *stts_entries = NULL;
uint32_t entries = -1;
uint32_t atom_size;
int i;
if (track->par->codec_type == AVMEDIA_TYPE_AUDIO && !track->audio_vbr) {
stts_entries = av_malloc(sizeof(*stts_entries)); /* one entry */
if (!stts_entries)
return AVERROR(ENOMEM);
stts_entries[0].count = track->sample_count;
stts_entries[0].duration = 1;
entries = 1;
} else {
if (track->entry) {
stts_entries = av_malloc_array(track->entry, sizeof(*stts_entries)); /* worst case */
if (!stts_entries)
return AVERROR(ENOMEM);
}
for (i = 0; i < track->entry; i++) {
int duration = get_cluster_duration(track, i);
if (i && duration == stts_entries[entries].duration) {
stts_entries[entries].count++; /* compress */
} else {
entries++;
stts_entries[entries].duration = duration;
stts_entries[entries].count = 1;
}
}
entries++; /* last one */
}
atom_size = 16 + (entries * 8);
avio_wb32(pb, atom_size); /* size */
ffio_wfourcc(pb, "stts");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, entries); /* entry count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, stts_entries[i].count);
avio_wb32(pb, stts_entries[i].duration);
}
av_free(stts_entries);
return atom_size;
}
static int mov_write_dref_tag(AVIOContext *pb)
{
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "dref");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, 1); /* entry count */
avio_wb32(pb, 0xc); /* size */
//FIXME add the alis and rsrc atom
ffio_wfourcc(pb, "url ");
avio_wb32(pb, 1); /* version & flags */
return 28;
}
static int mov_preroll_write_stbl_atoms(AVIOContext *pb, MOVTrack *track)
{
struct sgpd_entry {
int count;
int16_t roll_distance;
int group_description_index;
};
struct sgpd_entry *sgpd_entries = NULL;
int entries = -1;
int group = 0;
int i, j;
const int OPUS_SEEK_PREROLL_MS = 80;
int roll_samples = av_rescale_q(OPUS_SEEK_PREROLL_MS,
(AVRational){1, 1000},
(AVRational){1, 48000});
if (!track->entry)
return 0;
sgpd_entries = av_malloc_array(track->entry, sizeof(*sgpd_entries));
if (!sgpd_entries)
return AVERROR(ENOMEM);
av_assert0(track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC);
if (track->par->codec_id == AV_CODEC_ID_OPUS) {
for (i = 0; i < track->entry; i++) {
int roll_samples_remaining = roll_samples;
int distance = 0;
for (j = i - 1; j >= 0; j--) {
roll_samples_remaining -= get_cluster_duration(track, j);
distance++;
if (roll_samples_remaining <= 0)
break;
}
/* We don't have enough preceeding samples to compute a valid
roll_distance here, so this sample can't be independently
decoded. */
if (roll_samples_remaining > 0)
distance = 0;
/* Verify distance is a minimum of 2 (60ms) packets and a maximum of
32 (2.5ms) packets. */
av_assert0(distance == 0 || (distance >= 2 && distance <= 32));
if (i && distance == sgpd_entries[entries].roll_distance) {
sgpd_entries[entries].count++;
} else {
entries++;
sgpd_entries[entries].count = 1;
sgpd_entries[entries].roll_distance = distance;
sgpd_entries[entries].group_description_index = distance ? ++group : 0;
}
}
} else {
entries++;
sgpd_entries[entries].count = track->sample_count;
sgpd_entries[entries].roll_distance = 1;
sgpd_entries[entries].group_description_index = ++group;
}
entries++;
if (!group) {
av_free(sgpd_entries);
return 0;
}
/* Write sgpd tag */
avio_wb32(pb, 24 + (group * 2)); /* size */
ffio_wfourcc(pb, "sgpd");
avio_wb32(pb, 1 << 24); /* fullbox */
ffio_wfourcc(pb, "roll");
avio_wb32(pb, 2); /* default_length */
avio_wb32(pb, group); /* entry_count */
for (i = 0; i < entries; i++) {
if (sgpd_entries[i].group_description_index) {
avio_wb16(pb, -sgpd_entries[i].roll_distance); /* roll_distance */
}
}
/* Write sbgp tag */
avio_wb32(pb, 20 + (entries * 8)); /* size */
ffio_wfourcc(pb, "sbgp");
avio_wb32(pb, 0); /* fullbox */
ffio_wfourcc(pb, "roll");
avio_wb32(pb, entries); /* entry_count */
for (i = 0; i < entries; i++) {
avio_wb32(pb, sgpd_entries[i].count); /* sample_count */
avio_wb32(pb, sgpd_entries[i].group_description_index); /* group_description_index */
}
av_free(sgpd_entries);
return 0;
}
static int mov_write_stbl_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "stbl");
mov_write_stsd_tag(s, pb, mov, track);
mov_write_stts_tag(pb, track);
if ((track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
track->par->codec_tag == MKTAG('r','t','p',' ')) &&
track->has_keyframes && track->has_keyframes < track->entry)
mov_write_stss_tag(pb, track, MOV_SYNC_SAMPLE);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && track->has_disposable)
mov_write_sdtp_tag(pb, track);
if (track->mode == MODE_MOV && track->flags & MOV_TRACK_STPS)
mov_write_stss_tag(pb, track, MOV_PARTIAL_SYNC_SAMPLE);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO &&
track->flags & MOV_TRACK_CTTS && track->entry) {
if ((ret = mov_write_ctts_tag(s, pb, track)) < 0)
return ret;
}
mov_write_stsc_tag(pb, track);
mov_write_stsz_tag(pb, track);
mov_write_stco_tag(pb, track);
if (track->cenc.aes_ctr) {
ff_mov_cenc_write_stbl_atoms(&track->cenc, pb);
}
if (track->par->codec_id == AV_CODEC_ID_OPUS || track->par->codec_id == AV_CODEC_ID_AAC) {
mov_preroll_write_stbl_atoms(pb, track);
}
return update_size(pb, pos);
}
static int mov_write_dinf_tag(AVIOContext *pb)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "dinf");
mov_write_dref_tag(pb);
return update_size(pb, pos);
}
static int mov_write_nmhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 12);
ffio_wfourcc(pb, "nmhd");
avio_wb32(pb, 0);
return 12;
}
static int mov_write_tcmi_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
const char *font = "Lucida Grande";
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tcmi"); /* timecode media information atom */
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0); /* text font */
avio_wb16(pb, 0); /* text face */
avio_wb16(pb, 12); /* text size */
avio_wb16(pb, 0); /* (unknown, not in the QT specs...) */
avio_wb16(pb, 0x0000); /* text color (red) */
avio_wb16(pb, 0x0000); /* text color (green) */
avio_wb16(pb, 0x0000); /* text color (blue) */
avio_wb16(pb, 0xffff); /* background color (red) */
avio_wb16(pb, 0xffff); /* background color (green) */
avio_wb16(pb, 0xffff); /* background color (blue) */
avio_w8(pb, strlen(font)); /* font len (part of the pascal string) */
avio_write(pb, font, strlen(font)); /* font name */
return update_size(pb, pos);
}
static int mov_write_gmhd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gmhd");
avio_wb32(pb, 0x18); /* gmin size */
ffio_wfourcc(pb, "gmin");/* generic media info */
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0x40); /* graphics mode = */
avio_wb16(pb, 0x8000); /* opColor (r?) */
avio_wb16(pb, 0x8000); /* opColor (g?) */
avio_wb16(pb, 0x8000); /* opColor (b?) */
avio_wb16(pb, 0); /* balance */
avio_wb16(pb, 0); /* reserved */
/*
* This special text atom is required for
* Apple Quicktime chapters. The contents
* don't appear to be documented, so the
* bytes are copied verbatim.
*/
if (track->tag != MKTAG('c','6','0','8')) {
avio_wb32(pb, 0x2C); /* size */
ffio_wfourcc(pb, "text");
avio_wb16(pb, 0x01);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x01);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00);
avio_wb32(pb, 0x00004000);
avio_wb16(pb, 0x0000);
}
if (track->par->codec_tag == MKTAG('t','m','c','d')) {
int64_t tmcd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tmcd");
mov_write_tcmi_tag(pb, track);
update_size(pb, tmcd_pos);
} else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
int64_t gpmd_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "gpmd");
avio_wb32(pb, 0); /* version */
update_size(pb, gpmd_pos);
}
return update_size(pb, pos);
}
static int mov_write_smhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 16); /* size */
ffio_wfourcc(pb, "smhd");
avio_wb32(pb, 0); /* version & flags */
avio_wb16(pb, 0); /* reserved (balance, normally = 0) */
avio_wb16(pb, 0); /* reserved */
return 16;
}
static int mov_write_vmhd_tag(AVIOContext *pb)
{
avio_wb32(pb, 0x14); /* size (always 0x14) */
ffio_wfourcc(pb, "vmhd");
avio_wb32(pb, 0x01); /* version & flags */
avio_wb64(pb, 0); /* reserved (graphics mode = copy) */
return 0x14;
}
static int is_clcp_track(MOVTrack *track)
{
return track->tag == MKTAG('c','7','0','8') ||
track->tag == MKTAG('c','6','0','8');
}
static int mov_write_hdlr_tag(AVFormatContext *s, AVIOContext *pb, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
const char *hdlr, *descr = NULL, *hdlr_type = NULL;
int64_t pos = avio_tell(pb);
hdlr = "dhlr";
hdlr_type = "url ";
descr = "DataHandler";
if (track) {
hdlr = (track->mode == MODE_MOV) ? "mhlr" : "\0\0\0\0";
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
hdlr_type = "vide";
descr = "VideoHandler";
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
hdlr_type = "soun";
descr = "SoundHandler";
} else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
if (is_clcp_track(track)) {
hdlr_type = "clcp";
descr = "ClosedCaptionHandler";
} else {
if (track->tag == MKTAG('t','x','3','g')) {
hdlr_type = "sbtl";
} else if (track->tag == MKTAG('m','p','4','s')) {
hdlr_type = "subp";
} else {
hdlr_type = "text";
}
descr = "SubtitleHandler";
}
} else if (track->par->codec_tag == MKTAG('r','t','p',' ')) {
hdlr_type = "hint";
descr = "HintHandler";
} else if (track->par->codec_tag == MKTAG('t','m','c','d')) {
hdlr_type = "tmcd";
descr = "TimeCodeHandler";
} else if (track->par->codec_tag == MKTAG('g','p','m','d')) {
hdlr_type = "meta";
descr = "GoPro MET"; // GoPro Metadata
} else {
av_log(s, AV_LOG_WARNING,
"Unknown hldr_type for %s, writing dummy values\n",
av_fourcc2str(track->par->codec_tag));
}
if (track->st) {
// hdlr.name is used by some players to identify the content title
// of the track. So if an alternate handler description is
// specified, use it.
AVDictionaryEntry *t;
t = av_dict_get(track->st->metadata, "handler_name", NULL, 0);
if (t && utf8len(t->value))
descr = t->value;
}
}
if (mov->empty_hdlr_name) /* expressly allowed by QTFF and not prohibited in ISO 14496-12 8.4.3.3 */
descr = "";
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0); /* Version & flags */
avio_write(pb, hdlr, 4); /* handler */
ffio_wfourcc(pb, hdlr_type); /* handler type */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
if (!track || track->mode == MODE_MOV)
avio_w8(pb, strlen(descr)); /* pascal string */
avio_write(pb, descr, strlen(descr)); /* handler description */
if (track && track->mode != MODE_MOV)
avio_w8(pb, 0); /* c string */
return update_size(pb, pos);
}
static int mov_write_hmhd_tag(AVIOContext *pb)
{
/* This atom must be present, but leaving the values at zero
* seems harmless. */
avio_wb32(pb, 28); /* size */
ffio_wfourcc(pb, "hmhd");
avio_wb32(pb, 0); /* version, flags */
avio_wb16(pb, 0); /* maxPDUsize */
avio_wb16(pb, 0); /* avgPDUsize */
avio_wb32(pb, 0); /* maxbitrate */
avio_wb32(pb, 0); /* avgbitrate */
avio_wb32(pb, 0); /* reserved */
return 28;
}
static int mov_write_minf_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "minf");
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO)
mov_write_vmhd_tag(pb);
else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
mov_write_smhd_tag(pb);
else if (track->par->codec_type == AVMEDIA_TYPE_SUBTITLE) {
if (track->tag == MKTAG('t','e','x','t') || is_clcp_track(track)) {
mov_write_gmhd_tag(pb, track);
} else {
mov_write_nmhd_tag(pb);
}
} else if (track->tag == MKTAG('r','t','p',' ')) {
mov_write_hmhd_tag(pb);
} else if (track->tag == MKTAG('t','m','c','d')) {
if (track->mode != MODE_MOV)
mov_write_nmhd_tag(pb);
else
mov_write_gmhd_tag(pb, track);
} else if (track->tag == MKTAG('g','p','m','d')) {
mov_write_gmhd_tag(pb, track);
}
if (track->mode == MODE_MOV) /* FIXME: Why do it for MODE_MOV only ? */
mov_write_hdlr_tag(s, pb, NULL);
mov_write_dinf_tag(pb);
if ((ret = mov_write_stbl_tag(s, pb, mov, track)) < 0)
return ret;
return update_size(pb, pos);
}
static int mov_write_mdhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int version = track->track_duration < INT32_MAX ? 0 : 1;
if (track->mode == MODE_ISM)
version = 1;
(version == 1) ? avio_wb32(pb, 44) : avio_wb32(pb, 32); /* size */
ffio_wfourcc(pb, "mdhd");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
if (version == 1) {
avio_wb64(pb, track->time);
avio_wb64(pb, track->time);
} else {
avio_wb32(pb, track->time); /* creation time */
avio_wb32(pb, track->time); /* modification time */
}
avio_wb32(pb, track->timescale); /* time scale (sample rate for audio) */
if (!track->entry && mov->mode == MODE_ISM)
(version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
else if (!track->entry)
(version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
else
(version == 1) ? avio_wb64(pb, track->track_duration) : avio_wb32(pb, track->track_duration); /* duration */
avio_wb16(pb, track->language); /* language */
avio_wb16(pb, 0); /* reserved (quality) */
if (version != 0 && track->mode == MODE_MOV) {
av_log(NULL, AV_LOG_ERROR,
"FATAL error, file duration too long for timebase, this file will not be\n"
"playable with quicktime. Choose a different timebase or a different\n"
"container format\n");
}
return 32;
}
static int mov_write_mdia_tag(AVFormatContext *s, AVIOContext *pb,
MOVMuxContext *mov, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int ret;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "mdia");
mov_write_mdhd_tag(pb, mov, track);
mov_write_hdlr_tag(s, pb, track);
if ((ret = mov_write_minf_tag(s, pb, mov, track)) < 0)
return ret;
return update_size(pb, pos);
}
/* transformation matrix
|a b u|
|c d v|
|tx ty w| */
static void write_matrix(AVIOContext *pb, int16_t a, int16_t b, int16_t c,
int16_t d, int16_t tx, int16_t ty)
{
avio_wb32(pb, a << 16); /* 16.16 format */
avio_wb32(pb, b << 16); /* 16.16 format */
avio_wb32(pb, 0); /* u in 2.30 format */
avio_wb32(pb, c << 16); /* 16.16 format */
avio_wb32(pb, d << 16); /* 16.16 format */
avio_wb32(pb, 0); /* v in 2.30 format */
avio_wb32(pb, tx << 16); /* 16.16 format */
avio_wb32(pb, ty << 16); /* 16.16 format */
avio_wb32(pb, 1 << 30); /* w in 2.30 format */
}
static int mov_write_tkhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, AVStream *st)
{
int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
track->timescale, AV_ROUND_UP);
int version = duration < INT32_MAX ? 0 : 1;
int flags = MOV_TKHD_FLAG_IN_MOVIE;
int rotation = 0;
int group = 0;
uint32_t *display_matrix = NULL;
int display_matrix_size, i;
if (st) {
if (mov->per_stream_grouping)
group = st->index;
else
group = st->codecpar->codec_type;
display_matrix = (uint32_t*)av_stream_get_side_data(st, AV_PKT_DATA_DISPLAYMATRIX,
&display_matrix_size);
if (display_matrix && display_matrix_size < 9 * sizeof(*display_matrix))
display_matrix = NULL;
}
if (track->flags & MOV_TRACK_ENABLED)
flags |= MOV_TKHD_FLAG_ENABLED;
if (track->mode == MODE_ISM)
version = 1;
(version == 1) ? avio_wb32(pb, 104) : avio_wb32(pb, 92); /* size */
ffio_wfourcc(pb, "tkhd");
avio_w8(pb, version);
avio_wb24(pb, flags);
if (version == 1) {
avio_wb64(pb, track->time);
avio_wb64(pb, track->time);
} else {
avio_wb32(pb, track->time); /* creation time */
avio_wb32(pb, track->time); /* modification time */
}
avio_wb32(pb, track->track_id); /* track-id */
avio_wb32(pb, 0); /* reserved */
if (!track->entry && mov->mode == MODE_ISM)
(version == 1) ? avio_wb64(pb, UINT64_C(0xffffffffffffffff)) : avio_wb32(pb, 0xffffffff);
else if (!track->entry)
(version == 1) ? avio_wb64(pb, 0) : avio_wb32(pb, 0);
else
(version == 1) ? avio_wb64(pb, duration) : avio_wb32(pb, duration);
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb16(pb, 0); /* layer */
avio_wb16(pb, group); /* alternate group) */
/* Volume, only for audio */
if (track->par->codec_type == AVMEDIA_TYPE_AUDIO)
avio_wb16(pb, 0x0100);
else
avio_wb16(pb, 0);
avio_wb16(pb, 0); /* reserved */
/* Matrix structure */
#if FF_API_OLD_ROTATE_API
if (st && st->metadata) {
AVDictionaryEntry *rot = av_dict_get(st->metadata, "rotate", NULL, 0);
rotation = (rot && rot->value) ? atoi(rot->value) : 0;
}
#endif
if (display_matrix) {
for (i = 0; i < 9; i++)
avio_wb32(pb, display_matrix[i]);
#if FF_API_OLD_ROTATE_API
} else if (rotation == 90) {
write_matrix(pb, 0, 1, -1, 0, track->par->height, 0);
} else if (rotation == 180) {
write_matrix(pb, -1, 0, 0, -1, track->par->width, track->par->height);
} else if (rotation == 270) {
write_matrix(pb, 0, -1, 1, 0, 0, track->par->width);
#endif
} else {
write_matrix(pb, 1, 0, 0, 1, 0, 0);
}
/* Track width and height, for visual only */
if (st && (track->par->codec_type == AVMEDIA_TYPE_VIDEO ||
track->par->codec_type == AVMEDIA_TYPE_SUBTITLE)) {
int64_t track_width_1616;
if (track->mode == MODE_MOV) {
track_width_1616 = track->par->width * 0x10000ULL;
} else {
track_width_1616 = av_rescale(st->sample_aspect_ratio.num,
track->par->width * 0x10000LL,
st->sample_aspect_ratio.den);
if (!track_width_1616 ||
track->height != track->par->height ||
track_width_1616 > UINT32_MAX)
track_width_1616 = track->par->width * 0x10000ULL;
}
if (track_width_1616 > UINT32_MAX) {
av_log(mov->fc, AV_LOG_WARNING, "track width is too large\n");
track_width_1616 = 0;
}
avio_wb32(pb, track_width_1616);
if (track->height > 0xFFFF) {
av_log(mov->fc, AV_LOG_WARNING, "track height is too large\n");
avio_wb32(pb, 0);
} else
avio_wb32(pb, track->height * 0x10000U);
} else {
avio_wb32(pb, 0);
avio_wb32(pb, 0);
}
return 0x5c;
}
static int mov_write_tapt_tag(AVIOContext *pb, MOVTrack *track)
{
int32_t width = av_rescale(track->par->sample_aspect_ratio.num, track->par->width,
track->par->sample_aspect_ratio.den);
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tapt");
avio_wb32(pb, 20);
ffio_wfourcc(pb, "clef");
avio_wb32(pb, 0);
avio_wb32(pb, width << 16);
avio_wb32(pb, track->par->height << 16);
avio_wb32(pb, 20);
ffio_wfourcc(pb, "prof");
avio_wb32(pb, 0);
avio_wb32(pb, width << 16);
avio_wb32(pb, track->par->height << 16);
avio_wb32(pb, 20);
ffio_wfourcc(pb, "enof");
avio_wb32(pb, 0);
avio_wb32(pb, track->par->width << 16);
avio_wb32(pb, track->par->height << 16);
return update_size(pb, pos);
}
// This box seems important for the psp playback ... without it the movie seems to hang
static int mov_write_edts_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int64_t duration = av_rescale_rnd(track->track_duration, MOV_TIMESCALE,
track->timescale, AV_ROUND_UP);
int version = duration < INT32_MAX ? 0 : 1;
int entry_size, entry_count, size;
int64_t delay, start_ct = track->start_cts;
int64_t start_dts = track->start_dts;
if (track->entry) {
if (start_dts != track->cluster[0].dts || start_ct != track->cluster[0].cts) {
av_log(mov->fc, AV_LOG_DEBUG,
"EDTS using dts:%"PRId64" cts:%d instead of dts:%"PRId64" cts:%"PRId64" tid:%d\n",
track->cluster[0].dts, track->cluster[0].cts,
start_dts, start_ct, track->track_id);
start_dts = track->cluster[0].dts;
start_ct = track->cluster[0].cts;
}
}
delay = av_rescale_rnd(start_dts + start_ct, MOV_TIMESCALE,
track->timescale, AV_ROUND_DOWN);
version |= delay < INT32_MAX ? 0 : 1;
entry_size = (version == 1) ? 20 : 12;
entry_count = 1 + (delay > 0);
size = 24 + entry_count * entry_size;
/* write the atom data */
avio_wb32(pb, size);
ffio_wfourcc(pb, "edts");
avio_wb32(pb, size - 8);
ffio_wfourcc(pb, "elst");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
avio_wb32(pb, entry_count);
if (delay > 0) { /* add an empty edit to delay presentation */
/* In the positive delay case, the delay includes the cts
* offset, and the second edit list entry below trims out
* the same amount from the actual content. This makes sure
* that the offset last sample is included in the edit
* list duration as well. */
if (version == 1) {
avio_wb64(pb, delay);
avio_wb64(pb, -1);
} else {
avio_wb32(pb, delay);
avio_wb32(pb, -1);
}
avio_wb32(pb, 0x00010000);
} else {
/* Avoid accidentally ending up with start_ct = -1 which has got a
* special meaning. Normally start_ct should end up positive or zero
* here, but use FFMIN in case dts is a small positive integer
* rounded to 0 when represented in MOV_TIMESCALE units. */
av_assert0(av_rescale_rnd(start_dts, MOV_TIMESCALE, track->timescale, AV_ROUND_DOWN) <= 0);
start_ct = -FFMIN(start_dts, 0);
/* Note, this delay is calculated from the pts of the first sample,
* ensuring that we don't reduce the duration for cases with
* dts<0 pts=0. */
duration += delay;
}
/* For fragmented files, we don't know the full length yet. Setting
* duration to 0 allows us to only specify the offset, including
* the rest of the content (from all future fragments) without specifying
* an explicit duration. */
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
duration = 0;
/* duration */
if (version == 1) {
avio_wb64(pb, duration);
avio_wb64(pb, start_ct);
} else {
avio_wb32(pb, duration);
avio_wb32(pb, start_ct);
}
avio_wb32(pb, 0x00010000);
return size;
}
static int mov_write_tref_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 20); // size
ffio_wfourcc(pb, "tref");
avio_wb32(pb, 12); // size (subatom)
avio_wl32(pb, track->tref_tag);
avio_wb32(pb, track->tref_id);
return 20;
}
// goes at the end of each track! ... Critical for PSP playback ("Incompatible data" without it)
static int mov_write_uuid_tag_psp(AVIOContext *pb, MOVTrack *mov)
{
avio_wb32(pb, 0x34); /* size ... reports as 28 in mp4box! */
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "USMT");
avio_wb32(pb, 0x21d24fce);
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
avio_wb32(pb, 0x1c); // another size here!
ffio_wfourcc(pb, "MTDT");
avio_wb32(pb, 0x00010012);
avio_wb32(pb, 0x0a);
avio_wb32(pb, 0x55c40000);
avio_wb32(pb, 0x1);
avio_wb32(pb, 0x0);
return 0x34;
}
static int mov_write_udta_sdp(AVIOContext *pb, MOVTrack *track)
{
AVFormatContext *ctx = track->rtp_ctx;
char buf[1000] = "";
int len;
ff_sdp_write_media(buf, sizeof(buf), ctx->streams[0], track->src_track,
NULL, NULL, 0, 0, ctx);
av_strlcatf(buf, sizeof(buf), "a=control:streamid=%d\r\n", track->track_id);
len = strlen(buf);
avio_wb32(pb, len + 24);
ffio_wfourcc(pb, "udta");
avio_wb32(pb, len + 16);
ffio_wfourcc(pb, "hnti");
avio_wb32(pb, len + 8);
ffio_wfourcc(pb, "sdp ");
avio_write(pb, buf, len);
return len + 24;
}
static int mov_write_track_metadata(AVIOContext *pb, AVStream *st,
const char *tag, const char *str)
{
int64_t pos = avio_tell(pb);
AVDictionaryEntry *t = av_dict_get(st->metadata, str, NULL, 0);
if (!t || !utf8len(t->value))
return 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, tag); /* type */
avio_write(pb, t->value, strlen(t->value)); /* UTF8 string value */
return update_size(pb, pos);
}
static int mov_write_track_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVStream *st)
{
AVIOContext *pb_buf;
int ret, size;
uint8_t *buf;
if (!st)
return 0;
ret = avio_open_dyn_buf(&pb_buf);
if (ret < 0)
return ret;
if (mov->mode & (MODE_MP4|MODE_MOV))
mov_write_track_metadata(pb_buf, st, "name", "title");
if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "udta");
avio_write(pb, buf, size);
}
av_free(buf);
return 0;
}
static int mov_write_trak_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, AVStream *st)
{
int64_t pos = avio_tell(pb);
int entry_backup = track->entry;
int chunk_backup = track->chunkCount;
int ret;
/* If we want to have an empty moov, but some samples already have been
* buffered (delay_moov), pretend that no samples have been written yet. */
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV)
track->chunkCount = track->entry = 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "trak");
mov_write_tkhd_tag(pb, mov, track, st);
av_assert2(mov->use_editlist >= 0);
if (track->start_dts != AV_NOPTS_VALUE) {
if (mov->use_editlist)
mov_write_edts_tag(pb, mov, track); // PSP Movies and several other cases require edts box
else if ((track->entry && track->cluster[0].dts) || track->mode == MODE_PSP || is_clcp_track(track))
av_log(mov->fc, AV_LOG_WARNING,
"Not writing any edit list even though one would have been required\n");
}
if (track->tref_tag)
mov_write_tref_tag(pb, track);
if ((ret = mov_write_mdia_tag(s, pb, mov, track)) < 0)
return ret;
if (track->mode == MODE_PSP)
mov_write_uuid_tag_psp(pb, track); // PSP Movies require this uuid box
if (track->tag == MKTAG('r','t','p',' '))
mov_write_udta_sdp(pb, track);
if (track->mode == MODE_MOV) {
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
double sample_aspect_ratio = av_q2d(st->sample_aspect_ratio);
if (st->sample_aspect_ratio.num && 1.0 != sample_aspect_ratio) {
mov_write_tapt_tag(pb, track);
}
}
if (is_clcp_track(track) && st->sample_aspect_ratio.num) {
mov_write_tapt_tag(pb, track);
}
}
mov_write_track_udta_tag(pb, mov, st);
track->entry = entry_backup;
track->chunkCount = chunk_backup;
return update_size(pb, pos);
}
static int mov_write_iods_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int i, has_audio = 0, has_video = 0;
int64_t pos = avio_tell(pb);
int audio_profile = mov->iods_audio_profile;
int video_profile = mov->iods_video_profile;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
has_audio |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_AUDIO;
has_video |= mov->tracks[i].par->codec_type == AVMEDIA_TYPE_VIDEO;
}
}
if (audio_profile < 0)
audio_profile = 0xFF - has_audio;
if (video_profile < 0)
video_profile = 0xFF - has_video;
avio_wb32(pb, 0x0); /* size */
ffio_wfourcc(pb, "iods");
avio_wb32(pb, 0); /* version & flags */
put_descr(pb, 0x10, 7);
avio_wb16(pb, 0x004f);
avio_w8(pb, 0xff);
avio_w8(pb, 0xff);
avio_w8(pb, audio_profile);
avio_w8(pb, video_profile);
avio_w8(pb, 0xff);
return update_size(pb, pos);
}
static int mov_write_trex_tag(AVIOContext *pb, MOVTrack *track)
{
avio_wb32(pb, 0x20); /* size */
ffio_wfourcc(pb, "trex");
avio_wb32(pb, 0); /* version & flags */
avio_wb32(pb, track->track_id); /* track ID */
avio_wb32(pb, 1); /* default sample description index */
avio_wb32(pb, 0); /* default sample duration */
avio_wb32(pb, 0); /* default sample size */
avio_wb32(pb, 0); /* default sample flags */
return 0;
}
static int mov_write_mvex_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0x0); /* size */
ffio_wfourcc(pb, "mvex");
for (i = 0; i < mov->nb_streams; i++)
mov_write_trex_tag(pb, &mov->tracks[i]);
return update_size(pb, pos);
}
static int mov_write_mvhd_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int max_track_id = 1, i;
int64_t max_track_len = 0;
int version;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 && mov->tracks[i].timescale) {
int64_t max_track_len_temp = av_rescale_rnd(mov->tracks[i].track_duration,
MOV_TIMESCALE,
mov->tracks[i].timescale,
AV_ROUND_UP);
if (max_track_len < max_track_len_temp)
max_track_len = max_track_len_temp;
if (max_track_id < mov->tracks[i].track_id)
max_track_id = mov->tracks[i].track_id;
}
}
/* If using delay_moov, make sure the output is the same as if no
* samples had been written yet. */
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
max_track_len = 0;
max_track_id = 1;
}
version = max_track_len < UINT32_MAX ? 0 : 1;
avio_wb32(pb, version == 1 ? 120 : 108); /* size */
ffio_wfourcc(pb, "mvhd");
avio_w8(pb, version);
avio_wb24(pb, 0); /* flags */
if (version == 1) {
avio_wb64(pb, mov->time);
avio_wb64(pb, mov->time);
} else {
avio_wb32(pb, mov->time); /* creation time */
avio_wb32(pb, mov->time); /* modification time */
}
avio_wb32(pb, MOV_TIMESCALE);
(version == 1) ? avio_wb64(pb, max_track_len) : avio_wb32(pb, max_track_len); /* duration of longest track */
avio_wb32(pb, 0x00010000); /* reserved (preferred rate) 1.0 = normal */
avio_wb16(pb, 0x0100); /* reserved (preferred volume) 1.0 = normal */
avio_wb16(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
avio_wb32(pb, 0); /* reserved */
/* Matrix structure */
write_matrix(pb, 1, 0, 0, 1, 0, 0);
avio_wb32(pb, 0); /* reserved (preview time) */
avio_wb32(pb, 0); /* reserved (preview duration) */
avio_wb32(pb, 0); /* reserved (poster time) */
avio_wb32(pb, 0); /* reserved (selection time) */
avio_wb32(pb, 0); /* reserved (selection duration) */
avio_wb32(pb, 0); /* reserved (current time) */
avio_wb32(pb, max_track_id + 1); /* Next track id */
return 0x6c;
}
static int mov_write_itunes_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
avio_wb32(pb, 33); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "mdir");
ffio_wfourcc(pb, "appl");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_w8(pb, 0);
return 33;
}
/* helper function to write a data tag with the specified string as data */
static int mov_write_string_data_tag(AVIOContext *pb, const char *data, int lang, int long_style)
{
if (long_style) {
int size = 16 + strlen(data);
avio_wb32(pb, size); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 1);
avio_wb32(pb, 0);
avio_write(pb, data, strlen(data));
return size;
} else {
if (!lang)
lang = ff_mov_iso639_to_lang("und", 1);
avio_wb16(pb, strlen(data)); /* string length */
avio_wb16(pb, lang);
avio_write(pb, data, strlen(data));
return strlen(data) + 4;
}
}
static int mov_write_string_tag(AVIOContext *pb, const char *name,
const char *value, int lang, int long_style)
{
int size = 0;
if (value && value[0]) {
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, name);
mov_write_string_data_tag(pb, value, lang, long_style);
size = update_size(pb, pos);
}
return size;
}
static AVDictionaryEntry *get_metadata_lang(AVFormatContext *s,
const char *tag, int *lang)
{
int l, len, len2;
AVDictionaryEntry *t, *t2 = NULL;
char tag2[16];
*lang = 0;
if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
return NULL;
len = strlen(t->key);
snprintf(tag2, sizeof(tag2), "%s-", tag);
while ((t2 = av_dict_get(s->metadata, tag2, t2, AV_DICT_IGNORE_SUFFIX))) {
len2 = strlen(t2->key);
if (len2 == len + 4 && !strcmp(t->value, t2->value)
&& (l = ff_mov_iso639_to_lang(&t2->key[len2 - 3], 1)) >= 0) {
*lang = l;
return t;
}
}
return t;
}
static int mov_write_string_metadata(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *tag,
int long_style)
{
int lang;
AVDictionaryEntry *t = get_metadata_lang(s, tag, &lang);
if (!t)
return 0;
return mov_write_string_tag(pb, name, t->value, lang, long_style);
}
/* iTunes bpm number */
static int mov_write_tmpo_tag(AVIOContext *pb, AVFormatContext *s)
{
AVDictionaryEntry *t = av_dict_get(s->metadata, "tmpo", NULL, 0);
int size = 0, tmpo = t ? atoi(t->value) : 0;
if (tmpo) {
size = 26;
avio_wb32(pb, size);
ffio_wfourcc(pb, "tmpo");
avio_wb32(pb, size-8); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0x15); //type specifier
avio_wb32(pb, 0);
avio_wb16(pb, tmpo); // data
}
return size;
}
/* 3GPP TS 26.244 */
static int mov_write_loci_tag(AVFormatContext *s, AVIOContext *pb)
{
int lang;
int64_t pos = avio_tell(pb);
double latitude, longitude, altitude;
int32_t latitude_fix, longitude_fix, altitude_fix;
AVDictionaryEntry *t = get_metadata_lang(s, "location", &lang);
const char *ptr, *place = "";
char *end;
static const char *astronomical_body = "earth";
if (!t)
return 0;
ptr = t->value;
longitude = strtod(ptr, &end);
if (end == ptr) {
av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
return 0;
}
ptr = end;
latitude = strtod(ptr, &end);
if (end == ptr) {
av_log(s, AV_LOG_WARNING, "malformed location metadata\n");
return 0;
}
ptr = end;
altitude = strtod(ptr, &end);
/* If no altitude was present, the default 0 should be fine */
if (*end == '/')
place = end + 1;
latitude_fix = (int32_t) ((1 << 16) * latitude);
longitude_fix = (int32_t) ((1 << 16) * longitude);
altitude_fix = (int32_t) ((1 << 16) * altitude);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "loci"); /* type */
avio_wb32(pb, 0); /* version + flags */
avio_wb16(pb, lang);
avio_write(pb, place, strlen(place) + 1);
avio_w8(pb, 0); /* role of place (0 == shooting location, 1 == real location, 2 == fictional location) */
avio_wb32(pb, latitude_fix);
avio_wb32(pb, longitude_fix);
avio_wb32(pb, altitude_fix);
avio_write(pb, astronomical_body, strlen(astronomical_body) + 1);
avio_w8(pb, 0); /* additional notes, null terminated string */
return update_size(pb, pos);
}
/* iTunes track or disc number */
static int mov_write_trkn_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s, int disc)
{
AVDictionaryEntry *t = av_dict_get(s->metadata,
disc ? "disc" : "track",
NULL, 0);
int size = 0, track = t ? atoi(t->value) : 0;
if (track) {
int tracks = 0;
char *slash = strchr(t->value, '/');
if (slash)
tracks = atoi(slash + 1);
avio_wb32(pb, 32); /* size */
ffio_wfourcc(pb, disc ? "disk" : "trkn");
avio_wb32(pb, 24); /* size */
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0); // 8 bytes empty
avio_wb32(pb, 0);
avio_wb16(pb, 0); // empty
avio_wb16(pb, track); // track / disc number
avio_wb16(pb, tracks); // total track / disc number
avio_wb16(pb, 0); // empty
size = 32;
}
return size;
}
static int mov_write_int8_metadata(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *tag,
int len)
{
AVDictionaryEntry *t = NULL;
uint8_t num;
int size = 24 + len;
if (len != 1 && len != 4)
return -1;
if (!(t = av_dict_get(s->metadata, tag, NULL, 0)))
return 0;
num = atoi(t->value);
avio_wb32(pb, size);
ffio_wfourcc(pb, name);
avio_wb32(pb, size - 8);
ffio_wfourcc(pb, "data");
avio_wb32(pb, 0x15);
avio_wb32(pb, 0);
if (len==4) avio_wb32(pb, num);
else avio_w8 (pb, num);
return size;
}
static int mov_write_covr(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int64_t pos = 0;
int i;
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
if (!is_cover_image(trk->st) || trk->cover_image.size <= 0)
continue;
if (!pos) {
pos = avio_tell(pb);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "covr");
}
avio_wb32(pb, 16 + trk->cover_image.size);
ffio_wfourcc(pb, "data");
avio_wb32(pb, trk->tag);
avio_wb32(pb , 0);
avio_write(pb, trk->cover_image.data, trk->cover_image.size);
}
return pos ? update_size(pb, pos) : 0;
}
/* iTunes meta data list */
static int mov_write_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ilst");
mov_write_string_metadata(s, pb, "\251nam", "title" , 1);
mov_write_string_metadata(s, pb, "\251ART", "artist" , 1);
mov_write_string_metadata(s, pb, "aART", "album_artist", 1);
mov_write_string_metadata(s, pb, "\251wrt", "composer" , 1);
mov_write_string_metadata(s, pb, "\251alb", "album" , 1);
mov_write_string_metadata(s, pb, "\251day", "date" , 1);
if (!mov_write_string_metadata(s, pb, "\251too", "encoding_tool", 1)) {
if (!(s->flags & AVFMT_FLAG_BITEXACT))
mov_write_string_tag(pb, "\251too", LIBAVFORMAT_IDENT, 0, 1);
}
mov_write_string_metadata(s, pb, "\251cmt", "comment" , 1);
mov_write_string_metadata(s, pb, "\251gen", "genre" , 1);
mov_write_string_metadata(s, pb, "cprt", "copyright", 1);
mov_write_string_metadata(s, pb, "\251grp", "grouping" , 1);
mov_write_string_metadata(s, pb, "\251lyr", "lyrics" , 1);
mov_write_string_metadata(s, pb, "desc", "description",1);
mov_write_string_metadata(s, pb, "ldes", "synopsis" , 1);
mov_write_string_metadata(s, pb, "tvsh", "show" , 1);
mov_write_string_metadata(s, pb, "tven", "episode_id",1);
mov_write_string_metadata(s, pb, "tvnn", "network" , 1);
mov_write_string_metadata(s, pb, "keyw", "keywords" , 1);
mov_write_int8_metadata (s, pb, "tves", "episode_sort",4);
mov_write_int8_metadata (s, pb, "tvsn", "season_number",4);
mov_write_int8_metadata (s, pb, "stik", "media_type",1);
mov_write_int8_metadata (s, pb, "hdvd", "hd_video", 1);
mov_write_int8_metadata (s, pb, "pgap", "gapless_playback",1);
mov_write_int8_metadata (s, pb, "cpil", "compilation", 1);
mov_write_covr(pb, s);
mov_write_trkn_tag(pb, mov, s, 0); // track number
mov_write_trkn_tag(pb, mov, s, 1); // disc number
mov_write_tmpo_tag(pb, s);
return update_size(pb, pos);
}
static int mov_write_mdta_hdlr_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
avio_wb32(pb, 33); /* size */
ffio_wfourcc(pb, "hdlr");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
ffio_wfourcc(pb, "mdta");
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_wb32(pb, 0);
avio_w8(pb, 0);
return 33;
}
static int mov_write_mdta_keys_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVDictionaryEntry *t = NULL;
int64_t pos = avio_tell(pb);
int64_t curpos, entry_pos;
int count = 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "keys");
avio_wb32(pb, 0);
entry_pos = avio_tell(pb);
avio_wb32(pb, 0); /* entry count */
while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
avio_wb32(pb, strlen(t->key) + 8);
ffio_wfourcc(pb, "mdta");
avio_write(pb, t->key, strlen(t->key));
count += 1;
}
curpos = avio_tell(pb);
avio_seek(pb, entry_pos, SEEK_SET);
avio_wb32(pb, count); // rewrite entry count
avio_seek(pb, curpos, SEEK_SET);
return update_size(pb, pos);
}
static int mov_write_mdta_ilst_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVDictionaryEntry *t = NULL;
int64_t pos = avio_tell(pb);
int count = 1; /* keys are 1-index based */
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ilst");
while (t = av_dict_get(s->metadata, "", t, AV_DICT_IGNORE_SUFFIX)) {
int64_t entry_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
avio_wb32(pb, count); /* key */
mov_write_string_data_tag(pb, t->value, 0, 1);
update_size(pb, entry_pos);
count += 1;
}
return update_size(pb, pos);
}
/* meta data tags */
static int mov_write_meta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int size = 0;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "meta");
avio_wb32(pb, 0);
if (mov->flags & FF_MOV_FLAG_USE_MDTA) {
mov_write_mdta_hdlr_tag(pb, mov, s);
mov_write_mdta_keys_tag(pb, mov, s);
mov_write_mdta_ilst_tag(pb, mov, s);
}
else {
/* iTunes metadata tag */
mov_write_itunes_hdlr_tag(pb, mov, s);
mov_write_ilst_tag(pb, mov, s);
}
size = update_size(pb, pos);
return size;
}
static int mov_write_raw_metadata_tag(AVFormatContext *s, AVIOContext *pb,
const char *name, const char *key)
{
int len;
AVDictionaryEntry *t;
if (!(t = av_dict_get(s->metadata, key, NULL, 0)))
return 0;
len = strlen(t->value);
if (len > 0) {
int size = len + 8;
avio_wb32(pb, size);
ffio_wfourcc(pb, name);
avio_write(pb, t->value, len);
return size;
}
return 0;
}
static int ascii_to_wc(AVIOContext *pb, const uint8_t *b)
{
int val;
while (*b) {
GET_UTF8(val, *b++, return -1;)
avio_wb16(pb, val);
}
avio_wb16(pb, 0x00);
return 0;
}
static uint16_t language_code(const char *str)
{
return (((str[0] - 0x60) & 0x1F) << 10) +
(((str[1] - 0x60) & 0x1F) << 5) +
(( str[2] - 0x60) & 0x1F);
}
static int mov_write_3gp_udta_tag(AVIOContext *pb, AVFormatContext *s,
const char *tag, const char *str)
{
int64_t pos = avio_tell(pb);
AVDictionaryEntry *t = av_dict_get(s->metadata, str, NULL, 0);
if (!t || !utf8len(t->value))
return 0;
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, tag); /* type */
avio_wb32(pb, 0); /* version + flags */
if (!strcmp(tag, "yrrc"))
avio_wb16(pb, atoi(t->value));
else {
avio_wb16(pb, language_code("eng")); /* language */
avio_write(pb, t->value, strlen(t->value) + 1); /* UTF8 string value */
if (!strcmp(tag, "albm") &&
(t = av_dict_get(s->metadata, "track", NULL, 0)))
avio_w8(pb, atoi(t->value));
}
return update_size(pb, pos);
}
static int mov_write_chpl_tag(AVIOContext *pb, AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
int i, nb_chapters = FFMIN(s->nb_chapters, 255);
avio_wb32(pb, 0); // size
ffio_wfourcc(pb, "chpl");
avio_wb32(pb, 0x01000000); // version + flags
avio_wb32(pb, 0); // unknown
avio_w8(pb, nb_chapters);
for (i = 0; i < nb_chapters; i++) {
AVChapter *c = s->chapters[i];
AVDictionaryEntry *t;
avio_wb64(pb, av_rescale_q(c->start, c->time_base, (AVRational){1,10000000}));
if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
int len = FFMIN(strlen(t->value), 255);
avio_w8(pb, len);
avio_write(pb, t->value, len);
} else
avio_w8(pb, 0);
}
return update_size(pb, pos);
}
static int mov_write_udta_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
AVIOContext *pb_buf;
int ret, size;
uint8_t *buf;
ret = avio_open_dyn_buf(&pb_buf);
if (ret < 0)
return ret;
if (mov->mode & MODE_3GP) {
mov_write_3gp_udta_tag(pb_buf, s, "perf", "artist");
mov_write_3gp_udta_tag(pb_buf, s, "titl", "title");
mov_write_3gp_udta_tag(pb_buf, s, "auth", "author");
mov_write_3gp_udta_tag(pb_buf, s, "gnre", "genre");
mov_write_3gp_udta_tag(pb_buf, s, "dscp", "comment");
mov_write_3gp_udta_tag(pb_buf, s, "albm", "album");
mov_write_3gp_udta_tag(pb_buf, s, "cprt", "copyright");
mov_write_3gp_udta_tag(pb_buf, s, "yrrc", "date");
mov_write_loci_tag(s, pb_buf);
} else if (mov->mode == MODE_MOV && !(mov->flags & FF_MOV_FLAG_USE_MDTA)) { // the title field breaks gtkpod with mp4 and my suspicion is that stuff is not valid in mp4
mov_write_string_metadata(s, pb_buf, "\251ART", "artist", 0);
mov_write_string_metadata(s, pb_buf, "\251nam", "title", 0);
mov_write_string_metadata(s, pb_buf, "\251aut", "author", 0);
mov_write_string_metadata(s, pb_buf, "\251alb", "album", 0);
mov_write_string_metadata(s, pb_buf, "\251day", "date", 0);
mov_write_string_metadata(s, pb_buf, "\251swr", "encoder", 0);
// currently ignored by mov.c
mov_write_string_metadata(s, pb_buf, "\251des", "comment", 0);
// add support for libquicktime, this atom is also actually read by mov.c
mov_write_string_metadata(s, pb_buf, "\251cmt", "comment", 0);
mov_write_string_metadata(s, pb_buf, "\251gen", "genre", 0);
mov_write_string_metadata(s, pb_buf, "\251cpy", "copyright", 0);
mov_write_string_metadata(s, pb_buf, "\251mak", "make", 0);
mov_write_string_metadata(s, pb_buf, "\251mod", "model", 0);
mov_write_string_metadata(s, pb_buf, "\251xyz", "location", 0);
mov_write_string_metadata(s, pb_buf, "\251key", "keywords", 0);
mov_write_raw_metadata_tag(s, pb_buf, "XMP_", "xmp");
} else {
/* iTunes meta data */
mov_write_meta_tag(pb_buf, mov, s);
mov_write_loci_tag(s, pb_buf);
}
if (s->nb_chapters && !(mov->flags & FF_MOV_FLAG_DISABLE_CHPL))
mov_write_chpl_tag(pb_buf, s);
if ((size = avio_close_dyn_buf(pb_buf, &buf)) > 0) {
avio_wb32(pb, size + 8);
ffio_wfourcc(pb, "udta");
avio_write(pb, buf, size);
}
av_free(buf);
return 0;
}
static void mov_write_psp_udta_tag(AVIOContext *pb,
const char *str, const char *lang, int type)
{
int len = utf8len(str) + 1;
if (len <= 0)
return;
avio_wb16(pb, len * 2 + 10); /* size */
avio_wb32(pb, type); /* type */
avio_wb16(pb, language_code(lang)); /* language */
avio_wb16(pb, 0x01); /* ? */
ascii_to_wc(pb, str);
}
static int mov_write_uuidusmt_tag(AVIOContext *pb, AVFormatContext *s)
{
AVDictionaryEntry *title = av_dict_get(s->metadata, "title", NULL, 0);
int64_t pos, pos2;
if (title) {
pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "USMT");
avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
pos2 = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "MTDT");
avio_wb16(pb, 4);
// ?
avio_wb16(pb, 0x0C); /* size */
avio_wb32(pb, 0x0B); /* type */
avio_wb16(pb, language_code("und")); /* language */
avio_wb16(pb, 0x0); /* ? */
avio_wb16(pb, 0x021C); /* data */
if (!(s->flags & AVFMT_FLAG_BITEXACT))
mov_write_psp_udta_tag(pb, LIBAVCODEC_IDENT, "eng", 0x04);
mov_write_psp_udta_tag(pb, title->value, "eng", 0x01);
mov_write_psp_udta_tag(pb, "2006/04/01 11:11:11", "und", 0x03);
update_size(pb, pos2);
return update_size(pb, pos);
}
return 0;
}
static void build_chunks(MOVTrack *trk)
{
int i;
MOVIentry *chunk = &trk->cluster[0];
uint64_t chunkSize = chunk->size;
chunk->chunkNum = 1;
if (trk->chunkCount)
return;
trk->chunkCount = 1;
for (i = 1; i<trk->entry; i++){
if (chunk->pos + chunkSize == trk->cluster[i].pos &&
chunkSize + trk->cluster[i].size < (1<<20)){
chunkSize += trk->cluster[i].size;
chunk->samples_in_chunk += trk->cluster[i].entries;
} else {
trk->cluster[i].chunkNum = chunk->chunkNum+1;
chunk=&trk->cluster[i];
chunkSize = chunk->size;
trk->chunkCount++;
}
}
}
/**
* Assign track ids. If option "use_stream_ids_as_track_ids" is set,
* the stream ids are used as track ids.
*
* This assumes mov->tracks and s->streams are in the same order and
* there are no gaps in either of them (so mov->tracks[n] refers to
* s->streams[n]).
*
* As an exception, there can be more entries in
* s->streams than in mov->tracks, in which case new track ids are
* generated (starting after the largest found stream id).
*/
static int mov_setup_track_ids(MOVMuxContext *mov, AVFormatContext *s)
{
int i;
if (mov->track_ids_ok)
return 0;
if (mov->use_stream_ids_as_track_ids) {
int next_generated_track_id = 0;
for (i = 0; i < s->nb_streams; i++) {
if (s->streams[i]->id > next_generated_track_id)
next_generated_track_id = s->streams[i]->id;
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].track_id = i >= s->nb_streams ? ++next_generated_track_id : s->streams[i]->id;
}
} else {
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].track_id = i + 1;
}
}
mov->track_ids_ok = 1;
return 0;
}
static int mov_write_moov_tag(AVIOContext *pb, MOVMuxContext *mov,
AVFormatContext *s)
{
int i;
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "moov");
mov_setup_track_ids(mov, s);
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry <= 0 && !(mov->flags & FF_MOV_FLAG_FRAGMENT))
continue;
mov->tracks[i].time = mov->time;
if (mov->tracks[i].entry)
build_chunks(&mov->tracks[i]);
}
if (mov->chapter_track)
for (i = 0; i < s->nb_streams; i++) {
mov->tracks[i].tref_tag = MKTAG('c','h','a','p');
mov->tracks[i].tref_id = mov->tracks[mov->chapter_track].track_id;
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->tag == MKTAG('r','t','p',' ')) {
track->tref_tag = MKTAG('h','i','n','t');
track->tref_id = mov->tracks[track->src_track].track_id;
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
int * fallback, size;
fallback = (int*)av_stream_get_side_data(track->st,
AV_PKT_DATA_FALLBACK_TRACK,
&size);
if (fallback != NULL && size == sizeof(int)) {
if (*fallback >= 0 && *fallback < mov->nb_streams) {
track->tref_tag = MKTAG('f','a','l','l');
track->tref_id = mov->tracks[*fallback].track_id;
}
}
}
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].tag == MKTAG('t','m','c','d')) {
int src_trk = mov->tracks[i].src_track;
mov->tracks[src_trk].tref_tag = mov->tracks[i].tag;
mov->tracks[src_trk].tref_id = mov->tracks[i].track_id;
//src_trk may have a different timescale than the tmcd track
mov->tracks[i].track_duration = av_rescale(mov->tracks[src_trk].track_duration,
mov->tracks[i].timescale,
mov->tracks[src_trk].timescale);
}
}
mov_write_mvhd_tag(pb, mov);
if (mov->mode != MODE_MOV && !mov->iods_skip)
mov_write_iods_tag(pb, mov);
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry > 0 || mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret = mov_write_trak_tag(s, pb, mov, &(mov->tracks[i]), i < s->nb_streams ? s->streams[i] : NULL);
if (ret < 0)
return ret;
}
}
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
mov_write_mvex_tag(pb, mov); /* QuickTime requires trak to precede this */
if (mov->mode == MODE_PSP)
mov_write_uuidusmt_tag(pb, s);
else
mov_write_udta_tag(pb, mov, s);
return update_size(pb, pos);
}
static void param_write_int(AVIOContext *pb, const char *name, int value)
{
avio_printf(pb, "<param name=\"%s\" value=\"%d\" valuetype=\"data\"/>\n", name, value);
}
static void param_write_string(AVIOContext *pb, const char *name, const char *value)
{
avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, value);
}
static void param_write_hex(AVIOContext *pb, const char *name, const uint8_t *value, int len)
{
char buf[150];
len = FFMIN(sizeof(buf) / 2 - 1, len);
ff_data_to_hex(buf, value, len, 0);
buf[2 * len] = '\0';
avio_printf(pb, "<param name=\"%s\" value=\"%s\" valuetype=\"data\"/>\n", name, buf);
}
static int mov_write_isml_manifest(AVIOContext *pb, MOVMuxContext *mov, AVFormatContext *s)
{
int64_t pos = avio_tell(pb);
int i;
int64_t manifest_bit_rate = 0;
AVCPBProperties *props = NULL;
static const uint8_t uuid[] = {
0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd,
0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66
};
avio_wb32(pb, 0);
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_wb32(pb, 0);
avio_printf(pb, "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
avio_printf(pb, "<smil xmlns=\"http://www.w3.org/2001/SMIL20/Language\">\n");
avio_printf(pb, "<head>\n");
if (!(mov->fc->flags & AVFMT_FLAG_BITEXACT))
avio_printf(pb, "<meta name=\"creator\" content=\"%s\" />\n",
LIBAVFORMAT_IDENT);
avio_printf(pb, "</head>\n");
avio_printf(pb, "<body>\n");
avio_printf(pb, "<switch>\n");
mov_setup_track_ids(mov, s);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
const char *type;
int track_id = track->track_id;
char track_name_buf[32] = { 0 };
AVStream *st = track->st;
AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO && !is_cover_image(st)) {
type = "video";
} else if (track->par->codec_type == AVMEDIA_TYPE_AUDIO) {
type = "audio";
} else {
continue;
}
props = (AVCPBProperties*)av_stream_get_side_data(track->st, AV_PKT_DATA_CPB_PROPERTIES, NULL);
if (track->par->bit_rate) {
manifest_bit_rate = track->par->bit_rate;
} else if (props) {
manifest_bit_rate = props->max_bitrate;
}
avio_printf(pb, "<%s systemBitrate=\"%"PRId64"\">\n", type,
manifest_bit_rate);
param_write_int(pb, "systemBitrate", manifest_bit_rate);
param_write_int(pb, "trackID", track_id);
param_write_string(pb, "systemLanguage", lang ? lang->value : "und");
/* Build track name piece by piece: */
/* 1. track type */
av_strlcat(track_name_buf, type, sizeof(track_name_buf));
/* 2. track language, if available */
if (lang)
av_strlcatf(track_name_buf, sizeof(track_name_buf),
"_%s", lang->value);
/* 3. special type suffix */
/* "_cc" = closed captions, "_ad" = audio_description */
if (st->disposition & AV_DISPOSITION_HEARING_IMPAIRED)
av_strlcat(track_name_buf, "_cc", sizeof(track_name_buf));
else if (st->disposition & AV_DISPOSITION_VISUAL_IMPAIRED)
av_strlcat(track_name_buf, "_ad", sizeof(track_name_buf));
param_write_string(pb, "trackName", track_name_buf);
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
if (track->par->codec_id == AV_CODEC_ID_H264) {
uint8_t *ptr;
int size = track->par->extradata_size;
if (!ff_avc_write_annexb_extradata(track->par->extradata, &ptr,
&size)) {
param_write_hex(pb, "CodecPrivateData",
ptr ? ptr : track->par->extradata,
size);
av_free(ptr);
}
param_write_string(pb, "FourCC", "H264");
} else if (track->par->codec_id == AV_CODEC_ID_VC1) {
param_write_string(pb, "FourCC", "WVC1");
param_write_hex(pb, "CodecPrivateData", track->par->extradata,
track->par->extradata_size);
}
param_write_int(pb, "MaxWidth", track->par->width);
param_write_int(pb, "MaxHeight", track->par->height);
param_write_int(pb, "DisplayWidth", track->par->width);
param_write_int(pb, "DisplayHeight", track->par->height);
} else {
if (track->par->codec_id == AV_CODEC_ID_AAC) {
switch (track->par->profile)
{
case FF_PROFILE_AAC_HE_V2:
param_write_string(pb, "FourCC", "AACP");
break;
case FF_PROFILE_AAC_HE:
param_write_string(pb, "FourCC", "AACH");
break;
default:
param_write_string(pb, "FourCC", "AACL");
}
} else if (track->par->codec_id == AV_CODEC_ID_WMAPRO) {
param_write_string(pb, "FourCC", "WMAP");
}
param_write_hex(pb, "CodecPrivateData", track->par->extradata,
track->par->extradata_size);
param_write_int(pb, "AudioTag", ff_codec_get_tag(ff_codec_wav_tags,
track->par->codec_id));
param_write_int(pb, "Channels", track->par->channels);
param_write_int(pb, "SamplingRate", track->par->sample_rate);
param_write_int(pb, "BitsPerSample", 16);
param_write_int(pb, "PacketSize", track->par->block_align ?
track->par->block_align : 4);
}
avio_printf(pb, "</%s>\n", type);
}
avio_printf(pb, "</switch>\n");
avio_printf(pb, "</body>\n");
avio_printf(pb, "</smil>\n");
return update_size(pb, pos);
}
static int mov_write_mfhd_tag(AVIOContext *pb, MOVMuxContext *mov)
{
avio_wb32(pb, 16);
ffio_wfourcc(pb, "mfhd");
avio_wb32(pb, 0);
avio_wb32(pb, mov->fragments);
return 0;
}
static uint32_t get_sample_flags(MOVTrack *track, MOVIentry *entry)
{
return entry->flags & MOV_SYNC_SAMPLE ? MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO :
(MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC);
}
static int mov_write_tfhd_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int64_t moof_offset)
{
int64_t pos = avio_tell(pb);
uint32_t flags = MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
MOV_TFHD_BASE_DATA_OFFSET;
if (!track->entry) {
flags |= MOV_TFHD_DURATION_IS_EMPTY;
} else {
flags |= MOV_TFHD_DEFAULT_FLAGS;
}
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET)
flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
if (mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) {
flags &= ~MOV_TFHD_BASE_DATA_OFFSET;
flags |= MOV_TFHD_DEFAULT_BASE_IS_MOOF;
}
/* Don't set a default sample size, the silverlight player refuses
* to play files with that set. Don't set a default sample duration,
* WMP freaks out if it is set. Don't set a base data offset, PIFF
* file format says it MUST NOT be set. */
if (track->mode == MODE_ISM)
flags &= ~(MOV_TFHD_DEFAULT_SIZE | MOV_TFHD_DEFAULT_DURATION |
MOV_TFHD_BASE_DATA_OFFSET);
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "tfhd");
avio_w8(pb, 0); /* version */
avio_wb24(pb, flags);
avio_wb32(pb, track->track_id); /* track-id */
if (flags & MOV_TFHD_BASE_DATA_OFFSET)
avio_wb64(pb, moof_offset);
if (flags & MOV_TFHD_DEFAULT_DURATION) {
track->default_duration = get_cluster_duration(track, 0);
avio_wb32(pb, track->default_duration);
}
if (flags & MOV_TFHD_DEFAULT_SIZE) {
track->default_size = track->entry ? track->cluster[0].size : 1;
avio_wb32(pb, track->default_size);
} else
track->default_size = -1;
if (flags & MOV_TFHD_DEFAULT_FLAGS) {
/* Set the default flags based on the second sample, if available.
* If the first sample is different, that can be signaled via a separate field. */
if (track->entry > 1)
track->default_sample_flags = get_sample_flags(track, &track->cluster[1]);
else
track->default_sample_flags =
track->par->codec_type == AVMEDIA_TYPE_VIDEO ?
(MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES | MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC) :
MOV_FRAG_SAMPLE_FLAG_DEPENDS_NO;
avio_wb32(pb, track->default_sample_flags);
}
return update_size(pb, pos);
}
static int mov_write_trun_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int moof_size,
int first, int end)
{
int64_t pos = avio_tell(pb);
uint32_t flags = MOV_TRUN_DATA_OFFSET;
int i;
for (i = first; i < end; i++) {
if (get_cluster_duration(track, i) != track->default_duration)
flags |= MOV_TRUN_SAMPLE_DURATION;
if (track->cluster[i].size != track->default_size)
flags |= MOV_TRUN_SAMPLE_SIZE;
if (i > first && get_sample_flags(track, &track->cluster[i]) != track->default_sample_flags)
flags |= MOV_TRUN_SAMPLE_FLAGS;
}
if (!(flags & MOV_TRUN_SAMPLE_FLAGS) && track->entry > 0 &&
get_sample_flags(track, &track->cluster[0]) != track->default_sample_flags)
flags |= MOV_TRUN_FIRST_SAMPLE_FLAGS;
if (track->flags & MOV_TRACK_CTTS)
flags |= MOV_TRUN_SAMPLE_CTS;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "trun");
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
avio_w8(pb, 1); /* version */
else
avio_w8(pb, 0); /* version */
avio_wb24(pb, flags);
avio_wb32(pb, end - first); /* sample count */
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF) &&
!mov->first_trun)
avio_wb32(pb, 0); /* Later tracks follow immediately after the previous one */
else
avio_wb32(pb, moof_size + 8 + track->data_offset +
track->cluster[first].pos); /* data offset */
if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS)
avio_wb32(pb, get_sample_flags(track, &track->cluster[first]));
for (i = first; i < end; i++) {
if (flags & MOV_TRUN_SAMPLE_DURATION)
avio_wb32(pb, get_cluster_duration(track, i));
if (flags & MOV_TRUN_SAMPLE_SIZE)
avio_wb32(pb, track->cluster[i].size);
if (flags & MOV_TRUN_SAMPLE_FLAGS)
avio_wb32(pb, get_sample_flags(track, &track->cluster[i]));
if (flags & MOV_TRUN_SAMPLE_CTS)
avio_wb32(pb, track->cluster[i].cts);
}
mov->first_trun = 0;
return update_size(pb, pos);
}
static int mov_write_tfxd_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
static const uint8_t uuid[] = {
0x6d, 0x1d, 0x9b, 0x05, 0x42, 0xd5, 0x44, 0xe6,
0x80, 0xe2, 0x14, 0x1d, 0xaf, 0xf7, 0x57, 0xb2
};
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_w8(pb, 1);
avio_wb24(pb, 0);
avio_wb64(pb, track->start_dts + track->frag_start +
track->cluster[0].cts);
avio_wb64(pb, track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts));
return update_size(pb, pos);
}
static int mov_write_tfrf_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int entry)
{
int n = track->nb_frag_info - 1 - entry, i;
int size = 8 + 16 + 4 + 1 + 16*n;
static const uint8_t uuid[] = {
0xd4, 0x80, 0x7e, 0xf2, 0xca, 0x39, 0x46, 0x95,
0x8e, 0x54, 0x26, 0xcb, 0x9e, 0x46, 0xa7, 0x9f
};
if (entry < 0)
return 0;
avio_seek(pb, track->frag_info[entry].tfrf_offset, SEEK_SET);
avio_wb32(pb, size);
ffio_wfourcc(pb, "uuid");
avio_write(pb, uuid, sizeof(uuid));
avio_w8(pb, 1);
avio_wb24(pb, 0);
avio_w8(pb, n);
for (i = 0; i < n; i++) {
int index = entry + 1 + i;
avio_wb64(pb, track->frag_info[index].time);
avio_wb64(pb, track->frag_info[index].duration);
}
if (n < mov->ism_lookahead) {
int free_size = 16 * (mov->ism_lookahead - n);
avio_wb32(pb, free_size);
ffio_wfourcc(pb, "free");
ffio_fill(pb, 0, free_size - 8);
}
return 0;
}
static int mov_write_tfrf_tags(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int i;
for (i = 0; i < mov->ism_lookahead; i++) {
/* Update the tfrf tag for the last ism_lookahead fragments,
* nb_frag_info - 1 is the next fragment to be written. */
mov_write_tfrf_tag(pb, mov, track, track->nb_frag_info - 2 - i);
}
avio_seek(pb, pos, SEEK_SET);
return 0;
}
static int mov_add_tfra_entries(AVIOContext *pb, MOVMuxContext *mov, int tracks,
int size)
{
int i;
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
MOVFragmentInfo *info;
if ((tracks >= 0 && i != tracks) || !track->entry)
continue;
track->nb_frag_info++;
if (track->nb_frag_info >= track->frag_info_capacity) {
unsigned new_capacity = track->nb_frag_info + MOV_FRAG_INFO_ALLOC_INCREMENT;
if (av_reallocp_array(&track->frag_info,
new_capacity,
sizeof(*track->frag_info)))
return AVERROR(ENOMEM);
track->frag_info_capacity = new_capacity;
}
info = &track->frag_info[track->nb_frag_info - 1];
info->offset = avio_tell(pb);
info->size = size;
// Try to recreate the original pts for the first packet
// from the fields we have stored
info->time = track->start_dts + track->frag_start +
track->cluster[0].cts;
info->duration = track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts);
// If the pts is less than zero, we will have trimmed
// away parts of the media track using an edit list,
// and the corresponding start presentation time is zero.
if (info->time < 0) {
info->duration += info->time;
info->time = 0;
}
info->tfrf_offset = 0;
mov_write_tfrf_tags(pb, mov, track);
}
return 0;
}
static void mov_prune_frag_info(MOVMuxContext *mov, int tracks, int max)
{
int i;
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if ((tracks >= 0 && i != tracks) || !track->entry)
continue;
if (track->nb_frag_info > max) {
memmove(track->frag_info, track->frag_info + (track->nb_frag_info - max), max * sizeof(*track->frag_info));
track->nb_frag_info = max;
}
}
}
static int mov_write_tfdt_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "tfdt");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb64(pb, track->frag_start);
return update_size(pb, pos);
}
static int mov_write_traf_tag(AVIOContext *pb, MOVMuxContext *mov,
MOVTrack *track, int64_t moof_offset,
int moof_size)
{
int64_t pos = avio_tell(pb);
int i, start = 0;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "traf");
mov_write_tfhd_tag(pb, mov, track, moof_offset);
if (mov->mode != MODE_ISM)
mov_write_tfdt_tag(pb, track);
for (i = 1; i < track->entry; i++) {
if (track->cluster[i].pos != track->cluster[i - 1].pos + track->cluster[i - 1].size) {
mov_write_trun_tag(pb, mov, track, moof_size, start, i);
start = i;
}
}
mov_write_trun_tag(pb, mov, track, moof_size, start, track->entry);
if (mov->mode == MODE_ISM) {
mov_write_tfxd_tag(pb, track);
if (mov->ism_lookahead) {
int i, size = 16 + 4 + 1 + 16 * mov->ism_lookahead;
if (track->nb_frag_info > 0) {
MOVFragmentInfo *info = &track->frag_info[track->nb_frag_info - 1];
if (!info->tfrf_offset)
info->tfrf_offset = avio_tell(pb);
}
avio_wb32(pb, 8 + size);
ffio_wfourcc(pb, "free");
for (i = 0; i < size; i++)
avio_w8(pb, 0);
}
}
return update_size(pb, pos);
}
static int mov_write_moof_tag_internal(AVIOContext *pb, MOVMuxContext *mov,
int tracks, int moof_size)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "moof");
mov->first_trun = 1;
mov_write_mfhd_tag(pb, mov);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (tracks >= 0 && i != tracks)
continue;
if (!track->entry)
continue;
mov_write_traf_tag(pb, mov, track, pos, moof_size);
}
return update_size(pb, pos);
}
static int mov_write_sidx_tag(AVIOContext *pb,
MOVTrack *track, int ref_size, int total_sidx_size)
{
int64_t pos = avio_tell(pb), offset_pos, end_pos;
int64_t presentation_time, duration, offset;
int starts_with_SAP, i, entries;
if (track->entry) {
entries = 1;
presentation_time = track->start_dts + track->frag_start +
track->cluster[0].cts;
duration = track->end_pts -
(track->cluster[0].dts + track->cluster[0].cts);
starts_with_SAP = track->cluster[0].flags & MOV_SYNC_SAMPLE;
// pts<0 should be cut away using edts
if (presentation_time < 0) {
duration += presentation_time;
presentation_time = 0;
}
} else {
entries = track->nb_frag_info;
if (entries <= 0)
return 0;
presentation_time = track->frag_info[0].time;
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "sidx");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb32(pb, track->track_id); /* reference_ID */
avio_wb32(pb, track->timescale); /* timescale */
avio_wb64(pb, presentation_time); /* earliest_presentation_time */
offset_pos = avio_tell(pb);
avio_wb64(pb, 0); /* first_offset (offset to referenced moof) */
avio_wb16(pb, 0); /* reserved */
avio_wb16(pb, entries); /* reference_count */
for (i = 0; i < entries; i++) {
if (!track->entry) {
if (i > 1 && track->frag_info[i].offset != track->frag_info[i - 1].offset + track->frag_info[i - 1].size) {
av_log(NULL, AV_LOG_ERROR, "Non-consecutive fragments, writing incorrect sidx\n");
}
duration = track->frag_info[i].duration;
ref_size = track->frag_info[i].size;
starts_with_SAP = 1;
}
avio_wb32(pb, (0 << 31) | (ref_size & 0x7fffffff)); /* reference_type (0 = media) | referenced_size */
avio_wb32(pb, duration); /* subsegment_duration */
avio_wb32(pb, (starts_with_SAP << 31) | (0 << 28) | 0); /* starts_with_SAP | SAP_type | SAP_delta_time */
}
end_pos = avio_tell(pb);
offset = pos + total_sidx_size - end_pos;
avio_seek(pb, offset_pos, SEEK_SET);
avio_wb64(pb, offset);
avio_seek(pb, end_pos, SEEK_SET);
return update_size(pb, pos);
}
static int mov_write_sidx_tags(AVIOContext *pb, MOVMuxContext *mov,
int tracks, int ref_size)
{
int i, round, ret;
AVIOContext *avio_buf;
int total_size = 0;
for (round = 0; round < 2; round++) {
// First run one round to calculate the total size of all
// sidx atoms.
// This would be much simpler if we'd only write one sidx
// atom, for the first track in the moof.
if (round == 0) {
if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
return ret;
} else {
avio_buf = pb;
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (tracks >= 0 && i != tracks)
continue;
// When writing a sidx for the full file, entry is 0, but
// we want to include all tracks. ref_size is 0 in this case,
// since we read it from frag_info instead.
if (!track->entry && ref_size > 0)
continue;
total_size -= mov_write_sidx_tag(avio_buf, track, ref_size,
total_size);
}
if (round == 0)
total_size = ffio_close_null_buf(avio_buf);
}
return 0;
}
static int mov_write_prft_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks)
{
int64_t pos = avio_tell(pb), pts_us, ntp_ts;
MOVTrack *first_track;
/* PRFT should be associated with at most one track. So, choosing only the
* first track. */
if (tracks > 0)
return 0;
first_track = &(mov->tracks[0]);
if (!first_track->entry) {
av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, no entries in the track\n");
return 0;
}
if (first_track->cluster[0].pts == AV_NOPTS_VALUE) {
av_log(mov->fc, AV_LOG_WARNING, "Unable to write PRFT, first PTS is invalid\n");
return 0;
}
if (mov->write_prft == MOV_PRFT_SRC_WALLCLOCK) {
ntp_ts = ff_get_formatted_ntp_time(ff_ntp_time());
} else if (mov->write_prft == MOV_PRFT_SRC_PTS) {
pts_us = av_rescale_q(first_track->cluster[0].pts,
first_track->st->time_base, AV_TIME_BASE_Q);
ntp_ts = ff_get_formatted_ntp_time(pts_us + NTP_OFFSET_US);
} else {
av_log(mov->fc, AV_LOG_WARNING, "Unsupported PRFT box configuration: %d\n",
mov->write_prft);
return 0;
}
avio_wb32(pb, 0); // Size place holder
ffio_wfourcc(pb, "prft"); // Type
avio_w8(pb, 1); // Version
avio_wb24(pb, 0); // Flags
avio_wb32(pb, first_track->track_id); // reference track ID
avio_wb64(pb, ntp_ts); // NTP time stamp
avio_wb64(pb, first_track->cluster[0].pts); //media time
return update_size(pb, pos);
}
static int mov_write_moof_tag(AVIOContext *pb, MOVMuxContext *mov, int tracks,
int64_t mdat_size)
{
AVIOContext *avio_buf;
int ret, moof_size;
if ((ret = ffio_open_null_buf(&avio_buf)) < 0)
return ret;
mov_write_moof_tag_internal(avio_buf, mov, tracks, 0);
moof_size = ffio_close_null_buf(avio_buf);
if (mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX))
mov_write_sidx_tags(pb, mov, tracks, moof_size + 8 + mdat_size);
if (mov->write_prft > MOV_PRFT_NONE && mov->write_prft < MOV_PRFT_NB)
mov_write_prft_tag(pb, mov, tracks);
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX ||
!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER) ||
mov->ism_lookahead) {
if ((ret = mov_add_tfra_entries(pb, mov, tracks, moof_size + 8 + mdat_size)) < 0)
return ret;
if (!(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) &&
mov->flags & FF_MOV_FLAG_SKIP_TRAILER) {
mov_prune_frag_info(mov, tracks, mov->ism_lookahead + 1);
}
}
return mov_write_moof_tag_internal(pb, mov, tracks, moof_size);
}
static int mov_write_tfra_tag(AVIOContext *pb, MOVTrack *track)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "tfra");
avio_w8(pb, 1); /* version */
avio_wb24(pb, 0);
avio_wb32(pb, track->track_id);
avio_wb32(pb, 0); /* length of traf/trun/sample num */
avio_wb32(pb, track->nb_frag_info);
for (i = 0; i < track->nb_frag_info; i++) {
avio_wb64(pb, track->frag_info[i].time);
avio_wb64(pb, track->frag_info[i].offset + track->data_offset);
avio_w8(pb, 1); /* traf number */
avio_w8(pb, 1); /* trun number */
avio_w8(pb, 1); /* sample number */
}
return update_size(pb, pos);
}
static int mov_write_mfra_tag(AVIOContext *pb, MOVMuxContext *mov)
{
int64_t pos = avio_tell(pb);
int i;
avio_wb32(pb, 0); /* size placeholder */
ffio_wfourcc(pb, "mfra");
/* An empty mfra atom is enough to indicate to the publishing point that
* the stream has ended. */
if (mov->flags & FF_MOV_FLAG_ISML)
return update_size(pb, pos);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->nb_frag_info)
mov_write_tfra_tag(pb, track);
}
avio_wb32(pb, 16);
ffio_wfourcc(pb, "mfro");
avio_wb32(pb, 0); /* version + flags */
avio_wb32(pb, avio_tell(pb) + 4 - pos);
return update_size(pb, pos);
}
static int mov_write_mdat_tag(AVIOContext *pb, MOVMuxContext *mov)
{
avio_wb32(pb, 8); // placeholder for extended size field (64 bit)
ffio_wfourcc(pb, mov->mode == MODE_MOV ? "wide" : "free");
mov->mdat_pos = avio_tell(pb);
avio_wb32(pb, 0); /* size placeholder*/
ffio_wfourcc(pb, "mdat");
return 0;
}
/* TODO: This needs to be more general */
static int mov_write_ftyp_tag(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int64_t pos = avio_tell(pb);
int has_h264 = 0, has_video = 0;
int minor = 0x200;
int i;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (is_cover_image(st))
continue;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
has_video = 1;
if (st->codecpar->codec_id == AV_CODEC_ID_H264)
has_h264 = 1;
}
avio_wb32(pb, 0); /* size */
ffio_wfourcc(pb, "ftyp");
if (mov->major_brand && strlen(mov->major_brand) >= 4)
ffio_wfourcc(pb, mov->major_brand);
else if (mov->mode == MODE_3GP) {
ffio_wfourcc(pb, has_h264 ? "3gp6" : "3gp4");
minor = has_h264 ? 0x100 : 0x200;
} else if (mov->mode & MODE_3G2) {
ffio_wfourcc(pb, has_h264 ? "3g2b" : "3g2a");
minor = has_h264 ? 0x20000 : 0x10000;
} else if (mov->mode == MODE_PSP)
ffio_wfourcc(pb, "MSNV");
else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
ffio_wfourcc(pb, "iso5"); // Required when using default-base-is-moof
else if (mov->mode == MODE_MP4 && mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS)
ffio_wfourcc(pb, "iso4");
else if (mov->mode == MODE_MP4)
ffio_wfourcc(pb, "isom");
else if (mov->mode == MODE_IPOD)
ffio_wfourcc(pb, has_video ? "M4V ":"M4A ");
else if (mov->mode == MODE_ISM)
ffio_wfourcc(pb, "isml");
else if (mov->mode == MODE_F4V)
ffio_wfourcc(pb, "f4v ");
else
ffio_wfourcc(pb, "qt ");
avio_wb32(pb, minor);
if (mov->mode == MODE_MOV)
ffio_wfourcc(pb, "qt ");
else if (mov->mode == MODE_ISM) {
ffio_wfourcc(pb, "piff");
} else if (!(mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)) {
ffio_wfourcc(pb, "isom");
ffio_wfourcc(pb, "iso2");
if (has_h264)
ffio_wfourcc(pb, "avc1");
}
// We add tfdt atoms when fragmenting, signal this with the iso6 compatible
// brand. This is compatible with users that don't understand tfdt.
if (mov->flags & FF_MOV_FLAG_FRAGMENT && mov->mode != MODE_ISM)
ffio_wfourcc(pb, "iso6");
if (mov->mode == MODE_3GP)
ffio_wfourcc(pb, has_h264 ? "3gp6":"3gp4");
else if (mov->mode & MODE_3G2)
ffio_wfourcc(pb, has_h264 ? "3g2b":"3g2a");
else if (mov->mode == MODE_PSP)
ffio_wfourcc(pb, "MSNV");
else if (mov->mode == MODE_MP4)
ffio_wfourcc(pb, "mp41");
if (mov->flags & FF_MOV_FLAG_DASH && mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
ffio_wfourcc(pb, "dash");
return update_size(pb, pos);
}
static int mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)
{
AVStream *video_st = s->streams[0];
AVCodecParameters *video_par = s->streams[0]->codecpar;
AVCodecParameters *audio_par = s->streams[1]->codecpar;
int audio_rate = audio_par->sample_rate;
int64_t frame_rate = video_st->avg_frame_rate.den ?
(video_st->avg_frame_rate.num * 0x10000LL) / video_st->avg_frame_rate.den :
0;
int audio_kbitrate = audio_par->bit_rate / 1000;
int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);
if (frame_rate < 0 || frame_rate > INT32_MAX) {
av_log(s, AV_LOG_ERROR, "Frame rate %f outside supported range\n", frame_rate / (double)0x10000);
return AVERROR(EINVAL);
}
avio_wb32(pb, 0x94); /* size */
ffio_wfourcc(pb, "uuid");
ffio_wfourcc(pb, "PROF");
avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */
avio_wb32(pb, 0xbb88695c);
avio_wb32(pb, 0xfac9c740);
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x3); /* 3 sections ? */
avio_wb32(pb, 0x14); /* size */
ffio_wfourcc(pb, "FPRF");
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x0); /* ? */
avio_wb32(pb, 0x2c); /* size */
ffio_wfourcc(pb, "APRF"); /* audio */
avio_wb32(pb, 0x0);
avio_wb32(pb, 0x2); /* TrackID */
ffio_wfourcc(pb, "mp4a");
avio_wb32(pb, 0x20f);
avio_wb32(pb, 0x0);
avio_wb32(pb, audio_kbitrate);
avio_wb32(pb, audio_kbitrate);
avio_wb32(pb, audio_rate);
avio_wb32(pb, audio_par->channels);
avio_wb32(pb, 0x34); /* size */
ffio_wfourcc(pb, "VPRF"); /* video */
avio_wb32(pb, 0x0);
avio_wb32(pb, 0x1); /* TrackID */
if (video_par->codec_id == AV_CODEC_ID_H264) {
ffio_wfourcc(pb, "avc1");
avio_wb16(pb, 0x014D);
avio_wb16(pb, 0x0015);
} else {
ffio_wfourcc(pb, "mp4v");
avio_wb16(pb, 0x0000);
avio_wb16(pb, 0x0103);
}
avio_wb32(pb, 0x0);
avio_wb32(pb, video_kbitrate);
avio_wb32(pb, video_kbitrate);
avio_wb32(pb, frame_rate);
avio_wb32(pb, frame_rate);
avio_wb16(pb, video_par->width);
avio_wb16(pb, video_par->height);
avio_wb32(pb, 0x010001); /* ? */
return 0;
}
static int mov_write_identification(AVIOContext *pb, AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
mov_write_ftyp_tag(pb,s);
if (mov->mode == MODE_PSP) {
int video_streams_nb = 0, audio_streams_nb = 0, other_streams_nb = 0;
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (is_cover_image(st))
continue;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
video_streams_nb++;
else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
audio_streams_nb++;
else
other_streams_nb++;
}
if (video_streams_nb != 1 || audio_streams_nb != 1 || other_streams_nb) {
av_log(s, AV_LOG_ERROR, "PSP mode need one video and one audio stream\n");
return AVERROR(EINVAL);
}
return mov_write_uuidprof_tag(pb, s);
}
return 0;
}
static int mov_parse_mpeg2_frame(AVPacket *pkt, uint32_t *flags)
{
uint32_t c = -1;
int i, closed_gop = 0;
for (i = 0; i < pkt->size - 4; i++) {
c = (c << 8) + pkt->data[i];
if (c == 0x1b8) { // gop
closed_gop = pkt->data[i + 4] >> 6 & 0x01;
} else if (c == 0x100) { // pic
int temp_ref = (pkt->data[i + 1] << 2) | (pkt->data[i + 2] >> 6);
if (!temp_ref || closed_gop) // I picture is not reordered
*flags = MOV_SYNC_SAMPLE;
else
*flags = MOV_PARTIAL_SYNC_SAMPLE;
break;
}
}
return 0;
}
static void mov_parse_vc1_frame(AVPacket *pkt, MOVTrack *trk)
{
const uint8_t *start, *next, *end = pkt->data + pkt->size;
int seq = 0, entry = 0;
int key = pkt->flags & AV_PKT_FLAG_KEY;
start = find_next_marker(pkt->data, end);
for (next = start; next < end; start = next) {
next = find_next_marker(start + 4, end);
switch (AV_RB32(start)) {
case VC1_CODE_SEQHDR:
seq = 1;
break;
case VC1_CODE_ENTRYPOINT:
entry = 1;
break;
case VC1_CODE_SLICE:
trk->vc1_info.slices = 1;
break;
}
}
if (!trk->entry && trk->vc1_info.first_packet_seen)
trk->vc1_info.first_frag_written = 1;
if (!trk->entry && !trk->vc1_info.first_frag_written) {
/* First packet in first fragment */
trk->vc1_info.first_packet_seq = seq;
trk->vc1_info.first_packet_entry = entry;
trk->vc1_info.first_packet_seen = 1;
} else if ((seq && !trk->vc1_info.packet_seq) ||
(entry && !trk->vc1_info.packet_entry)) {
int i;
for (i = 0; i < trk->entry; i++)
trk->cluster[i].flags &= ~MOV_SYNC_SAMPLE;
trk->has_keyframes = 0;
if (seq)
trk->vc1_info.packet_seq = 1;
if (entry)
trk->vc1_info.packet_entry = 1;
if (!trk->vc1_info.first_frag_written) {
/* First fragment */
if ((!seq || trk->vc1_info.first_packet_seq) &&
(!entry || trk->vc1_info.first_packet_entry)) {
/* First packet had the same headers as this one, readd the
* sync sample flag. */
trk->cluster[0].flags |= MOV_SYNC_SAMPLE;
trk->has_keyframes = 1;
}
}
}
if (trk->vc1_info.packet_seq && trk->vc1_info.packet_entry)
key = seq && entry;
else if (trk->vc1_info.packet_seq)
key = seq;
else if (trk->vc1_info.packet_entry)
key = entry;
if (key) {
trk->cluster[trk->entry].flags |= MOV_SYNC_SAMPLE;
trk->has_keyframes++;
}
}
static int mov_flush_fragment_interleaving(AVFormatContext *s, MOVTrack *track)
{
MOVMuxContext *mov = s->priv_data;
int ret, buf_size;
uint8_t *buf;
int i, offset;
if (!track->mdat_buf)
return 0;
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
track->mdat_buf = NULL;
offset = avio_tell(mov->mdat_buf);
avio_write(mov->mdat_buf, buf, buf_size);
av_free(buf);
for (i = track->entries_flushed; i < track->entry; i++)
track->cluster[i].pos += offset;
track->entries_flushed = track->entry;
return 0;
}
static int mov_flush_fragment(AVFormatContext *s, int force)
{
MOVMuxContext *mov = s->priv_data;
int i, first_track = -1;
int64_t mdat_size = 0;
int ret;
int has_video = 0, starts_with_key = 0, first_video_track = 1;
if (!(mov->flags & FF_MOV_FLAG_FRAGMENT))
return 0;
// Try to fill in the duration of the last packet in each stream
// from queued packets in the interleave queues. If the flushing
// of fragments was triggered automatically by an AVPacket, we
// already have reliable info for the end of that track, but other
// tracks may need to be filled in.
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (!track->end_reliable) {
AVPacket pkt;
if (!ff_interleaved_peek(s, i, &pkt, 1)) {
if (track->dts_shift != AV_NOPTS_VALUE)
pkt.dts += track->dts_shift;
track->track_duration = pkt.dts - track->start_dts;
if (pkt.pts != AV_NOPTS_VALUE)
track->end_pts = pkt.pts;
else
track->end_pts = pkt.dts;
}
}
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (track->entry <= 1)
continue;
// Sample durations are calculated as the diff of dts values,
// but for the last sample in a fragment, we don't know the dts
// of the first sample in the next fragment, so we have to rely
// on what was set as duration in the AVPacket. Not all callers
// set this though, so we might want to replace it with an
// estimate if it currently is zero.
if (get_cluster_duration(track, track->entry - 1) != 0)
continue;
// Use the duration (i.e. dts diff) of the second last sample for
// the last one. This is a wild guess (and fatal if it turns out
// to be too long), but probably the best we can do - having a zero
// duration is bad as well.
track->track_duration += get_cluster_duration(track, track->entry - 2);
track->end_pts += get_cluster_duration(track, track->entry - 2);
if (!mov->missing_duration_warned) {
av_log(s, AV_LOG_WARNING,
"Estimating the duration of the last packet in a "
"fragment, consider setting the duration field in "
"AVPacket instead.\n");
mov->missing_duration_warned = 1;
}
}
if (!mov->moov_written) {
int64_t pos = avio_tell(s->pb);
uint8_t *buf;
int buf_size, moov_size;
for (i = 0; i < mov->nb_streams; i++)
if (!mov->tracks[i].entry && !is_cover_image(mov->tracks[i].st))
break;
/* Don't write the initial moov unless all tracks have data */
if (i < mov->nb_streams && !force)
return 0;
moov_size = get_moov_size(s);
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset = pos + moov_size + 8;
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_HEADER);
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
mov_write_identification(s->pb, s);
if ((ret = mov_write_moov_tag(s->pb, mov, s)) < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV) {
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(s->pb);
avio_flush(s->pb);
mov->moov_written = 1;
return 0;
}
buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
mov->mdat_buf = NULL;
avio_wb32(s->pb, buf_size + 8);
ffio_wfourcc(s->pb, "mdat");
avio_write(s->pb, buf, buf_size);
av_free(buf);
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(s->pb);
mov->moov_written = 1;
mov->mdat_size = 0;
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].entry)
mov->tracks[i].frag_start += mov->tracks[i].start_dts +
mov->tracks[i].track_duration -
mov->tracks[i].cluster[0].dts;
mov->tracks[i].entry = 0;
mov->tracks[i].end_reliable = 0;
}
avio_flush(s->pb);
return 0;
}
if (mov->frag_interleave) {
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
int ret;
if ((ret = mov_flush_fragment_interleaving(s, track)) < 0)
return ret;
}
if (!mov->mdat_buf)
return 0;
mdat_size = avio_tell(mov->mdat_buf);
}
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF || mov->frag_interleave)
track->data_offset = 0;
else
track->data_offset = mdat_size;
if (track->par->codec_type == AVMEDIA_TYPE_VIDEO) {
has_video = 1;
if (first_video_track) {
if (track->entry)
starts_with_key = track->cluster[0].flags & MOV_SYNC_SAMPLE;
first_video_track = 0;
}
}
if (!track->entry)
continue;
if (track->mdat_buf)
mdat_size += avio_tell(track->mdat_buf);
if (first_track < 0)
first_track = i;
}
if (!mdat_size)
return 0;
avio_write_marker(s->pb,
av_rescale(mov->tracks[first_track].cluster[0].dts, AV_TIME_BASE, mov->tracks[first_track].timescale),
(has_video ? starts_with_key : mov->tracks[first_track].cluster[0].flags & MOV_SYNC_SAMPLE) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
int buf_size, write_moof = 1, moof_tracks = -1;
uint8_t *buf;
int64_t duration = 0;
if (track->entry)
duration = track->start_dts + track->track_duration -
track->cluster[0].dts;
if (mov->flags & FF_MOV_FLAG_SEPARATE_MOOF) {
if (!track->mdat_buf)
continue;
mdat_size = avio_tell(track->mdat_buf);
moof_tracks = i;
} else {
write_moof = i == first_track;
}
if (write_moof) {
avio_flush(s->pb);
mov_write_moof_tag(s->pb, mov, moof_tracks, mdat_size);
mov->fragments++;
avio_wb32(s->pb, mdat_size + 8);
ffio_wfourcc(s->pb, "mdat");
}
if (track->entry)
track->frag_start += duration;
track->entry = 0;
track->entries_flushed = 0;
track->end_reliable = 0;
if (!mov->frag_interleave) {
if (!track->mdat_buf)
continue;
buf_size = avio_close_dyn_buf(track->mdat_buf, &buf);
track->mdat_buf = NULL;
} else {
if (!mov->mdat_buf)
continue;
buf_size = avio_close_dyn_buf(mov->mdat_buf, &buf);
mov->mdat_buf = NULL;
}
avio_write(s->pb, buf, buf_size);
av_free(buf);
}
mov->mdat_size = 0;
avio_flush(s->pb);
return 0;
}
static int mov_auto_flush_fragment(AVFormatContext *s, int force)
{
MOVMuxContext *mov = s->priv_data;
int had_moov = mov->moov_written;
int ret = mov_flush_fragment(s, force);
if (ret < 0)
return ret;
// If using delay_moov, the first flush only wrote the moov,
// not the actual moof+mdat pair, thus flush once again.
if (!had_moov && mov->flags & FF_MOV_FLAG_DELAY_MOOV)
ret = mov_flush_fragment(s, force);
return ret;
}
static int check_pkt(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
int64_t ref;
uint64_t duration;
if (trk->entry) {
ref = trk->cluster[trk->entry - 1].dts;
} else if ( trk->start_dts != AV_NOPTS_VALUE
&& !trk->frag_discont) {
ref = trk->start_dts + trk->track_duration;
} else
ref = pkt->dts; // Skip tests for the first packet
if (trk->dts_shift != AV_NOPTS_VALUE) {
/* With negative CTS offsets we have set an offset to the DTS,
* reverse this for the check. */
ref -= trk->dts_shift;
}
duration = pkt->dts - ref;
if (pkt->dts < ref || duration >= INT_MAX) {
av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" / timestamp: %"PRId64" is out of range for mov/mp4 format\n",
duration, pkt->dts
);
pkt->dts = ref + 1;
pkt->pts = AV_NOPTS_VALUE;
}
if (pkt->duration < 0 || pkt->duration > INT_MAX) {
av_log(s, AV_LOG_ERROR, "Application provided duration: %"PRId64" is invalid\n", pkt->duration);
return AVERROR(EINVAL);
}
return 0;
}
int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
unsigned int samples_in_chunk = 0;
int size = pkt->size, ret = 0;
uint8_t *reformatted_data = NULL;
ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
int ret;
if (mov->moov_written || mov->flags & FF_MOV_FLAG_EMPTY_MOOV) {
if (mov->frag_interleave && mov->fragments > 0) {
if (trk->entry - trk->entries_flushed >= mov->frag_interleave) {
if ((ret = mov_flush_fragment_interleaving(s, trk)) < 0)
return ret;
}
}
if (!trk->mdat_buf) {
if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)
return ret;
}
pb = trk->mdat_buf;
} else {
if (!mov->mdat_buf) {
if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)
return ret;
}
pb = mov->mdat_buf;
}
}
if (par->codec_id == AV_CODEC_ID_AMR_NB) {
/* We must find out how many AMR blocks there are in one packet */
static const uint16_t packed_size[16] =
{13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};
int len = 0;
while (len < size && samples_in_chunk < 100) {
len += packed_size[(pkt->data[len] >> 3) & 0x0F];
samples_in_chunk++;
}
if (samples_in_chunk > 1) {
av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");
return -1;
}
} else if (par->codec_id == AV_CODEC_ID_ADPCM_MS ||
par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {
samples_in_chunk = trk->par->frame_size;
} else if (trk->sample_size)
samples_in_chunk = size / trk->sample_size;
else
samples_in_chunk = 1;
/* copy extradata if it exists */
if (trk->vos_len == 0 && par->extradata_size > 0 &&
!TAG_IS_AVCI(trk->tag) &&
(par->codec_id != AV_CODEC_ID_DNXHD)) {
trk->vos_len = par->extradata_size;
trk->vos_data = av_malloc(trk->vos_len);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, par->extradata, trk->vos_len);
}
if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
(AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
if (!s->streams[pkt->stream_index]->nb_frames) {
av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
"use the audio bitstream filter 'aac_adtstoasc' to fix it "
"('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
return -1;
}
av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
}
if (par->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1 && !TAG_IS_AVCI(trk->tag)) {
/* from x264 or from bytestream H.264 */
/* NAL reformatting needed */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,
&size);
avio_write(pb, reformatted_data, size);
} else {
if (trk->cenc.aes_ctr) {
size = ff_mov_cenc_avc_parse_nal_units(&trk->cenc, pb, pkt->data, size);
if (size < 0) {
ret = size;
goto err;
}
} else {
size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);
}
}
} else if (par->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&
(AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {
/* extradata is Annex B, assume the bitstream is too and convert it */
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {
ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);
avio_write(pb, reformatted_data, size);
} else {
size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);
}
#if CONFIG_AC3_PARSER
} else if (par->codec_id == AV_CODEC_ID_EAC3) {
size = handle_eac3(mov, pkt, trk);
if (size < 0)
return size;
else if (!size)
goto end;
avio_write(pb, pkt->data, size);
#endif
} else {
if (trk->cenc.aes_ctr) {
if (par->codec_id == AV_CODEC_ID_H264 && par->extradata_size > 4) {
int nal_size_length = (par->extradata[4] & 0x3) + 1;
ret = ff_mov_cenc_avc_write_nal_units(s, &trk->cenc, nal_size_length, pb, pkt->data, size);
} else {
ret = ff_mov_cenc_write_packet(&trk->cenc, pb, pkt->data, size);
}
if (ret) {
goto err;
}
} else {
avio_write(pb, pkt->data, size);
}
}
if ((par->codec_id == AV_CODEC_ID_DNXHD ||
par->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {
/* copy frame to create needed atoms */
trk->vos_len = size;
trk->vos_data = av_malloc(size);
if (!trk->vos_data) {
ret = AVERROR(ENOMEM);
goto err;
}
memcpy(trk->vos_data, pkt->data, size);
}
if (trk->entry >= trk->cluster_capacity) {
unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);
if (av_reallocp_array(&trk->cluster, new_capacity,
sizeof(*trk->cluster))) {
ret = AVERROR(ENOMEM);
goto err;
}
trk->cluster_capacity = new_capacity;
}
trk->cluster[trk->entry].pos = avio_tell(pb) - size;
trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;
trk->cluster[trk->entry].chunkNum = 0;
trk->cluster[trk->entry].size = size;
trk->cluster[trk->entry].entries = samples_in_chunk;
trk->cluster[trk->entry].dts = pkt->dts;
trk->cluster[trk->entry].pts = pkt->pts;
if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {
if (!trk->frag_discont) {
/* First packet of a new fragment. We already wrote the duration
* of the last packet of the previous fragment based on track_duration,
* which might not exactly match our dts. Therefore adjust the dts
* of this packet to be what the previous packets duration implies. */
trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;
/* We also may have written the pts and the corresponding duration
* in sidx/tfrf/tfxd tags; make sure the sidx pts and duration match up with
* the next fragment. This means the cts of the first sample must
* be the same in all fragments, unless end_pts was updated by
* the packet causing the fragment to be written. */
if ((mov->flags & FF_MOV_FLAG_DASH && !(mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)) ||
mov->mode == MODE_ISM)
pkt->pts = pkt->dts + trk->end_pts - trk->cluster[trk->entry].dts;
} else {
/* New fragment, but discontinuous from previous fragments.
* Pretend the duration sum of the earlier fragments is
* pkt->dts - trk->start_dts. */
trk->frag_start = pkt->dts - trk->start_dts;
trk->end_pts = AV_NOPTS_VALUE;
trk->frag_discont = 0;
}
}
if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {
/* Not using edit lists and shifting the first track to start from zero.
* If the other streams start from a later timestamp, we won't be able
* to signal the difference in starting time without an edit list.
* Thus move the timestamp for this first sample to 0, increasing
* its duration instead. */
trk->cluster[trk->entry].dts = trk->start_dts = 0;
}
if (trk->start_dts == AV_NOPTS_VALUE) {
trk->start_dts = pkt->dts;
if (trk->frag_discont) {
if (mov->use_editlist) {
/* Pretend the whole stream started at pts=0, with earlier fragments
* already written. If the stream started at pts=0, the duration sum
* of earlier fragments would have been pkt->pts. */
trk->frag_start = pkt->pts;
trk->start_dts = pkt->dts - pkt->pts;
} else {
/* Pretend the whole stream started at dts=0, with earlier fragments
* already written, with a duration summing up to pkt->dts. */
trk->frag_start = pkt->dts;
trk->start_dts = 0;
}
trk->frag_discont = 0;
} else if (pkt->dts && mov->moov_written)
av_log(s, AV_LOG_WARNING,
"Track %d starts with a nonzero dts %"PRId64", while the moov "
"already has been written. Set the delay_moov flag to handle "
"this case.\n",
pkt->stream_index, pkt->dts);
}
trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;
trk->last_sample_is_subtitle_end = 0;
if (pkt->pts == AV_NOPTS_VALUE) {
av_log(s, AV_LOG_WARNING, "pts has no value\n");
pkt->pts = pkt->dts;
}
if (pkt->dts != pkt->pts)
trk->flags |= MOV_TRACK_CTTS;
trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;
trk->cluster[trk->entry].flags = 0;
if (trk->start_cts == AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
if (trk->end_pts == AV_NOPTS_VALUE)
trk->end_pts = trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts + pkt->duration;
else
trk->end_pts = FFMAX(trk->end_pts, trk->cluster[trk->entry].dts +
trk->cluster[trk->entry].cts +
pkt->duration);
if (par->codec_id == AV_CODEC_ID_VC1) {
mov_parse_vc1_frame(pkt, trk);
} else if (pkt->flags & AV_PKT_FLAG_KEY) {
if (mov->mode == MODE_MOV && par->codec_id == AV_CODEC_ID_MPEG2VIDEO &&
trk->entry > 0) { // force sync sample for the first key frame
mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);
if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)
trk->flags |= MOV_TRACK_STPS;
} else {
trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;
}
if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)
trk->has_keyframes++;
}
if (pkt->flags & AV_PKT_FLAG_DISPOSABLE) {
trk->cluster[trk->entry].flags |= MOV_DISPOSABLE_SAMPLE;
trk->has_disposable++;
}
trk->entry++;
trk->sample_count += samples_in_chunk;
mov->mdat_size += size;
if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)
ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,
reformatted_data, size);
end:
err:
av_free(reformatted_data);
return ret;
}
static int mov_write_single_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk = &mov->tracks[pkt->stream_index];
AVCodecParameters *par = trk->par;
int64_t frag_duration = 0;
int size = pkt->size;
int ret = check_pkt(s, pkt);
if (ret < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_FRAG_DISCONT) {
int i;
for (i = 0; i < s->nb_streams; i++)
mov->tracks[i].frag_discont = 1;
mov->flags &= ~FF_MOV_FLAG_FRAG_DISCONT;
}
if (mov->flags & FF_MOV_FLAG_NEGATIVE_CTS_OFFSETS) {
if (trk->dts_shift == AV_NOPTS_VALUE)
trk->dts_shift = pkt->pts - pkt->dts;
pkt->dts += trk->dts_shift;
}
if (trk->par->codec_id == AV_CODEC_ID_MP4ALS ||
trk->par->codec_id == AV_CODEC_ID_AAC ||
trk->par->codec_id == AV_CODEC_ID_FLAC) {
int side_size = 0;
uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
void *newextra = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
if (!newextra)
return AVERROR(ENOMEM);
av_free(par->extradata);
par->extradata = newextra;
memcpy(par->extradata, side, side_size);
par->extradata_size = side_size;
if (!pkt->size) // Flush packet
mov->need_rewrite_extradata = 1;
}
}
if (!pkt->size) {
if (trk->start_dts == AV_NOPTS_VALUE && trk->frag_discont) {
trk->start_dts = pkt->dts;
if (pkt->pts != AV_NOPTS_VALUE)
trk->start_cts = pkt->pts - pkt->dts;
else
trk->start_cts = 0;
}
return 0; /* Discard 0 sized packets */
}
if (trk->entry && pkt->stream_index < s->nb_streams)
frag_duration = av_rescale_q(pkt->dts - trk->cluster[0].dts,
s->streams[pkt->stream_index]->time_base,
AV_TIME_BASE_Q);
if ((mov->max_fragment_duration &&
frag_duration >= mov->max_fragment_duration) ||
(mov->max_fragment_size && mov->mdat_size + size >= mov->max_fragment_size) ||
(mov->flags & FF_MOV_FLAG_FRAG_KEYFRAME &&
par->codec_type == AVMEDIA_TYPE_VIDEO &&
trk->entry && pkt->flags & AV_PKT_FLAG_KEY) ||
(mov->flags & FF_MOV_FLAG_FRAG_EVERY_FRAME)) {
if (frag_duration >= mov->min_fragment_duration) {
// Set the duration of this track to line up with the next
// sample in this track. This avoids relying on AVPacket
// duration, but only helps for this particular track, not
// for the other ones that are flushed at the same time.
trk->track_duration = pkt->dts - trk->start_dts;
if (pkt->pts != AV_NOPTS_VALUE)
trk->end_pts = pkt->pts;
else
trk->end_pts = pkt->dts;
trk->end_reliable = 1;
mov_auto_flush_fragment(s, 0);
}
}
return ff_mov_write_packet(s, pkt);
}
static int mov_write_subtitle_end_packet(AVFormatContext *s,
int stream_index,
int64_t dts) {
AVPacket end;
uint8_t data[2] = {0};
int ret;
av_init_packet(&end);
end.size = sizeof(data);
end.data = data;
end.pts = dts;
end.dts = dts;
end.duration = 0;
end.stream_index = stream_index;
ret = mov_write_single_packet(s, &end);
av_packet_unref(&end);
return ret;
}
static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)
{
MOVMuxContext *mov = s->priv_data;
MOVTrack *trk;
if (!pkt) {
mov_flush_fragment(s, 1);
return 1;
}
trk = &mov->tracks[pkt->stream_index];
if (is_cover_image(trk->st)) {
int ret;
if (trk->st->nb_frames >= 1) {
if (trk->st->nb_frames == 1)
av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d,"
" ignoring.\n", pkt->stream_index);
return 0;
}
if ((ret = av_packet_ref(&trk->cover_image, pkt)) < 0)
return ret;
return 0;
} else {
int i;
if (!pkt->size)
return mov_write_single_packet(s, pkt); /* Passthrough. */
/*
* Subtitles require special handling.
*
* 1) For full complaince, every track must have a sample at
* dts == 0, which is rarely true for subtitles. So, as soon
* as we see any packet with dts > 0, write an empty subtitle
* at dts == 0 for any subtitle track with no samples in it.
*
* 2) For each subtitle track, check if the current packet's
* dts is past the duration of the last subtitle sample. If
* so, we now need to write an end sample for that subtitle.
*
* This must be done conditionally to allow for subtitles that
* immediately replace each other, in which case an end sample
* is not needed, and is, in fact, actively harmful.
*
* 3) See mov_write_trailer for how the final end sample is
* handled.
*/
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
int ret;
if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
trk->track_duration < pkt->dts &&
(trk->entry == 0 || !trk->last_sample_is_subtitle_end)) {
ret = mov_write_subtitle_end_packet(s, i, trk->track_duration);
if (ret < 0) return ret;
trk->last_sample_is_subtitle_end = 1;
}
}
if (trk->mode == MODE_MOV && trk->par->codec_type == AVMEDIA_TYPE_VIDEO) {
AVPacket *opkt = pkt;
int reshuffle_ret, ret;
if (trk->is_unaligned_qt_rgb) {
int64_t bpc = trk->par->bits_per_coded_sample != 15 ? trk->par->bits_per_coded_sample : 16;
int expected_stride = ((trk->par->width * bpc + 15) >> 4)*2;
reshuffle_ret = ff_reshuffle_raw_rgb(s, &pkt, trk->par, expected_stride);
if (reshuffle_ret < 0)
return reshuffle_ret;
} else
reshuffle_ret = 0;
if (trk->par->format == AV_PIX_FMT_PAL8 && !trk->pal_done) {
ret = ff_get_packet_palette(s, opkt, reshuffle_ret, trk->palette);
if (ret < 0)
goto fail;
if (ret)
trk->pal_done++;
} else if (trk->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
(trk->par->format == AV_PIX_FMT_GRAY8 ||
trk->par->format == AV_PIX_FMT_MONOBLACK)) {
for (i = 0; i < pkt->size; i++)
pkt->data[i] = ~pkt->data[i];
}
if (reshuffle_ret) {
ret = mov_write_single_packet(s, pkt);
fail:
if (reshuffle_ret)
av_packet_free(&pkt);
return ret;
}
}
return mov_write_single_packet(s, pkt);
}
}
// QuickTime chapters involve an additional text track with the chapter names
// as samples, and a tref pointing from the other tracks to the chapter one.
static int mov_create_chapter_track(AVFormatContext *s, int tracknum)
{
AVIOContext *pb;
MOVMuxContext *mov = s->priv_data;
MOVTrack *track = &mov->tracks[tracknum];
AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };
int i, len;
track->mode = mov->mode;
track->tag = MKTAG('t','e','x','t');
track->timescale = MOV_TIMESCALE;
track->par = avcodec_parameters_alloc();
if (!track->par)
return AVERROR(ENOMEM);
track->par->codec_type = AVMEDIA_TYPE_SUBTITLE;
#if 0
// These properties are required to make QT recognize the chapter track
uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };
if (ff_alloc_extradata(track->par, sizeof(chapter_properties)))
return AVERROR(ENOMEM);
memcpy(track->par->extradata, chapter_properties, sizeof(chapter_properties));
#else
if (avio_open_dyn_buf(&pb) >= 0) {
int size;
uint8_t *buf;
/* Stub header (usually for Quicktime chapter track) */
// TextSampleEntry
avio_wb32(pb, 0x01); // displayFlags
avio_w8(pb, 0x00); // horizontal justification
avio_w8(pb, 0x00); // vertical justification
avio_w8(pb, 0x00); // bgColourRed
avio_w8(pb, 0x00); // bgColourGreen
avio_w8(pb, 0x00); // bgColourBlue
avio_w8(pb, 0x00); // bgColourAlpha
// BoxRecord
avio_wb16(pb, 0x00); // defTextBoxTop
avio_wb16(pb, 0x00); // defTextBoxLeft
avio_wb16(pb, 0x00); // defTextBoxBottom
avio_wb16(pb, 0x00); // defTextBoxRight
// StyleRecord
avio_wb16(pb, 0x00); // startChar
avio_wb16(pb, 0x00); // endChar
avio_wb16(pb, 0x01); // fontID
avio_w8(pb, 0x00); // fontStyleFlags
avio_w8(pb, 0x00); // fontSize
avio_w8(pb, 0x00); // fgColourRed
avio_w8(pb, 0x00); // fgColourGreen
avio_w8(pb, 0x00); // fgColourBlue
avio_w8(pb, 0x00); // fgColourAlpha
// FontTableBox
avio_wb32(pb, 0x0D); // box size
ffio_wfourcc(pb, "ftab"); // box atom name
avio_wb16(pb, 0x01); // entry count
// FontRecord
avio_wb16(pb, 0x01); // font ID
avio_w8(pb, 0x00); // font name length
if ((size = avio_close_dyn_buf(pb, &buf)) > 0) {
track->par->extradata = buf;
track->par->extradata_size = size;
} else {
av_freep(&buf);
}
}
#endif
for (i = 0; i < s->nb_chapters; i++) {
AVChapter *c = s->chapters[i];
AVDictionaryEntry *t;
int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});
pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});
pkt.duration = end - pkt.dts;
if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {
static const char encd[12] = {
0x00, 0x00, 0x00, 0x0C,
'e', 'n', 'c', 'd',
0x00, 0x00, 0x01, 0x00 };
len = strlen(t->value);
pkt.size = len + 2 + 12;
pkt.data = av_malloc(pkt.size);
if (!pkt.data)
return AVERROR(ENOMEM);
AV_WB16(pkt.data, len);
memcpy(pkt.data + 2, t->value, len);
memcpy(pkt.data + len + 2, encd, sizeof(encd));
ff_mov_write_packet(s, &pkt);
av_freep(&pkt.data);
}
}
return 0;
}
static int mov_check_timecode_track(AVFormatContext *s, AVTimecode *tc, int src_index, const char *tcstr)
{
int ret;
/* compute the frame number */
ret = av_timecode_init_from_string(tc, find_fps(s, s->streams[src_index]), tcstr, s);
return ret;
}
static int mov_create_timecode_track(AVFormatContext *s, int index, int src_index, AVTimecode tc)
{
int ret;
MOVMuxContext *mov = s->priv_data;
MOVTrack *track = &mov->tracks[index];
AVStream *src_st = s->streams[src_index];
AVPacket pkt = {.stream_index = index, .flags = AV_PKT_FLAG_KEY, .size = 4};
AVRational rate = find_fps(s, src_st);
/* tmcd track based on video stream */
track->mode = mov->mode;
track->tag = MKTAG('t','m','c','d');
track->src_track = src_index;
track->timescale = mov->tracks[src_index].timescale;
if (tc.flags & AV_TIMECODE_FLAG_DROPFRAME)
track->timecode_flags |= MOV_TIMECODE_FLAG_DROPFRAME;
/* set st to src_st for metadata access*/
track->st = src_st;
/* encode context: tmcd data stream */
track->par = avcodec_parameters_alloc();
if (!track->par)
return AVERROR(ENOMEM);
track->par->codec_type = AVMEDIA_TYPE_DATA;
track->par->codec_tag = track->tag;
track->st->avg_frame_rate = av_inv_q(rate);
/* the tmcd track just contains one packet with the frame number */
pkt.data = av_malloc(pkt.size);
if (!pkt.data)
return AVERROR(ENOMEM);
AV_WB32(pkt.data, tc.start);
ret = ff_mov_write_packet(s, &pkt);
av_free(pkt.data);
return ret;
}
/*
* st->disposition controls the "enabled" flag in the tkhd tag.
* QuickTime will not play a track if it is not enabled. So make sure
* that one track of each type (audio, video, subtitle) is enabled.
*
* Subtitles are special. For audio and video, setting "enabled" also
* makes the track "default" (i.e. it is rendered when played). For
* subtitles, an "enabled" subtitle is not rendered by default, but
* if no subtitle is enabled, the subtitle menu in QuickTime will be
* empty!
*/
static void enable_tracks(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
int enabled[AVMEDIA_TYPE_NB];
int first[AVMEDIA_TYPE_NB];
for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
enabled[i] = 0;
first[i] = -1;
}
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (st->codecpar->codec_type <= AVMEDIA_TYPE_UNKNOWN ||
st->codecpar->codec_type >= AVMEDIA_TYPE_NB ||
is_cover_image(st))
continue;
if (first[st->codecpar->codec_type] < 0)
first[st->codecpar->codec_type] = i;
if (st->disposition & AV_DISPOSITION_DEFAULT) {
mov->tracks[i].flags |= MOV_TRACK_ENABLED;
enabled[st->codecpar->codec_type]++;
}
}
for (i = 0; i < AVMEDIA_TYPE_NB; i++) {
switch (i) {
case AVMEDIA_TYPE_VIDEO:
case AVMEDIA_TYPE_AUDIO:
case AVMEDIA_TYPE_SUBTITLE:
if (enabled[i] > 1)
mov->per_stream_grouping = 1;
if (!enabled[i] && first[i] >= 0)
mov->tracks[first[i]].flags |= MOV_TRACK_ENABLED;
break;
}
}
}
static void mov_free(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
int i;
if (mov->chapter_track) {
if (mov->tracks[mov->chapter_track].par)
av_freep(&mov->tracks[mov->chapter_track].par->extradata);
av_freep(&mov->tracks[mov->chapter_track].par);
}
for (i = 0; i < mov->nb_streams; i++) {
if (mov->tracks[i].tag == MKTAG('r','t','p',' '))
ff_mov_close_hinting(&mov->tracks[i]);
else if (mov->tracks[i].tag == MKTAG('t','m','c','d') && mov->nb_meta_tmcd)
av_freep(&mov->tracks[i].par);
av_freep(&mov->tracks[i].cluster);
av_freep(&mov->tracks[i].frag_info);
av_packet_unref(&mov->tracks[i].cover_image);
if (mov->tracks[i].vos_len)
av_freep(&mov->tracks[i].vos_data);
ff_mov_cenc_free(&mov->tracks[i].cenc);
}
av_freep(&mov->tracks);
}
static uint32_t rgb_to_yuv(uint32_t rgb)
{
uint8_t r, g, b;
int y, cb, cr;
r = (rgb >> 16) & 0xFF;
g = (rgb >> 8) & 0xFF;
b = (rgb ) & 0xFF;
y = av_clip_uint8(( 16000 + 257 * r + 504 * g + 98 * b)/1000);
cb = av_clip_uint8((128000 - 148 * r - 291 * g + 439 * b)/1000);
cr = av_clip_uint8((128000 + 439 * r - 368 * g - 71 * b)/1000);
return (y << 16) | (cr << 8) | cb;
}
static int mov_create_dvd_sub_decoder_specific_info(MOVTrack *track,
AVStream *st)
{
int i, width = 720, height = 480;
int have_palette = 0, have_size = 0;
uint32_t palette[16];
char *cur = st->codecpar->extradata;
while (cur && *cur) {
if (strncmp("palette:", cur, 8) == 0) {
int i, count;
count = sscanf(cur + 8,
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32", "
"%06"PRIx32", %06"PRIx32", %06"PRIx32", %06"PRIx32"",
&palette[ 0], &palette[ 1], &palette[ 2], &palette[ 3],
&palette[ 4], &palette[ 5], &palette[ 6], &palette[ 7],
&palette[ 8], &palette[ 9], &palette[10], &palette[11],
&palette[12], &palette[13], &palette[14], &palette[15]);
for (i = 0; i < count; i++) {
palette[i] = rgb_to_yuv(palette[i]);
}
have_palette = 1;
} else if (!strncmp("size:", cur, 5)) {
sscanf(cur + 5, "%dx%d", &width, &height);
have_size = 1;
}
if (have_palette && have_size)
break;
cur += strcspn(cur, "\n\r");
cur += strspn(cur, "\n\r");
}
if (have_palette) {
track->vos_data = av_malloc(16*4);
if (!track->vos_data)
return AVERROR(ENOMEM);
for (i = 0; i < 16; i++) {
AV_WB32(track->vos_data + i * 4, palette[i]);
}
track->vos_len = 16 * 4;
}
st->codecpar->width = width;
st->codecpar->height = track->height = height;
return 0;
}
static int mov_init(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
AVDictionaryEntry *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
int i, ret;
mov->fc = s;
/* Default mode == MP4 */
mov->mode = MODE_MP4;
if (s->oformat) {
if (!strcmp("3gp", s->oformat->name)) mov->mode = MODE_3GP;
else if (!strcmp("3g2", s->oformat->name)) mov->mode = MODE_3GP|MODE_3G2;
else if (!strcmp("mov", s->oformat->name)) mov->mode = MODE_MOV;
else if (!strcmp("psp", s->oformat->name)) mov->mode = MODE_PSP;
else if (!strcmp("ipod",s->oformat->name)) mov->mode = MODE_IPOD;
else if (!strcmp("ismv",s->oformat->name)) mov->mode = MODE_ISM;
else if (!strcmp("f4v", s->oformat->name)) mov->mode = MODE_F4V;
}
if (mov->flags & FF_MOV_FLAG_DELAY_MOOV)
mov->flags |= FF_MOV_FLAG_EMPTY_MOOV;
/* Set the FRAGMENT flag if any of the fragmentation methods are
* enabled. */
if (mov->max_fragment_duration || mov->max_fragment_size ||
mov->flags & (FF_MOV_FLAG_EMPTY_MOOV |
FF_MOV_FLAG_FRAG_KEYFRAME |
FF_MOV_FLAG_FRAG_CUSTOM |
FF_MOV_FLAG_FRAG_EVERY_FRAME))
mov->flags |= FF_MOV_FLAG_FRAGMENT;
/* Set other implicit flags immediately */
if (mov->mode == MODE_ISM)
mov->flags |= FF_MOV_FLAG_EMPTY_MOOV | FF_MOV_FLAG_SEPARATE_MOOF |
FF_MOV_FLAG_FRAGMENT;
if (mov->flags & FF_MOV_FLAG_DASH)
mov->flags |= FF_MOV_FLAG_FRAGMENT | FF_MOV_FLAG_EMPTY_MOOV |
FF_MOV_FLAG_DEFAULT_BASE_MOOF;
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV && s->flags & AVFMT_FLAG_AUTO_BSF) {
av_log(s, AV_LOG_VERBOSE, "Empty MOOV enabled; disabling automatic bitstream filtering\n");
s->flags &= ~AVFMT_FLAG_AUTO_BSF;
}
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
mov->reserved_moov_size = -1;
}
if (mov->use_editlist < 0) {
mov->use_editlist = 1;
if (mov->flags & FF_MOV_FLAG_FRAGMENT &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
// If we can avoid needing an edit list by shifting the
// tracks, prefer that over (trying to) write edit lists
// in fragmented output.
if (s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO ||
s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO)
mov->use_editlist = 0;
}
}
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV) && mov->use_editlist)
av_log(s, AV_LOG_WARNING, "No meaningful edit list will be written when using empty_moov without delay_moov\n");
if (!mov->use_editlist && s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_AUTO)
s->avoid_negative_ts = AVFMT_AVOID_NEG_TS_MAKE_ZERO;
/* Clear the omit_tfhd_offset flag if default_base_moof is set;
* if the latter is set that's enough and omit_tfhd_offset doesn't
* add anything extra on top of that. */
if (mov->flags & FF_MOV_FLAG_OMIT_TFHD_OFFSET &&
mov->flags & FF_MOV_FLAG_DEFAULT_BASE_MOOF)
mov->flags &= ~FF_MOV_FLAG_OMIT_TFHD_OFFSET;
if (mov->frag_interleave &&
mov->flags & (FF_MOV_FLAG_OMIT_TFHD_OFFSET | FF_MOV_FLAG_SEPARATE_MOOF)) {
av_log(s, AV_LOG_ERROR,
"Sample interleaving in fragments is mutually exclusive with "
"omit_tfhd_offset and separate_moof\n");
return AVERROR(EINVAL);
}
/* Non-seekable output is ok if using fragmentation. If ism_lookahead
* is enabled, we don't support non-seekable output at all. */
if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
(!(mov->flags & FF_MOV_FLAG_FRAGMENT) || mov->ism_lookahead)) {
av_log(s, AV_LOG_ERROR, "muxer does not support non seekable output\n");
return AVERROR(EINVAL);
}
mov->nb_streams = s->nb_streams;
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
mov->chapter_track = mov->nb_streams++;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
for (i = 0; i < s->nb_streams; i++)
if (rtp_hinting_needed(s->streams[i]))
mov->nb_streams++;
}
if ( mov->write_tmcd == -1 && (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
|| mov->write_tmcd == 1) {
/* +1 tmcd track for each video stream with a timecode */
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
AVDictionaryEntry *t = global_tcr;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
(t || (t=av_dict_get(st->metadata, "timecode", NULL, 0)))) {
AVTimecode tc;
ret = mov_check_timecode_track(s, &tc, i, t->value);
if (ret >= 0)
mov->nb_meta_tmcd++;
}
}
/* check if there is already a tmcd track to remux */
if (mov->nb_meta_tmcd) {
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) {
av_log(s, AV_LOG_WARNING, "You requested a copy of the original timecode track "
"so timecode metadata are now ignored\n");
mov->nb_meta_tmcd = 0;
}
}
}
mov->nb_streams += mov->nb_meta_tmcd;
}
// Reserve an extra stream for chapters for the case where chapters
// are written in the trailer
mov->tracks = av_mallocz_array((mov->nb_streams + 1), sizeof(*mov->tracks));
if (!mov->tracks)
return AVERROR(ENOMEM);
if (mov->encryption_scheme_str != NULL && strcmp(mov->encryption_scheme_str, "none") != 0) {
if (strcmp(mov->encryption_scheme_str, "cenc-aes-ctr") == 0) {
mov->encryption_scheme = MOV_ENC_CENC_AES_CTR;
if (mov->encryption_key_len != AES_CTR_KEY_SIZE) {
av_log(s, AV_LOG_ERROR, "Invalid encryption key len %d expected %d\n",
mov->encryption_key_len, AES_CTR_KEY_SIZE);
return AVERROR(EINVAL);
}
if (mov->encryption_kid_len != CENC_KID_SIZE) {
av_log(s, AV_LOG_ERROR, "Invalid encryption kid len %d expected %d\n",
mov->encryption_kid_len, CENC_KID_SIZE);
return AVERROR(EINVAL);
}
} else {
av_log(s, AV_LOG_ERROR, "unsupported encryption scheme %s\n",
mov->encryption_scheme_str);
return AVERROR(EINVAL);
}
}
for (i = 0; i < s->nb_streams; i++) {
AVStream *st= s->streams[i];
MOVTrack *track= &mov->tracks[i];
AVDictionaryEntry *lang = av_dict_get(st->metadata, "language", NULL,0);
track->st = st;
track->par = st->codecpar;
track->language = ff_mov_iso639_to_lang(lang?lang->value:"und", mov->mode!=MODE_MOV);
if (track->language < 0)
track->language = 0;
track->mode = mov->mode;
track->tag = mov_find_codec_tag(s, track);
if (!track->tag) {
av_log(s, AV_LOG_ERROR, "Could not find tag for codec %s in stream #%d, "
"codec not currently supported in container\n",
avcodec_get_name(st->codecpar->codec_id), i);
return AVERROR(EINVAL);
}
/* If hinting of this track is enabled by a later hint track,
* this is updated. */
track->hint_track = -1;
track->start_dts = AV_NOPTS_VALUE;
track->start_cts = AV_NOPTS_VALUE;
track->end_pts = AV_NOPTS_VALUE;
track->dts_shift = AV_NOPTS_VALUE;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
if (track->tag == MKTAG('m','x','3','p') || track->tag == MKTAG('m','x','3','n') ||
track->tag == MKTAG('m','x','4','p') || track->tag == MKTAG('m','x','4','n') ||
track->tag == MKTAG('m','x','5','p') || track->tag == MKTAG('m','x','5','n')) {
if (st->codecpar->width != 720 || (st->codecpar->height != 608 && st->codecpar->height != 512)) {
av_log(s, AV_LOG_ERROR, "D-10/IMX must use 720x608 or 720x512 video resolution\n");
return AVERROR(EINVAL);
}
track->height = track->tag >> 24 == 'n' ? 486 : 576;
}
if (mov->video_track_timescale) {
track->timescale = mov->video_track_timescale;
} else {
track->timescale = st->time_base.den;
while(track->timescale < 10000)
track->timescale *= 2;
}
if (st->codecpar->width > 65535 || st->codecpar->height > 65535) {
av_log(s, AV_LOG_ERROR, "Resolution %dx%d too large for mov/mp4\n", st->codecpar->width, st->codecpar->height);
return AVERROR(EINVAL);
}
if (track->mode == MODE_MOV && track->timescale > 100000)
av_log(s, AV_LOG_WARNING,
"WARNING codec timebase is very high. If duration is too long,\n"
"file may not be playable by quicktime. Specify a shorter timebase\n"
"or choose different container.\n");
if (track->mode == MODE_MOV &&
track->par->codec_id == AV_CODEC_ID_RAWVIDEO &&
track->tag == MKTAG('r','a','w',' ')) {
enum AVPixelFormat pix_fmt = track->par->format;
if (pix_fmt == AV_PIX_FMT_NONE && track->par->bits_per_coded_sample == 1)
pix_fmt = AV_PIX_FMT_MONOWHITE;
track->is_unaligned_qt_rgb =
pix_fmt == AV_PIX_FMT_RGB24 ||
pix_fmt == AV_PIX_FMT_BGR24 ||
pix_fmt == AV_PIX_FMT_PAL8 ||
pix_fmt == AV_PIX_FMT_GRAY8 ||
pix_fmt == AV_PIX_FMT_MONOWHITE ||
pix_fmt == AV_PIX_FMT_MONOBLACK;
}
if (track->par->codec_id == AV_CODEC_ID_VP9) {
if (track->mode != MODE_MP4) {
av_log(s, AV_LOG_ERROR, "VP9 only supported in MP4.\n");
return AVERROR(EINVAL);
}
} else if (track->par->codec_id == AV_CODEC_ID_AV1) {
/* spec is not finished, so forbid for now */
av_log(s, AV_LOG_ERROR, "AV1 muxing is currently not supported.\n");
return AVERROR_PATCHWELCOME;
} else if (track->par->codec_id == AV_CODEC_ID_VP8) {
/* altref frames handling is not defined in the spec as of version v1.0,
* so just forbid muxing VP8 streams altogether until a new version does */
av_log(s, AV_LOG_ERROR, "VP8 muxing is currently not supported.\n");
return AVERROR_PATCHWELCOME;
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
track->timescale = st->codecpar->sample_rate;
if (!st->codecpar->frame_size && !av_get_bits_per_sample(st->codecpar->codec_id)) {
av_log(s, AV_LOG_WARNING, "track %d: codec frame size is not set\n", i);
track->audio_vbr = 1;
}else if (st->codecpar->codec_id == AV_CODEC_ID_ADPCM_MS ||
st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV ||
st->codecpar->codec_id == AV_CODEC_ID_ILBC){
if (!st->codecpar->block_align) {
av_log(s, AV_LOG_ERROR, "track %d: codec block align is not set for adpcm\n", i);
return AVERROR(EINVAL);
}
track->sample_size = st->codecpar->block_align;
}else if (st->codecpar->frame_size > 1){ /* assume compressed audio */
track->audio_vbr = 1;
}else{
track->sample_size = (av_get_bits_per_sample(st->codecpar->codec_id) >> 3) * st->codecpar->channels;
}
if (st->codecpar->codec_id == AV_CODEC_ID_ILBC ||
st->codecpar->codec_id == AV_CODEC_ID_ADPCM_IMA_QT) {
track->audio_vbr = 1;
}
if (track->mode != MODE_MOV &&
track->par->codec_id == AV_CODEC_ID_MP3 && track->timescale < 16000) {
if (s->strict_std_compliance >= FF_COMPLIANCE_NORMAL) {
av_log(s, AV_LOG_ERROR, "track %d: muxing mp3 at %dhz is not standard, to mux anyway set strict to -1\n",
i, track->par->sample_rate);
return AVERROR(EINVAL);
} else {
av_log(s, AV_LOG_WARNING, "track %d: muxing mp3 at %dhz is not standard in MP4\n",
i, track->par->sample_rate);
}
}
if (track->par->codec_id == AV_CODEC_ID_FLAC ||
track->par->codec_id == AV_CODEC_ID_OPUS) {
if (track->mode != MODE_MP4) {
av_log(s, AV_LOG_ERROR, "%s only supported in MP4.\n", avcodec_get_name(track->par->codec_id));
return AVERROR(EINVAL);
}
if (s->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
av_log(s, AV_LOG_ERROR,
"%s in MP4 support is experimental, add "
"'-strict %d' if you want to use it.\n",
avcodec_get_name(track->par->codec_id), FF_COMPLIANCE_EXPERIMENTAL);
return AVERROR_EXPERIMENTAL;
}
}
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) {
track->timescale = st->time_base.den;
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) {
track->timescale = st->time_base.den;
} else {
track->timescale = MOV_TIMESCALE;
}
if (!track->height)
track->height = st->codecpar->height;
/* The ism specific timescale isn't mandatory, but is assumed by
* some tools, such as mp4split. */
if (mov->mode == MODE_ISM)
track->timescale = 10000000;
avpriv_set_pts_info(st, 64, 1, track->timescale);
if (mov->encryption_scheme == MOV_ENC_CENC_AES_CTR) {
ret = ff_mov_cenc_init(&track->cenc, mov->encryption_key,
track->par->codec_id == AV_CODEC_ID_H264, s->flags & AVFMT_FLAG_BITEXACT);
if (ret)
return ret;
}
}
enable_tracks(s);
return 0;
}
static int mov_write_header(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
MOVMuxContext *mov = s->priv_data;
AVDictionaryEntry *t, *global_tcr = av_dict_get(s->metadata, "timecode", NULL, 0);
int i, ret, hint_track = 0, tmcd_track = 0, nb_tracks = s->nb_streams;
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters)
nb_tracks++;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
hint_track = nb_tracks;
for (i = 0; i < s->nb_streams; i++)
if (rtp_hinting_needed(s->streams[i]))
nb_tracks++;
}
if (mov->mode == MODE_MOV || mov->mode == MODE_MP4)
tmcd_track = nb_tracks;
for (i = 0; i < s->nb_streams; i++) {
int j;
AVStream *st= s->streams[i];
MOVTrack *track= &mov->tracks[i];
/* copy extradata if it exists */
if (st->codecpar->extradata_size) {
if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE)
mov_create_dvd_sub_decoder_specific_info(track, st);
else if (!TAG_IS_AVCI(track->tag) && st->codecpar->codec_id != AV_CODEC_ID_DNXHD) {
track->vos_len = st->codecpar->extradata_size;
track->vos_data = av_malloc(track->vos_len);
if (!track->vos_data) {
return AVERROR(ENOMEM);
}
memcpy(track->vos_data, st->codecpar->extradata, track->vos_len);
}
}
if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
track->par->channel_layout != AV_CH_LAYOUT_MONO)
continue;
for (j = 0; j < s->nb_streams; j++) {
AVStream *stj= s->streams[j];
MOVTrack *trackj= &mov->tracks[j];
if (j == i)
continue;
if (stj->codecpar->codec_type != AVMEDIA_TYPE_AUDIO ||
trackj->par->channel_layout != AV_CH_LAYOUT_MONO ||
trackj->language != track->language ||
trackj->tag != track->tag
)
continue;
track->multichannel_as_mono++;
}
}
if (!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
if ((ret = mov_write_identification(pb, s)) < 0)
return ret;
}
if (mov->reserved_moov_size){
mov->reserved_header_pos = avio_tell(pb);
if (mov->reserved_moov_size > 0)
avio_skip(pb, mov->reserved_moov_size);
}
if (mov->flags & FF_MOV_FLAG_FRAGMENT) {
/* If no fragmentation options have been set, set a default. */
if (!(mov->flags & (FF_MOV_FLAG_FRAG_KEYFRAME |
FF_MOV_FLAG_FRAG_CUSTOM |
FF_MOV_FLAG_FRAG_EVERY_FRAME)) &&
!mov->max_fragment_duration && !mov->max_fragment_size)
mov->flags |= FF_MOV_FLAG_FRAG_KEYFRAME;
} else {
if (mov->flags & FF_MOV_FLAG_FASTSTART)
mov->reserved_header_pos = avio_tell(pb);
mov_write_mdat_tag(pb, mov);
}
ff_parse_creation_time_metadata(s, &mov->time, 1);
if (mov->time)
mov->time += 0x7C25B080; // 1970 based -> 1904 based
if (mov->chapter_track)
if ((ret = mov_create_chapter_track(s, mov->chapter_track)) < 0)
return ret;
if (mov->flags & FF_MOV_FLAG_RTP_HINT) {
for (i = 0; i < s->nb_streams; i++) {
if (rtp_hinting_needed(s->streams[i])) {
if ((ret = ff_mov_init_hinting(s, hint_track, i)) < 0)
return ret;
hint_track++;
}
}
}
if (mov->nb_meta_tmcd) {
/* Initialize the tmcd tracks */
for (i = 0; i < s->nb_streams; i++) {
AVStream *st = s->streams[i];
t = global_tcr;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
AVTimecode tc;
if (!t)
t = av_dict_get(st->metadata, "timecode", NULL, 0);
if (!t)
continue;
if (mov_check_timecode_track(s, &tc, i, t->value) < 0)
continue;
if ((ret = mov_create_timecode_track(s, tmcd_track, i, tc)) < 0)
return ret;
tmcd_track++;
}
}
}
avio_flush(pb);
if (mov->flags & FF_MOV_FLAG_ISML)
mov_write_isml_manifest(pb, mov, s);
if (mov->flags & FF_MOV_FLAG_EMPTY_MOOV &&
!(mov->flags & FF_MOV_FLAG_DELAY_MOOV)) {
if ((ret = mov_write_moov_tag(pb, mov, s)) < 0)
return ret;
avio_flush(pb);
mov->moov_written = 1;
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX)
mov->reserved_header_pos = avio_tell(pb);
}
return 0;
}
static int get_moov_size(AVFormatContext *s)
{
int ret;
AVIOContext *moov_buf;
MOVMuxContext *mov = s->priv_data;
if ((ret = ffio_open_null_buf(&moov_buf)) < 0)
return ret;
if ((ret = mov_write_moov_tag(moov_buf, mov, s)) < 0)
return ret;
return ffio_close_null_buf(moov_buf);
}
static int get_sidx_size(AVFormatContext *s)
{
int ret;
AVIOContext *buf;
MOVMuxContext *mov = s->priv_data;
if ((ret = ffio_open_null_buf(&buf)) < 0)
return ret;
mov_write_sidx_tags(buf, mov, -1, 0);
return ffio_close_null_buf(buf);
}
/*
* This function gets the moov size if moved to the top of the file: the chunk
* offset table can switch between stco (32-bit entries) to co64 (64-bit
* entries) when the moov is moved to the beginning, so the size of the moov
* would change. It also updates the chunk offset tables.
*/
static int compute_moov_size(AVFormatContext *s)
{
int i, moov_size, moov_size2;
MOVMuxContext *mov = s->priv_data;
moov_size = get_moov_size(s);
if (moov_size < 0)
return moov_size;
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += moov_size;
moov_size2 = get_moov_size(s);
if (moov_size2 < 0)
return moov_size2;
/* if the size changed, we just switched from stco to co64 and need to
* update the offsets */
if (moov_size2 != moov_size)
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += moov_size2 - moov_size;
return moov_size2;
}
static int compute_sidx_size(AVFormatContext *s)
{
int i, sidx_size;
MOVMuxContext *mov = s->priv_data;
sidx_size = get_sidx_size(s);
if (sidx_size < 0)
return sidx_size;
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset += sidx_size;
return sidx_size;
}
static int shift_data(AVFormatContext *s)
{
int ret = 0, moov_size;
MOVMuxContext *mov = s->priv_data;
int64_t pos, pos_end = avio_tell(s->pb);
uint8_t *buf, *read_buf[2];
int read_buf_id = 0;
int read_size[2];
AVIOContext *read_pb;
if (mov->flags & FF_MOV_FLAG_FRAGMENT)
moov_size = compute_sidx_size(s);
else
moov_size = compute_moov_size(s);
if (moov_size < 0)
return moov_size;
buf = av_malloc(moov_size * 2);
if (!buf)
return AVERROR(ENOMEM);
read_buf[0] = buf;
read_buf[1] = buf + moov_size;
/* Shift the data: the AVIO context of the output can only be used for
* writing, so we re-open the same output, but for reading. It also avoids
* a read/seek/write/seek back and forth. */
avio_flush(s->pb);
ret = s->io_open(s, &read_pb, s->url, AVIO_FLAG_READ, NULL);
if (ret < 0) {
av_log(s, AV_LOG_ERROR, "Unable to re-open %s output file for "
"the second pass (faststart)\n", s->url);
goto end;
}
/* mark the end of the shift to up to the last data we wrote, and get ready
* for writing */
pos_end = avio_tell(s->pb);
avio_seek(s->pb, mov->reserved_header_pos + moov_size, SEEK_SET);
/* start reading at where the new moov will be placed */
avio_seek(read_pb, mov->reserved_header_pos, SEEK_SET);
pos = avio_tell(read_pb);
#define READ_BLOCK do { \
read_size[read_buf_id] = avio_read(read_pb, read_buf[read_buf_id], moov_size); \
read_buf_id ^= 1; \
} while (0)
/* shift data by chunk of at most moov_size */
READ_BLOCK;
do {
int n;
READ_BLOCK;
n = read_size[read_buf_id];
if (n <= 0)
break;
avio_write(s->pb, read_buf[read_buf_id], n);
pos += n;
} while (pos < pos_end);
ff_format_io_close(s, &read_pb);
end:
av_free(buf);
return ret;
}
static int mov_write_trailer(AVFormatContext *s)
{
MOVMuxContext *mov = s->priv_data;
AVIOContext *pb = s->pb;
int res = 0;
int i;
int64_t moov_pos;
if (mov->need_rewrite_extradata) {
for (i = 0; i < s->nb_streams; i++) {
MOVTrack *track = &mov->tracks[i];
AVCodecParameters *par = track->par;
track->vos_len = par->extradata_size;
track->vos_data = av_malloc(track->vos_len);
if (!track->vos_data)
return AVERROR(ENOMEM);
memcpy(track->vos_data, par->extradata, track->vos_len);
}
mov->need_rewrite_extradata = 0;
}
/*
* Before actually writing the trailer, make sure that there are no
* dangling subtitles, that need a terminating sample.
*/
for (i = 0; i < mov->nb_streams; i++) {
MOVTrack *trk = &mov->tracks[i];
if (trk->par->codec_id == AV_CODEC_ID_MOV_TEXT &&
!trk->last_sample_is_subtitle_end) {
mov_write_subtitle_end_packet(s, i, trk->track_duration);
trk->last_sample_is_subtitle_end = 1;
}
}
// If there were no chapters when the header was written, but there
// are chapters now, write them in the trailer. This only works
// when we are not doing fragments.
if (!mov->chapter_track && !(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
if (mov->mode & (MODE_MP4|MODE_MOV|MODE_IPOD) && s->nb_chapters) {
mov->chapter_track = mov->nb_streams++;
if ((res = mov_create_chapter_track(s, mov->chapter_track)) < 0)
return res;
}
}
if (!(mov->flags & FF_MOV_FLAG_FRAGMENT)) {
moov_pos = avio_tell(pb);
/* Write size of mdat tag */
if (mov->mdat_size + 8 <= UINT32_MAX) {
avio_seek(pb, mov->mdat_pos, SEEK_SET);
avio_wb32(pb, mov->mdat_size + 8);
} else {
/* overwrite 'wide' placeholder atom */
avio_seek(pb, mov->mdat_pos - 8, SEEK_SET);
/* special value: real atom size will be 64 bit value after
* tag field */
avio_wb32(pb, 1);
ffio_wfourcc(pb, "mdat");
avio_wb64(pb, mov->mdat_size + 16);
}
avio_seek(pb, mov->reserved_moov_size > 0 ? mov->reserved_header_pos : moov_pos, SEEK_SET);
if (mov->flags & FF_MOV_FLAG_FASTSTART) {
av_log(s, AV_LOG_INFO, "Starting second pass: moving the moov atom to the beginning of the file\n");
res = shift_data(s);
if (res < 0)
return res;
avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
} else if (mov->reserved_moov_size > 0) {
int64_t size;
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
size = mov->reserved_moov_size - (avio_tell(pb) - mov->reserved_header_pos);
if (size < 8){
av_log(s, AV_LOG_ERROR, "reserved_moov_size is too small, needed %"PRId64" additional\n", 8-size);
return AVERROR(EINVAL);
}
avio_wb32(pb, size);
ffio_wfourcc(pb, "free");
ffio_fill(pb, 0, size - 8);
avio_seek(pb, moov_pos, SEEK_SET);
} else {
if ((res = mov_write_moov_tag(pb, mov, s)) < 0)
return res;
}
res = 0;
} else {
mov_auto_flush_fragment(s, 1);
for (i = 0; i < mov->nb_streams; i++)
mov->tracks[i].data_offset = 0;
if (mov->flags & FF_MOV_FLAG_GLOBAL_SIDX) {
int64_t end;
av_log(s, AV_LOG_INFO, "Starting second pass: inserting sidx atoms\n");
res = shift_data(s);
if (res < 0)
return res;
end = avio_tell(pb);
avio_seek(pb, mov->reserved_header_pos, SEEK_SET);
mov_write_sidx_tags(pb, mov, -1, 0);
avio_seek(pb, end, SEEK_SET);
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
mov_write_mfra_tag(pb, mov);
} else if (!(mov->flags & FF_MOV_FLAG_SKIP_TRAILER)) {
avio_write_marker(s->pb, AV_NOPTS_VALUE, AVIO_DATA_MARKER_TRAILER);
mov_write_mfra_tag(pb, mov);
}
}
return res;
}
static int mov_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt)
{
int ret = 1;
AVStream *st = s->streams[pkt->stream_index];
if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
if (pkt->size > 2 && (AV_RB16(pkt->data) & 0xfff0) == 0xfff0)
ret = ff_stream_add_bitstream_filter(st, "aac_adtstoasc", NULL);
} else if (st->codecpar->codec_id == AV_CODEC_ID_VP9) {
ret = ff_stream_add_bitstream_filter(st, "vp9_superframe", NULL);
}
return ret;
}
static const AVCodecTag codec_3gp_tags[] = {
{ AV_CODEC_ID_H263, MKTAG('s','2','6','3') },
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_AMR_NB, MKTAG('s','a','m','r') },
{ AV_CODEC_ID_AMR_WB, MKTAG('s','a','w','b') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
{ AV_CODEC_ID_NONE, 0 },
};
const AVCodecTag codec_mp4_tags[] = {
{ AV_CODEC_ID_MPEG4 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '1') },
{ AV_CODEC_ID_H264 , MKTAG('a', 'v', 'c', '3') },
{ AV_CODEC_ID_HEVC , MKTAG('h', 'e', 'v', '1') },
{ AV_CODEC_ID_HEVC , MKTAG('h', 'v', 'c', '1') },
{ AV_CODEC_ID_MPEG2VIDEO , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_MPEG1VIDEO , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_MJPEG , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_PNG , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_JPEG2000 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_VC1 , MKTAG('v', 'c', '-', '1') },
{ AV_CODEC_ID_DIRAC , MKTAG('d', 'r', 'a', 'c') },
{ AV_CODEC_ID_TSCC2 , MKTAG('m', 'p', '4', 'v') },
{ AV_CODEC_ID_VP9 , MKTAG('v', 'p', '0', '9') },
{ AV_CODEC_ID_AAC , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP4ALS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP3 , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_MP2 , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_AC3 , MKTAG('a', 'c', '-', '3') },
{ AV_CODEC_ID_EAC3 , MKTAG('e', 'c', '-', '3') },
{ AV_CODEC_ID_DTS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_FLAC , MKTAG('f', 'L', 'a', 'C') },
{ AV_CODEC_ID_OPUS , MKTAG('O', 'p', 'u', 's') },
{ AV_CODEC_ID_VORBIS , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_QCELP , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_EVRC , MKTAG('m', 'p', '4', 'a') },
{ AV_CODEC_ID_DVD_SUBTITLE, MKTAG('m', 'p', '4', 's') },
{ AV_CODEC_ID_MOV_TEXT , MKTAG('t', 'x', '3', 'g') },
{ AV_CODEC_ID_NONE , 0 },
};
const AVCodecTag codec_ism_tags[] = {
{ AV_CODEC_ID_WMAPRO , MKTAG('w', 'm', 'a', ' ') },
{ AV_CODEC_ID_NONE , 0 },
};
static const AVCodecTag codec_ipod_tags[] = {
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_MPEG4, MKTAG('m','p','4','v') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_ALAC, MKTAG('a','l','a','c') },
{ AV_CODEC_ID_AC3, MKTAG('a','c','-','3') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','x','3','g') },
{ AV_CODEC_ID_MOV_TEXT, MKTAG('t','e','x','t') },
{ AV_CODEC_ID_NONE, 0 },
};
static const AVCodecTag codec_f4v_tags[] = {
{ AV_CODEC_ID_MP3, MKTAG('.','m','p','3') },
{ AV_CODEC_ID_AAC, MKTAG('m','p','4','a') },
{ AV_CODEC_ID_H264, MKTAG('a','v','c','1') },
{ AV_CODEC_ID_VP6A, MKTAG('V','P','6','A') },
{ AV_CODEC_ID_VP6F, MKTAG('V','P','6','F') },
{ AV_CODEC_ID_NONE, 0 },
};
#if CONFIG_MOV_MUXER
MOV_CLASS(mov)
AVOutputFormat ff_mov_muxer = {
.name = "mov",
.long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"),
.extensions = "mov",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){
ff_codec_movvideo_tags, ff_codec_movaudio_tags, 0
},
.check_bitstream = mov_check_bitstream,
.priv_class = &mov_muxer_class,
};
#endif
#if CONFIG_TGP_MUXER
MOV_CLASS(tgp)
AVOutputFormat ff_tgp_muxer = {
.name = "3gp",
.long_name = NULL_IF_CONFIG_SMALL("3GP (3GPP file format)"),
.extensions = "3gp",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AMR_NB,
.video_codec = AV_CODEC_ID_H263,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &tgp_muxer_class,
};
#endif
#if CONFIG_MP4_MUXER
MOV_CLASS(mp4)
AVOutputFormat ff_mp4_muxer = {
.name = "mp4",
.long_name = NULL_IF_CONFIG_SMALL("MP4 (MPEG-4 Part 14)"),
.mime_type = "video/mp4",
.extensions = "mp4",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &mp4_muxer_class,
};
#endif
#if CONFIG_PSP_MUXER
MOV_CLASS(psp)
AVOutputFormat ff_psp_muxer = {
.name = "psp",
.long_name = NULL_IF_CONFIG_SMALL("PSP MP4 (MPEG-4 Part 14)"),
.extensions = "mp4,psp",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = CONFIG_LIBX264_ENCODER ?
AV_CODEC_ID_H264 : AV_CODEC_ID_MPEG4,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_mp4_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &psp_muxer_class,
};
#endif
#if CONFIG_TG2_MUXER
MOV_CLASS(tg2)
AVOutputFormat ff_tg2_muxer = {
.name = "3g2",
.long_name = NULL_IF_CONFIG_SMALL("3GP2 (3GPP2 file format)"),
.extensions = "3g2",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AMR_NB,
.video_codec = AV_CODEC_ID_H263,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_3gp_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &tg2_muxer_class,
};
#endif
#if CONFIG_IPOD_MUXER
MOV_CLASS(ipod)
AVOutputFormat ff_ipod_muxer = {
.name = "ipod",
.long_name = NULL_IF_CONFIG_SMALL("iPod H.264 MP4 (MPEG-4 Part 14)"),
.mime_type = "video/mp4",
.extensions = "m4v,m4a,m4b",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){ codec_ipod_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &ipod_muxer_class,
};
#endif
#if CONFIG_ISMV_MUXER
MOV_CLASS(ismv)
AVOutputFormat ff_ismv_muxer = {
.name = "ismv",
.long_name = NULL_IF_CONFIG_SMALL("ISMV/ISMA (Smooth Streaming)"),
.mime_type = "video/mp4",
.extensions = "ismv,isma",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH | AVFMT_TS_NEGATIVE,
.codec_tag = (const AVCodecTag* const []){
codec_mp4_tags, codec_ism_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &ismv_muxer_class,
};
#endif
#if CONFIG_F4V_MUXER
MOV_CLASS(f4v)
AVOutputFormat ff_f4v_muxer = {
.name = "f4v",
.long_name = NULL_IF_CONFIG_SMALL("F4V Adobe Flash Video"),
.mime_type = "application/f4v",
.extensions = "f4v",
.priv_data_size = sizeof(MOVMuxContext),
.audio_codec = AV_CODEC_ID_AAC,
.video_codec = AV_CODEC_ID_H264,
.init = mov_init,
.write_header = mov_write_header,
.write_packet = mov_write_packet,
.write_trailer = mov_write_trailer,
.deinit = mov_free,
.flags = AVFMT_GLOBALHEADER | AVFMT_ALLOW_FLUSH,
.codec_tag = (const AVCodecTag* const []){ codec_f4v_tags, 0 },
.check_bitstream = mov_check_bitstream,
.priv_class = &f4v_muxer_class,
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_215_0 |
crossvul-cpp_data_bad_3376_0 | /**********************************************************************
regexec.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 "regint.h"
#define USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#ifdef USE_CRNL_AS_LINE_TERMINATOR
#define ONIGENC_IS_MBC_CRNL(enc,p,end) \
(ONIGENC_MBC_TO_CODE(enc,p,end) == 13 && \
ONIGENC_IS_MBC_NEWLINE(enc,(p+enclen(enc,p)),end))
#endif
#ifdef USE_CAPTURE_HISTORY
static void history_tree_free(OnigCaptureTreeNode* node);
static void
history_tree_clear(OnigCaptureTreeNode* node)
{
int i;
if (IS_NOT_NULL(node)) {
for (i = 0; i < node->num_childs; i++) {
if (IS_NOT_NULL(node->childs[i])) {
history_tree_free(node->childs[i]);
}
}
for (i = 0; i < node->allocated; i++) {
node->childs[i] = (OnigCaptureTreeNode* )0;
}
node->num_childs = 0;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
node->group = -1;
}
}
static void
history_tree_free(OnigCaptureTreeNode* node)
{
history_tree_clear(node);
xfree(node);
}
static void
history_root_free(OnigRegion* r)
{
if (IS_NOT_NULL(r->history_root)) {
history_tree_free(r->history_root);
r->history_root = (OnigCaptureTreeNode* )0;
}
}
static OnigCaptureTreeNode*
history_node_new(void)
{
OnigCaptureTreeNode* node;
node = (OnigCaptureTreeNode* )xmalloc(sizeof(OnigCaptureTreeNode));
CHECK_NULL_RETURN(node);
node->childs = (OnigCaptureTreeNode** )0;
node->allocated = 0;
node->num_childs = 0;
node->group = -1;
node->beg = ONIG_REGION_NOTPOS;
node->end = ONIG_REGION_NOTPOS;
return node;
}
static int
history_tree_add_child(OnigCaptureTreeNode* parent, OnigCaptureTreeNode* child)
{
#define HISTORY_TREE_INIT_ALLOC_SIZE 8
if (parent->num_childs >= parent->allocated) {
int n, i;
if (IS_NULL(parent->childs)) {
n = HISTORY_TREE_INIT_ALLOC_SIZE;
parent->childs =
(OnigCaptureTreeNode** )xmalloc(sizeof(OnigCaptureTreeNode*) * n);
}
else {
n = parent->allocated * 2;
parent->childs =
(OnigCaptureTreeNode** )xrealloc(parent->childs,
sizeof(OnigCaptureTreeNode*) * n);
}
CHECK_NULL_RETURN_MEMERR(parent->childs);
for (i = parent->allocated; i < n; i++) {
parent->childs[i] = (OnigCaptureTreeNode* )0;
}
parent->allocated = n;
}
parent->childs[parent->num_childs] = child;
parent->num_childs++;
return 0;
}
static OnigCaptureTreeNode*
history_tree_clone(OnigCaptureTreeNode* node)
{
int i;
OnigCaptureTreeNode *clone, *child;
clone = history_node_new();
CHECK_NULL_RETURN(clone);
clone->beg = node->beg;
clone->end = node->end;
for (i = 0; i < node->num_childs; i++) {
child = history_tree_clone(node->childs[i]);
if (IS_NULL(child)) {
history_tree_free(clone);
return (OnigCaptureTreeNode* )0;
}
history_tree_add_child(clone, child);
}
return clone;
}
extern OnigCaptureTreeNode*
onig_get_capture_tree(OnigRegion* region)
{
return region->history_root;
}
#endif /* USE_CAPTURE_HISTORY */
extern void
onig_region_clear(OnigRegion* region)
{
int i;
for (i = 0; i < region->num_regs; i++) {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(region);
#endif
}
extern int
onig_region_resize(OnigRegion* region, int n)
{
region->num_regs = n;
if (n < ONIG_NREGION)
n = ONIG_NREGION;
if (region->allocated == 0) {
region->beg = (int* )xmalloc(n * sizeof(int));
region->end = (int* )xmalloc(n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
else if (region->allocated < n) {
region->beg = (int* )xrealloc(region->beg, n * sizeof(int));
region->end = (int* )xrealloc(region->end, n * sizeof(int));
if (region->beg == 0 || region->end == 0)
return ONIGERR_MEMORY;
region->allocated = n;
}
return 0;
}
static int
onig_region_resize_clear(OnigRegion* region, int n)
{
int r;
r = onig_region_resize(region, n);
if (r != 0) return r;
onig_region_clear(region);
return 0;
}
extern int
onig_region_set(OnigRegion* region, int at, int beg, int end)
{
if (at < 0) return ONIGERR_INVALID_ARGUMENT;
if (at >= region->allocated) {
int r = onig_region_resize(region, at + 1);
if (r < 0) return r;
}
region->beg[at] = beg;
region->end[at] = end;
return 0;
}
extern void
onig_region_init(OnigRegion* region)
{
region->num_regs = 0;
region->allocated = 0;
region->beg = (int* )0;
region->end = (int* )0;
region->history_root = (OnigCaptureTreeNode* )0;
}
extern OnigRegion*
onig_region_new(void)
{
OnigRegion* r;
r = (OnigRegion* )xmalloc(sizeof(OnigRegion));
onig_region_init(r);
return r;
}
extern void
onig_region_free(OnigRegion* r, int free_self)
{
if (r) {
if (r->allocated > 0) {
if (r->beg) xfree(r->beg);
if (r->end) xfree(r->end);
r->allocated = 0;
}
#ifdef USE_CAPTURE_HISTORY
history_root_free(r);
#endif
if (free_self) xfree(r);
}
}
extern void
onig_region_copy(OnigRegion* to, OnigRegion* from)
{
#define RREGC_SIZE (sizeof(int) * from->num_regs)
int i;
if (to == from) return;
if (to->allocated == 0) {
if (from->num_regs > 0) {
to->beg = (int* )xmalloc(RREGC_SIZE);
to->end = (int* )xmalloc(RREGC_SIZE);
to->allocated = from->num_regs;
}
}
else if (to->allocated < from->num_regs) {
to->beg = (int* )xrealloc(to->beg, RREGC_SIZE);
to->end = (int* )xrealloc(to->end, RREGC_SIZE);
to->allocated = from->num_regs;
}
for (i = 0; i < from->num_regs; i++) {
to->beg[i] = from->beg[i];
to->end[i] = from->end[i];
}
to->num_regs = from->num_regs;
#ifdef USE_CAPTURE_HISTORY
history_root_free(to);
if (IS_NOT_NULL(from->history_root)) {
to->history_root = history_tree_clone(from->history_root);
}
#endif
}
/** stack **/
#define INVALID_STACK_INDEX -1
/* stack type */
/* used by normal-POP */
#define STK_ALT 0x0001
#define STK_LOOK_BEHIND_NOT 0x0002
#define STK_POS_NOT 0x0003
/* handled by normal-POP */
#define STK_MEM_START 0x0100
#define STK_MEM_END 0x8200
#define STK_REPEAT_INC 0x0300
#define STK_STATE_CHECK_MARK 0x1000
/* avoided by normal-POP */
#define STK_NULL_CHECK_START 0x3000
#define STK_NULL_CHECK_END 0x5000 /* for recursive call */
#define STK_MEM_END_MARK 0x8400
#define STK_POS 0x0500 /* used when POP-POS */
#define STK_STOP_BT 0x0600 /* mark for "(?>...)" */
#define STK_REPEAT 0x0700
#define STK_CALL_FRAME 0x0800
#define STK_RETURN 0x0900
#define STK_VOID 0x0a00 /* for fill a blank */
/* stack type check mask */
#define STK_MASK_POP_USED 0x00ff
#define STK_MASK_TO_VOID_TARGET 0x10ff
#define STK_MASK_MEM_END_OR_MARK 0x8000 /* MEM_END or MEM_END_MARK */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).best_len = ONIG_MISMATCH;\
(msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\
} while(0)
#else
#define MATCH_ARG_INIT(msa, reg, arg_option, arg_region, arg_start) do {\
(msa).stack_p = (void* )0;\
(msa).options = (arg_option);\
(msa).region = (arg_region);\
(msa).start = (arg_start);\
(msa).ptr_num = (reg)->num_repeat + (reg)->num_mem * 2;\
} while(0)
#endif
#ifdef USE_COMBINATION_EXPLOSION_CHECK
#define STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE 16
#define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num) do { \
if ((state_num) > 0 && str_len >= STATE_CHECK_STRING_THRESHOLD_LEN) {\
unsigned int size = (unsigned int )(((str_len) + 1) * (state_num) + 7) >> 3;\
offset = ((offset) * (state_num)) >> 3;\
if (size > 0 && offset < size && size < STATE_CHECK_BUFF_MAX_SIZE) {\
if (size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) \
(msa).state_check_buff = (void* )xmalloc(size);\
else \
(msa).state_check_buff = (void* )xalloca(size);\
xmemset(((char* )((msa).state_check_buff)+(offset)), 0, \
(size_t )(size - (offset))); \
(msa).state_check_buff_size = size;\
}\
else {\
(msa).state_check_buff = (void* )0;\
(msa).state_check_buff_size = 0;\
}\
}\
else {\
(msa).state_check_buff = (void* )0;\
(msa).state_check_buff_size = 0;\
}\
} while(0)
#define MATCH_ARG_FREE(msa) do {\
if ((msa).stack_p) xfree((msa).stack_p);\
if ((msa).state_check_buff_size >= STATE_CHECK_BUFF_MALLOC_THRESHOLD_SIZE) { \
if ((msa).state_check_buff) xfree((msa).state_check_buff);\
}\
} while(0)
#else
#define STATE_CHECK_BUFF_INIT(msa, str_len, offset, state_num)
#define MATCH_ARG_FREE(msa) if ((msa).stack_p) xfree((msa).stack_p)
#endif
#define ALLOCA_PTR_NUM_LIMIT 50
#define STACK_INIT(stack_num) do {\
if (msa->stack_p) {\
is_alloca = 0;\
alloc_base = msa->stack_p;\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + msa->stack_n;\
}\
else if (msa->ptr_num > ALLOCA_PTR_NUM_LIMIT) {\
is_alloca = 0;\
alloc_base = (char* )xmalloc(sizeof(OnigStackIndex) * msa->ptr_num\
+ sizeof(OnigStackType) * (stack_num));\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
else {\
is_alloca = 1;\
alloc_base = (char* )xalloca(sizeof(OnigStackIndex) * msa->ptr_num\
+ sizeof(OnigStackType) * (stack_num));\
stk_base = (OnigStackType* )(alloc_base\
+ (sizeof(OnigStackIndex) * msa->ptr_num));\
stk = stk_base;\
stk_end = stk_base + (stack_num);\
}\
} while(0);
#define STACK_SAVE do{\
msa->stack_n = stk_end - stk_base;\
if (is_alloca != 0) {\
size_t size = sizeof(OnigStackIndex) * msa->ptr_num \
+ sizeof(OnigStackType) * msa->stack_n;\
msa->stack_p = xmalloc(size);\
xmemcpy(msa->stack_p, alloc_base, size);\
}\
else {\
msa->stack_p = alloc_base;\
};\
} while(0)
#define UPDATE_FOR_STACK_REALLOC do{\
repeat_stk = (OnigStackIndex* )alloc_base;\
mem_start_stk = (OnigStackIndex* )(repeat_stk + reg->num_repeat);\
mem_end_stk = mem_start_stk + num_mem;\
mem_start_stk--; /* for index start from 1 */\
mem_end_stk--; /* for index start from 1 */\
} while(0)
static unsigned int MatchStackLimitSize = DEFAULT_MATCH_STACK_LIMIT_SIZE;
extern unsigned int
onig_get_match_stack_limit_size(void)
{
return MatchStackLimitSize;
}
extern int
onig_set_match_stack_limit_size(unsigned int size)
{
MatchStackLimitSize = size;
return 0;
}
static int
stack_double(int is_alloca, char** arg_alloc_base,
OnigStackType** arg_stk_base,
OnigStackType** arg_stk_end, OnigStackType** arg_stk,
OnigMatchArg* msa)
{
unsigned int n;
int used;
size_t size;
size_t new_size;
char* alloc_base;
char* new_alloc_base;
OnigStackType *stk_base, *stk_end, *stk;
alloc_base = *arg_alloc_base;
stk_base = *arg_stk_base;
stk_end = *arg_stk_end;
stk = *arg_stk;
n = stk_end - stk_base;
size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n;
n *= 2;
new_size = sizeof(OnigStackIndex) * msa->ptr_num + sizeof(OnigStackType) * n;
if (is_alloca != 0) {
new_alloc_base = (char* )xmalloc(new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
xmemcpy(new_alloc_base, alloc_base, size);
}
else {
if (MatchStackLimitSize != 0 && n > MatchStackLimitSize) {
if ((unsigned int )(stk_end - stk_base) == MatchStackLimitSize)
return ONIGERR_MATCH_STACK_LIMIT_OVER;
else
n = MatchStackLimitSize;
}
new_alloc_base = (char* )xrealloc(alloc_base, new_size);
if (IS_NULL(new_alloc_base)) {
STACK_SAVE;
return ONIGERR_MEMORY;
}
}
alloc_base = new_alloc_base;
used = stk - stk_base;
*arg_alloc_base = alloc_base;
*arg_stk_base = (OnigStackType* )(alloc_base
+ (sizeof(OnigStackIndex) * msa->ptr_num));
*arg_stk = *arg_stk_base + used;
*arg_stk_end = *arg_stk_base + n;
return 0;
}
#define STACK_ENSURE(n) do {\
if (stk_end - stk < (n)) {\
int r = stack_double(is_alloca, &alloc_base, &stk_base, &stk_end, &stk,\
msa);\
if (r != 0) { STACK_SAVE; return r; } \
is_alloca = 0;\
UPDATE_FOR_STACK_REALLOC;\
}\
} while(0)
#define STACK_AT(index) (stk_base + (index))
#define GET_STACK_INDEX(stk) ((stk) - stk_base)
#define STACK_PUSH_TYPE(stack_type) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
STACK_INC;\
} while(0)
#define IS_TO_VOID_TARGET(stk) (((stk)->type & STK_MASK_TO_VOID_TARGET) != 0)
#ifdef USE_COMBINATION_EXPLOSION_CHECK
#define STATE_CHECK_POS(s,snum) \
(((s) - str) * num_comb_exp_check + ((snum) - 1))
#define STATE_CHECK_VAL(v,snum) do {\
if (state_check_buff != NULL) {\
int x = STATE_CHECK_POS(s,snum);\
(v) = state_check_buff[x/8] & (1<<(x%8));\
}\
else (v) = 0;\
} while(0)
#define ELSE_IF_STATE_CHECK_MARK(stk) \
else if ((stk)->type == STK_STATE_CHECK_MARK) { \
int x = STATE_CHECK_POS(stk->u.state.pstr, stk->u.state.state_check);\
state_check_buff[x/8] |= (1<<(x%8)); \
}
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
stk->u.state.state_check = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.state_check = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_ALT_WITH_STATE_CHECK(pat,s,sprev,snum) do {\
STACK_ENSURE(1);\
stk->type = STK_ALT;\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
stk->u.state.state_check = ((state_check_buff != NULL) ? (snum) : 0);\
STACK_INC;\
} while(0)
#define STACK_PUSH_STATE_CHECK(s,snum) do {\
if (state_check_buff != NULL) {\
STACK_ENSURE(1);\
stk->type = STK_STATE_CHECK_MARK;\
stk->u.state.pstr = (s);\
stk->u.state.state_check = (snum);\
STACK_INC;\
}\
} while(0)
#else /* USE_COMBINATION_EXPLOSION_CHECK */
#define ELSE_IF_STATE_CHECK_MARK(stk)
#define STACK_PUSH(stack_type,pat,s,sprev) do {\
STACK_ENSURE(1);\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
stk->u.state.pstr = (s);\
stk->u.state.pstr_prev = (sprev);\
STACK_INC;\
} while(0)
#define STACK_PUSH_ENSURED(stack_type,pat) do {\
stk->type = (stack_type);\
stk->u.state.pcode = (pat);\
STACK_INC;\
} while(0)
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
#define STACK_PUSH_ALT(pat,s,sprev) STACK_PUSH(STK_ALT,pat,s,sprev)
#define STACK_PUSH_POS(s,sprev) STACK_PUSH(STK_POS,NULL_UCHARP,s,sprev)
#define STACK_PUSH_POS_NOT(pat,s,sprev) STACK_PUSH(STK_POS_NOT,pat,s,sprev)
#define STACK_PUSH_STOP_BT STACK_PUSH_TYPE(STK_STOP_BT)
#define STACK_PUSH_LOOK_BEHIND_NOT(pat,s,sprev) \
STACK_PUSH(STK_LOOK_BEHIND_NOT,pat,s,sprev)
#define STACK_PUSH_REPEAT(id, pat) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT;\
stk->u.repeat.num = (id);\
stk->u.repeat.pcode = (pat);\
stk->u.repeat.count = 0;\
STACK_INC;\
} while(0)
#define STACK_PUSH_REPEAT_INC(sindex) do {\
STACK_ENSURE(1);\
stk->type = STK_REPEAT_INC;\
stk->u.repeat_inc.si = (sindex);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_START(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_START;\
stk->u.mem.num = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.start = mem_start_stk[mnum];\
stk->u.mem.end = mem_end_stk[mnum];\
mem_start_stk[mnum] = GET_STACK_INDEX(stk);\
mem_end_stk[mnum] = INVALID_STACK_INDEX;\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END(mnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END;\
stk->u.mem.num = (mnum);\
stk->u.mem.pstr = (s);\
stk->u.mem.start = mem_start_stk[mnum];\
stk->u.mem.end = mem_end_stk[mnum];\
mem_end_stk[mnum] = GET_STACK_INDEX(stk);\
STACK_INC;\
} while(0)
#define STACK_PUSH_MEM_END_MARK(mnum) do {\
STACK_ENSURE(1);\
stk->type = STK_MEM_END_MARK;\
stk->u.mem.num = (mnum);\
STACK_INC;\
} while(0)
#define STACK_GET_MEM_START(mnum, k) do {\
int level = 0;\
k = stk;\
while (k > stk_base) {\
k--;\
if ((k->type & STK_MASK_MEM_END_OR_MARK) != 0 \
&& k->u.mem.num == (mnum)) {\
level++;\
}\
else if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) break;\
level--;\
}\
}\
} while(0)
#define STACK_GET_MEM_RANGE(k, mnum, start, end) do {\
int level = 0;\
while (k < stk) {\
if (k->type == STK_MEM_START && k->u.mem.num == (mnum)) {\
if (level == 0) (start) = k->u.mem.pstr;\
level++;\
}\
else if (k->type == STK_MEM_END && k->u.mem.num == (mnum)) {\
level--;\
if (level == 0) {\
(end) = k->u.mem.pstr;\
break;\
}\
}\
k++;\
}\
} while(0)
#define STACK_PUSH_NULL_CHECK_START(cnum, s) do {\
STACK_ENSURE(1);\
stk->type = STK_NULL_CHECK_START;\
stk->u.null_check.num = (cnum);\
stk->u.null_check.pstr = (s);\
STACK_INC;\
} while(0)
#define STACK_PUSH_NULL_CHECK_END(cnum) do {\
STACK_ENSURE(1);\
stk->type = STK_NULL_CHECK_END;\
stk->u.null_check.num = (cnum);\
STACK_INC;\
} while(0)
#define STACK_PUSH_CALL_FRAME(pat) do {\
STACK_ENSURE(1);\
stk->type = STK_CALL_FRAME;\
stk->u.call_frame.ret_addr = (pat);\
STACK_INC;\
} while(0)
#define STACK_PUSH_RETURN do {\
STACK_ENSURE(1);\
stk->type = STK_RETURN;\
STACK_INC;\
} while(0)
#ifdef ONIG_DEBUG
#define STACK_BASE_CHECK(p, at) \
if ((p) < stk_base) {\
fprintf(stderr, "at %s\n", at);\
goto stack_error;\
}
#else
#define STACK_BASE_CHECK(p, at)
#endif
#define STACK_POP_ONE do {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_ONE"); \
} while(0)
#define STACK_POP do {\
switch (pop_level) {\
case STACK_POP_LEVEL_FREE:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
case STACK_POP_LEVEL_MEM_START:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 2"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
default:\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP 3"); \
if ((stk->type & STK_MASK_POP_USED) != 0) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
break;\
}\
} while(0)
#define STACK_POP_TIL_POS_NOT do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_TIL_POS_NOT"); \
if (stk->type == STK_POS_NOT) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
} while(0)
#define STACK_POP_TIL_LOOK_BEHIND_NOT do {\
while (1) {\
stk--;\
STACK_BASE_CHECK(stk, "STACK_POP_TIL_LOOK_BEHIND_NOT"); \
if (stk->type == STK_LOOK_BEHIND_NOT) break;\
else if (stk->type == STK_MEM_START) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
else if (stk->type == STK_REPEAT_INC) {\
STACK_AT(stk->u.repeat_inc.si)->u.repeat.count--;\
}\
else if (stk->type == STK_MEM_END) {\
mem_start_stk[stk->u.mem.num] = stk->u.mem.start;\
mem_end_stk[stk->u.mem.num] = stk->u.mem.end;\
}\
ELSE_IF_STATE_CHECK_MARK(stk);\
}\
} while(0)
#define STACK_POS_END(k) do {\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_POS_END"); \
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_POS) {\
k->type = STK_VOID;\
break;\
}\
}\
} while(0)
#define STACK_STOP_BT_END do {\
OnigStackType *k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_STOP_BT_END"); \
if (IS_TO_VOID_TARGET(k)) {\
k->type = STK_VOID;\
}\
else if (k->type == STK_STOP_BT) {\
k->type = STK_VOID;\
break;\
}\
}\
} while(0)
#define STACK_NULL_CHECK(isnull,id,s) do {\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
(isnull) = (k->u.null_check.pstr == (s));\
break;\
}\
}\
}\
} while(0)
#define STACK_NULL_CHECK_REC(isnull,id,s) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_REC"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (level == 0) {\
(isnull) = (k->u.null_check.pstr == (s));\
break;\
}\
else level--;\
}\
}\
else if (k->type == STK_NULL_CHECK_END) {\
level++;\
}\
}\
} while(0)
#define STACK_NULL_CHECK_MEMST(isnull,id,s,reg) do {\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (k->u.null_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (k->u.mem.end == INVALID_STACK_INDEX) {\
(isnull) = 0; break;\
}\
if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\
endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\
else\
endp = (UChar* )k->u.mem.end;\
if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
k++;\
}\
break;\
}\
}\
}\
}\
} while(0)
#define STACK_NULL_CHECK_MEMST_REC(isnull,id,s,reg) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_NULL_CHECK_MEMST_REC"); \
if (k->type == STK_NULL_CHECK_START) {\
if (k->u.null_check.num == (id)) {\
if (level == 0) {\
if (k->u.null_check.pstr != (s)) {\
(isnull) = 0;\
break;\
}\
else {\
UChar* endp;\
(isnull) = 1;\
while (k < stk) {\
if (k->type == STK_MEM_START) {\
if (k->u.mem.end == INVALID_STACK_INDEX) {\
(isnull) = 0; break;\
}\
if (BIT_STATUS_AT(reg->bt_mem_end, k->u.mem.num))\
endp = STACK_AT(k->u.mem.end)->u.mem.pstr;\
else\
endp = (UChar* )k->u.mem.end;\
if (STACK_AT(k->u.mem.start)->u.mem.pstr != endp) {\
(isnull) = 0; break;\
}\
else if (endp != s) {\
(isnull) = -1; /* empty, but position changed */ \
}\
}\
k++;\
}\
break;\
}\
}\
else {\
level--;\
}\
}\
}\
else if (k->type == STK_NULL_CHECK_END) {\
if (k->u.null_check.num == (id)) level++;\
}\
}\
} while(0)
#define STACK_GET_REPEAT(id, k) do {\
int level = 0;\
k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_GET_REPEAT"); \
if (k->type == STK_REPEAT) {\
if (level == 0) {\
if (k->u.repeat.num == (id)) {\
break;\
}\
}\
}\
else if (k->type == STK_CALL_FRAME) level--;\
else if (k->type == STK_RETURN) level++;\
}\
} while(0)
#define STACK_RETURN(addr) do {\
int level = 0;\
OnigStackType* k = stk;\
while (1) {\
k--;\
STACK_BASE_CHECK(k, "STACK_RETURN"); \
if (k->type == STK_CALL_FRAME) {\
if (level == 0) {\
(addr) = k->u.call_frame.ret_addr;\
break;\
}\
else level--;\
}\
else if (k->type == STK_RETURN)\
level++;\
}\
} while(0)
#define STRING_CMP(s1,s2,len) do {\
while (len-- > 0) {\
if (*s1++ != *s2++) goto fail;\
}\
} while(0)
#define STRING_CMP_IC(case_fold_flag,s1,ps2,len) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
goto fail; \
} while(0)
static int string_cmp_ic(OnigEncoding enc, int case_fold_flag,
UChar* s1, UChar** ps2, int mblen)
{
UChar buf1[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar buf2[ONIGENC_MBC_CASE_FOLD_MAXLEN];
UChar *p1, *p2, *end1, *s2, *end2;
int len1, len2;
s2 = *ps2;
end1 = s1 + mblen;
end2 = s2 + mblen;
while (s1 < end1) {
len1 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s1, end1, buf1);
len2 = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &s2, end2, buf2);
if (len1 != len2) return 0;
p1 = buf1;
p2 = buf2;
while (len1-- > 0) {
if (*p1 != *p2) return 0;
p1++;
p2++;
}
}
*ps2 = s2;
return 1;
}
#define STRING_CMP_VALUE(s1,s2,len,is_fail) do {\
is_fail = 0;\
while (len-- > 0) {\
if (*s1++ != *s2++) {\
is_fail = 1; break;\
}\
}\
} while(0)
#define STRING_CMP_VALUE_IC(case_fold_flag,s1,ps2,len,is_fail) do {\
if (string_cmp_ic(encode, case_fold_flag, s1, ps2, len) == 0) \
is_fail = 1; \
else \
is_fail = 0; \
} while(0)
#define IS_EMPTY_STR (str == end)
#define ON_STR_BEGIN(s) ((s) == str)
#define ON_STR_END(s) ((s) == end)
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#define DATA_ENSURE_CHECK1 (s < right_range)
#define DATA_ENSURE_CHECK(n) (s + (n) <= right_range)
#define DATA_ENSURE(n) if (s + (n) > right_range) goto fail
#else
#define DATA_ENSURE_CHECK1 (s < end)
#define DATA_ENSURE_CHECK(n) (s + (n) <= end)
#define DATA_ENSURE(n) if (s + (n) > end) goto fail
#endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */
#ifdef USE_CAPTURE_HISTORY
static int
make_capture_history_tree(OnigCaptureTreeNode* node, OnigStackType** kp,
OnigStackType* stk_top, UChar* str, regex_t* reg)
{
int n, r;
OnigCaptureTreeNode* child;
OnigStackType* k = *kp;
while (k < stk_top) {
if (k->type == STK_MEM_START) {
n = k->u.mem.num;
if (n <= ONIG_MAX_CAPTURE_HISTORY_GROUP &&
BIT_STATUS_AT(reg->capture_history, n) != 0) {
child = history_node_new();
CHECK_NULL_RETURN_MEMERR(child);
child->group = n;
child->beg = (int )(k->u.mem.pstr - str);
r = history_tree_add_child(node, child);
if (r != 0) return r;
*kp = (k + 1);
r = make_capture_history_tree(child, kp, stk_top, str, reg);
if (r != 0) return r;
k = *kp;
child->end = (int )(k->u.mem.pstr - str);
}
}
else if (k->type == STK_MEM_END) {
if (k->u.mem.num == node->group) {
node->end = (int )(k->u.mem.pstr - str);
*kp = k;
return 0;
}
}
k++;
}
return 1; /* 1: root node ending. */
}
#endif
#ifdef USE_BACKREF_WITH_LEVEL
static int mem_is_in_memp(int mem, int num, UChar* memp)
{
int i;
MemNumType m;
for (i = 0; i < num; i++) {
GET_MEMNUM_INC(m, memp);
if (mem == (int )m) return 1;
}
return 0;
}
static int backref_match_at_nested_level(regex_t* reg
, OnigStackType* top, OnigStackType* stk_base
, int ignore_case, int case_fold_flag
, int nest, int mem_num, UChar* memp, UChar** s, const UChar* send)
{
UChar *ss, *p, *pstart, *pend = NULL_UCHARP;
int level;
OnigStackType* k;
level = 0;
k = top;
k--;
while (k >= stk_base) {
if (k->type == STK_CALL_FRAME) {
level--;
}
else if (k->type == STK_RETURN) {
level++;
}
else if (level == nest) {
if (k->type == STK_MEM_START) {
if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) {
pstart = k->u.mem.pstr;
if (pend != NULL_UCHARP) {
if (pend - pstart > send - *s) return 0; /* or goto next_mem; */
p = pstart;
ss = *s;
if (ignore_case != 0) {
if (string_cmp_ic(reg->enc, case_fold_flag,
pstart, &ss, (int )(pend - pstart)) == 0)
return 0; /* or goto next_mem; */
}
else {
while (p < pend) {
if (*p++ != *ss++) return 0; /* or goto next_mem; */
}
}
*s = ss;
return 1;
}
}
}
else if (k->type == STK_MEM_END) {
if (mem_is_in_memp(k->u.mem.num, mem_num, memp)) {
pend = k->u.mem.pstr;
}
}
}
k--;
}
return 0;
}
#endif /* USE_BACKREF_WITH_LEVEL */
#ifdef ONIG_DEBUG_STATISTICS
#define USE_TIMEOFDAY
#ifdef USE_TIMEOFDAY
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
static struct timeval ts, te;
#define GETTIME(t) gettimeofday(&(t), (struct timezone* )0)
#define TIMEDIFF(te,ts) (((te).tv_usec - (ts).tv_usec) + \
(((te).tv_sec - (ts).tv_sec)*1000000))
#else
#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif
static struct tms ts, te;
#define GETTIME(t) times(&(t))
#define TIMEDIFF(te,ts) ((te).tms_utime - (ts).tms_utime)
#endif
static int OpCounter[256];
static int OpPrevCounter[256];
static unsigned long OpTime[256];
static int OpCurr = OP_FINISH;
static int OpPrevTarget = OP_FAIL;
static int MaxStackDepth = 0;
#define MOP_IN(opcode) do {\
if (opcode == OpPrevTarget) OpPrevCounter[OpCurr]++;\
OpCurr = opcode;\
OpCounter[opcode]++;\
GETTIME(ts);\
} while(0)
#define MOP_OUT do {\
GETTIME(te);\
OpTime[OpCurr] += TIMEDIFF(te, ts);\
} while(0)
extern void
onig_statistics_init(void)
{
int i;
for (i = 0; i < 256; i++) {
OpCounter[i] = OpPrevCounter[i] = 0; OpTime[i] = 0;
}
MaxStackDepth = 0;
}
extern int
onig_print_statistics(FILE* f)
{
int r;
int i;
r = fprintf(f, " count prev time\n");
if (r < 0) return -1;
for (i = 0; OnigOpInfo[i].opcode >= 0; i++) {
r = fprintf(f, "%8d: %8d: %10ld: %s\n",
OpCounter[i], OpPrevCounter[i], OpTime[i], OnigOpInfo[i].name);
if (r < 0) return -1;
}
r = fprintf(f, "\nmax stack depth: %d\n", MaxStackDepth);
if (r < 0) return -1;
return 0;
}
#define STACK_INC do {\
stk++;\
if (stk - stk_base > MaxStackDepth) \
MaxStackDepth = stk - stk_base;\
} while(0)
#else
#define STACK_INC stk++
#define MOP_IN(opcode)
#define MOP_OUT
#endif
/* matching region of POSIX API */
typedef int regoff_t;
typedef struct {
regoff_t rm_so;
regoff_t rm_eo;
} posix_regmatch_t;
/* match data(str - end) from position (sstart). */
/* if sstart == str then set sprev to NULL. */
static int
match_at(regex_t* reg, const UChar* str, const UChar* end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar* right_range,
#endif
const UChar* sstart, UChar* sprev, OnigMatchArg* msa)
{
static UChar FinishCode[] = { OP_FINISH };
int i, n, num_mem, best_len, pop_level;
LengthType tlen, tlen2;
MemNumType mem;
RelAddrType addr;
UChar *s, *q, *sbegin;
int is_alloca;
char *alloc_base;
OnigStackType *stk_base, *stk, *stk_end;
OnigStackType *stkp; /* used as any purpose. */
OnigStackIndex si;
OnigStackIndex *repeat_stk;
OnigStackIndex *mem_start_stk, *mem_end_stk;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
int scv;
unsigned char* state_check_buff = msa->state_check_buff;
int num_comb_exp_check = reg->num_comb_exp_check;
#endif
UChar *p = reg->p;
OnigOptionType option = reg->options;
OnigEncoding encode = reg->enc;
OnigCaseFoldType case_fold_flag = reg->case_fold_flag;
//n = reg->num_repeat + reg->num_mem * 2;
pop_level = reg->stack_pop_level;
num_mem = reg->num_mem;
STACK_INIT(INIT_MATCH_STACK_SIZE);
UPDATE_FOR_STACK_REALLOC;
for (i = 1; i <= num_mem; i++) {
mem_start_stk[i] = mem_end_stk[i] = INVALID_STACK_INDEX;
}
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "match_at: str: %d, end: %d, start: %d, sprev: %d\n",
(int )str, (int )end, (int )sstart, (int )sprev);
fprintf(stderr, "size: %d, start offset: %d\n",
(int )(end - str), (int )(sstart - str));
#endif
STACK_PUSH_ENSURED(STK_ALT, FinishCode); /* bottom stack */
best_len = ONIG_MISMATCH;
s = (UChar* )sstart;
while (1) {
#ifdef ONIG_DEBUG_MATCH
{
UChar *q, *bp, buf[50];
int len;
fprintf(stderr, "%4d> \"", (int )(s - str));
bp = buf;
for (i = 0, q = s; i < 7 && q < end; i++) {
len = enclen(encode, q);
while (len-- > 0) *bp++ = *q++;
}
if (q < end) { xmemcpy(bp, "...\"", 4); bp += 4; }
else { xmemcpy(bp, "\"", 1); bp += 1; }
*bp = 0;
fputs((char* )buf, stderr);
for (i = 0; i < 20 - (bp - buf); i++) fputc(' ', stderr);
onig_print_compiled_byte_code(stderr, p, NULL, encode);
fprintf(stderr, "\n");
}
#endif
sbegin = s;
switch (*p++) {
case OP_END: MOP_IN(OP_END);
n = s - sstart;
if (n > best_len) {
OnigRegion* region;
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(option)) {
if (n > msa->best_len) {
msa->best_len = n;
msa->best_s = (UChar* )sstart;
}
else
goto end_best_len;
}
#endif
best_len = n;
region = msa->region;
if (region) {
#ifdef USE_POSIX_API_REGION_OPTION
if (IS_POSIX_REGION(msa->options)) {
posix_regmatch_t* rmt = (posix_regmatch_t* )region;
rmt[0].rm_so = sstart - str;
rmt[0].rm_eo = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
rmt[i].rm_so = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
rmt[i].rm_so = (UChar* )((void* )(mem_start_stk[i])) - str;
rmt[i].rm_eo = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
rmt[i].rm_so = rmt[i].rm_eo = ONIG_REGION_NOTPOS;
}
}
}
else {
#endif /* USE_POSIX_API_REGION_OPTION */
region->beg[0] = sstart - str;
region->end[0] = s - str;
for (i = 1; i <= num_mem; i++) {
if (mem_end_stk[i] != INVALID_STACK_INDEX) {
if (BIT_STATUS_AT(reg->bt_mem_start, i))
region->beg[i] = STACK_AT(mem_start_stk[i])->u.mem.pstr - str;
else
region->beg[i] = (UChar* )((void* )mem_start_stk[i]) - str;
region->end[i] = (BIT_STATUS_AT(reg->bt_mem_end, i)
? STACK_AT(mem_end_stk[i])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[i])) - str;
}
else {
region->beg[i] = region->end[i] = ONIG_REGION_NOTPOS;
}
}
#ifdef USE_CAPTURE_HISTORY
if (reg->capture_history != 0) {
int r;
OnigCaptureTreeNode* node;
if (IS_NULL(region->history_root)) {
region->history_root = node = history_node_new();
CHECK_NULL_RETURN_MEMERR(node);
}
else {
node = region->history_root;
history_tree_clear(node);
}
node->group = 0;
node->beg = sstart - str;
node->end = s - str;
stkp = stk_base;
r = make_capture_history_tree(region->history_root, &stkp,
stk, (UChar* )str, reg);
if (r < 0) {
best_len = r; /* error code */
goto finish;
}
}
#endif /* USE_CAPTURE_HISTORY */
#ifdef USE_POSIX_API_REGION_OPTION
} /* else IS_POSIX_REGION() */
#endif
} /* if (region) */
} /* n > best_len */
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
end_best_len:
#endif
MOP_OUT;
if (IS_FIND_CONDITION(option)) {
if (IS_FIND_NOT_EMPTY(option) && s == sstart) {
best_len = ONIG_MISMATCH;
goto fail; /* for retry */
}
if (IS_FIND_LONGEST(option) && DATA_ENSURE_CHECK1) {
goto fail; /* for retry */
}
}
/* default behavior: return first-matching result. */
goto finish;
break;
case OP_EXACT1: MOP_IN(OP_EXACT1);
DATA_ENSURE(1);
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACT1_IC: MOP_IN(OP_EXACT1_IC);
{
int len;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) {
goto fail;
}
p++; q++;
}
}
MOP_OUT;
break;
case OP_EXACT2: MOP_IN(OP_EXACT2);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT3: MOP_IN(OP_EXACT3);
DATA_ENSURE(3);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT4: MOP_IN(OP_EXACT4);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACT5: MOP_IN(OP_EXACT5);
DATA_ENSURE(5);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
sprev = s;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTN: MOP_IN(OP_EXACTN);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen);
while (tlen-- > 0) {
if (*p++ != *s++) goto fail;
}
sprev = s - 1;
MOP_OUT;
continue;
break;
case OP_EXACTN_IC: MOP_IN(OP_EXACTN_IC);
{
int len;
UChar *q, *endp, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
GET_LENGTH_INC(tlen, p);
endp = p + tlen;
while (p < endp) {
sprev = s;
DATA_ENSURE(1);
len = ONIGENC_MBC_CASE_FOLD(encode,
/* DISABLE_CASE_FOLD_MULTI_CHAR(case_fold_flag), */
case_fold_flag,
&s, end, lowbuf);
DATA_ENSURE(0);
q = lowbuf;
while (len-- > 0) {
if (*p != *q) goto fail;
p++; q++;
}
}
}
MOP_OUT;
continue;
break;
case OP_EXACTMB2N1: MOP_IN(OP_EXACTMB2N1);
DATA_ENSURE(2);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
break;
case OP_EXACTMB2N2: MOP_IN(OP_EXACTMB2N2);
DATA_ENSURE(4);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N3: MOP_IN(OP_EXACTMB2N3);
DATA_ENSURE(6);
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
sprev = s;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
MOP_OUT;
continue;
break;
case OP_EXACTMB2N: MOP_IN(OP_EXACTMB2N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 2);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 2;
MOP_OUT;
continue;
break;
case OP_EXACTMB3N: MOP_IN(OP_EXACTMB3N);
GET_LENGTH_INC(tlen, p);
DATA_ENSURE(tlen * 3);
while (tlen-- > 0) {
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - 3;
MOP_OUT;
continue;
break;
case OP_EXACTMBN: MOP_IN(OP_EXACTMBN);
GET_LENGTH_INC(tlen, p); /* mb-len */
GET_LENGTH_INC(tlen2, p); /* string len */
tlen2 *= tlen;
DATA_ENSURE(tlen2);
while (tlen2-- > 0) {
if (*p != *s) goto fail;
p++; s++;
}
sprev = s - tlen;
MOP_OUT;
continue;
break;
case OP_CCLASS: MOP_IN(OP_CCLASS);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) == 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s); /* OP_CCLASS can match mb-code. \D, \S */
MOP_OUT;
break;
case OP_CCLASS_MB: MOP_IN(OP_CCLASS_MB);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) goto fail;
cclass_mb:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len;
DATA_ENSURE(1);
mb_len = enclen(encode, s);
DATA_ENSURE(mb_len);
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (! onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (! onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
MOP_OUT;
break;
case OP_CCLASS_MIX: MOP_IN(OP_CCLASS_MIX);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) == 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NOT: MOP_IN(OP_CCLASS_NOT);
DATA_ENSURE(1);
if (BITSET_AT(((BitSetRef )p), *s) != 0) goto fail;
p += SIZE_BITSET;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_CCLASS_MB_NOT: MOP_IN(OP_CCLASS_MB_NOT);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_HEAD(encode, s)) {
s++;
GET_LENGTH_INC(tlen, p);
p += tlen;
goto cc_mb_not_success;
}
cclass_mb_not:
GET_LENGTH_INC(tlen, p);
{
OnigCodePoint code;
UChar *ss;
int mb_len = enclen(encode, s);
if (! DATA_ENSURE_CHECK(mb_len)) {
DATA_ENSURE(1);
s = (UChar* )end;
p += tlen;
goto cc_mb_not_success;
}
ss = s;
s += mb_len;
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
#ifdef PLATFORM_UNALIGNED_WORD_ACCESS
if (onig_is_in_code_range(p, code)) goto fail;
#else
q = p;
ALIGNMENT_RIGHT(q);
if (onig_is_in_code_range(q, code)) goto fail;
#endif
}
p += tlen;
cc_mb_not_success:
MOP_OUT;
break;
case OP_CCLASS_MIX_NOT: MOP_IN(OP_CCLASS_MIX_NOT);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_HEAD(encode, s)) {
p += SIZE_BITSET;
goto cclass_mb_not;
}
else {
if (BITSET_AT(((BitSetRef )p), *s) != 0)
goto fail;
p += SIZE_BITSET;
GET_LENGTH_INC(tlen, p);
p += tlen;
s++;
}
MOP_OUT;
break;
case OP_CCLASS_NODE: MOP_IN(OP_CCLASS_NODE);
{
OnigCodePoint code;
void *node;
int mb_len;
UChar *ss;
DATA_ENSURE(1);
GET_POINTER_INC(node, p);
mb_len = enclen(encode, s);
ss = s;
s += mb_len;
DATA_ENSURE(0);
code = ONIGENC_MBC_TO_CODE(encode, ss, s);
if (onig_is_code_in_cc_len(mb_len, code, node) == 0) goto fail;
}
MOP_OUT;
break;
case OP_ANYCHAR: MOP_IN(OP_ANYCHAR);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_ML: MOP_IN(OP_ANYCHAR_ML);
DATA_ENSURE(1);
n = enclen(encode, s);
DATA_ENSURE(n);
s += n;
MOP_OUT;
break;
case OP_ANYCHAR_STAR: MOP_IN(OP_ANYCHAR_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR: MOP_IN(OP_ANYCHAR_ML_STAR);
while (DATA_ENSURE_CHECK1) {
STACK_PUSH_ALT(p, s, sprev);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
case OP_ANYCHAR_STAR_PEEK_NEXT: MOP_IN(OP_ANYCHAR_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
p++;
MOP_OUT;
break;
case OP_ANYCHAR_ML_STAR_PEEK_NEXT:MOP_IN(OP_ANYCHAR_ML_STAR_PEEK_NEXT);
while (DATA_ENSURE_CHECK1) {
if (*p == *s) {
STACK_PUSH_ALT(p + 1, s, sprev);
}
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
p++;
MOP_OUT;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_ANYCHAR_STAR: MOP_IN(OP_STATE_CHECK_ANYCHAR_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
DATA_ENSURE(n);
if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) goto fail;
sprev = s;
s += n;
}
MOP_OUT;
break;
case OP_STATE_CHECK_ANYCHAR_ML_STAR:
MOP_IN(OP_STATE_CHECK_ANYCHAR_ML_STAR);
GET_STATE_CHECK_NUM_INC(mem, p);
while (DATA_ENSURE_CHECK1) {
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_ALT_WITH_STATE_CHECK(p, s, sprev, mem);
n = enclen(encode, s);
if (n > 1) {
DATA_ENSURE(n);
sprev = s;
s += n;
}
else {
sprev = s;
s++;
}
}
MOP_OUT;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_WORD: MOP_IN(OP_WORD);
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_NOT_WORD: MOP_IN(OP_NOT_WORD);
DATA_ENSURE(1);
if (ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
s += enclen(encode, s);
MOP_OUT;
break;
case OP_WORD_BOUND: MOP_IN(OP_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
DATA_ENSURE(1);
if (! ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (! ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
== ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
case OP_NOT_WORD_BOUND: MOP_IN(OP_NOT_WORD_BOUND);
if (ON_STR_BEGIN(s)) {
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end))
goto fail;
}
else if (ON_STR_END(s)) {
if (ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
else {
if (ONIGENC_IS_MBC_WORD(encode, s, end)
!= ONIGENC_IS_MBC_WORD(encode, sprev, end))
goto fail;
}
MOP_OUT;
continue;
break;
#ifdef USE_WORD_BEGIN_END
case OP_WORD_BEGIN: MOP_IN(OP_WORD_BEGIN);
if (DATA_ENSURE_CHECK1 && ONIGENC_IS_MBC_WORD(encode, s, end)) {
if (ON_STR_BEGIN(s) || !ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
case OP_WORD_END: MOP_IN(OP_WORD_END);
if (!ON_STR_BEGIN(s) && ONIGENC_IS_MBC_WORD(encode, sprev, end)) {
if (ON_STR_END(s) || !ONIGENC_IS_MBC_WORD(encode, s, end)) {
MOP_OUT;
continue;
}
}
goto fail;
break;
#endif
case OP_BEGIN_BUF: MOP_IN(OP_BEGIN_BUF);
if (! ON_STR_BEGIN(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_END_BUF: MOP_IN(OP_END_BUF);
if (! ON_STR_END(s)) goto fail;
MOP_OUT;
continue;
break;
case OP_BEGIN_LINE: MOP_IN(OP_BEGIN_LINE);
if (ON_STR_BEGIN(s)) {
if (IS_NOTBOL(msa->options)) goto fail;
MOP_OUT;
continue;
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, sprev, end) && !ON_STR_END(s)) {
MOP_OUT;
continue;
}
goto fail;
break;
case OP_END_LINE: MOP_IN(OP_END_LINE);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end)) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
MOP_OUT;
continue;
}
#endif
goto fail;
break;
case OP_SEMI_END_BUF: MOP_IN(OP_SEMI_END_BUF);
if (ON_STR_END(s)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
if (IS_EMPTY_STR || !ONIGENC_IS_MBC_NEWLINE(encode, sprev, end)) {
#endif
if (IS_NOTEOL(msa->options)) goto fail;
MOP_OUT;
continue;
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
}
#endif
}
else if (ONIGENC_IS_MBC_NEWLINE(encode, s, end) &&
ON_STR_END(s + enclen(encode, s))) {
MOP_OUT;
continue;
}
#ifdef USE_CRNL_AS_LINE_TERMINATOR
else if (ONIGENC_IS_MBC_CRNL(encode, s, end)) {
UChar* ss = s + enclen(encode, s);
ss += enclen(encode, ss);
if (ON_STR_END(ss)) {
MOP_OUT;
continue;
}
}
#endif
goto fail;
break;
case OP_BEGIN_POSITION: MOP_IN(OP_BEGIN_POSITION);
if (s != msa->start)
goto fail;
MOP_OUT;
continue;
break;
case OP_MEMORY_START_PUSH: MOP_IN(OP_MEMORY_START_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_START(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_START: MOP_IN(OP_MEMORY_START);
GET_MEMNUM_INC(mem, p);
mem_start_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_PUSH: MOP_IN(OP_MEMORY_END_PUSH);
GET_MEMNUM_INC(mem, p);
STACK_PUSH_MEM_END(mem, s);
MOP_OUT;
continue;
break;
case OP_MEMORY_END: MOP_IN(OP_MEMORY_END);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
MOP_OUT;
continue;
break;
#ifdef USE_SUBEXP_CALL
case OP_MEMORY_END_PUSH_REC: MOP_IN(OP_MEMORY_END_PUSH_REC);
GET_MEMNUM_INC(mem, p);
STACK_GET_MEM_START(mem, stkp); /* should be before push mem-end. */
STACK_PUSH_MEM_END(mem, s);
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
MOP_OUT;
continue;
break;
case OP_MEMORY_END_REC: MOP_IN(OP_MEMORY_END_REC);
GET_MEMNUM_INC(mem, p);
mem_end_stk[mem] = (OnigStackIndex )((void* )s);
STACK_GET_MEM_START(mem, stkp);
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
mem_start_stk[mem] = GET_STACK_INDEX(stkp);
else
mem_start_stk[mem] = (OnigStackIndex )((void* )stkp->u.mem.pstr);
STACK_PUSH_MEM_END_MARK(mem);
MOP_OUT;
continue;
break;
#endif
case OP_BACKREF1: MOP_IN(OP_BACKREF1);
mem = 1;
goto backref;
break;
case OP_BACKREF2: MOP_IN(OP_BACKREF2);
mem = 2;
goto backref;
break;
case OP_BACKREFN: MOP_IN(OP_BACKREFN);
GET_MEMNUM_INC(mem, p);
backref:
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP(pstart, s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREFN_IC: MOP_IN(OP_BACKREFN_IC);
GET_MEMNUM_INC(mem, p);
{
int len;
UChar *pstart, *pend;
/* if you want to remove following line,
you should check in parse and compile time. */
if (mem > num_mem) goto fail;
if (mem_end_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) goto fail;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
STRING_CMP_IC(case_fold_flag, pstart, &s, n);
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI: MOP_IN(OP_BACKREF_MULTI);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE(pstart, swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
case OP_BACKREF_MULTI_IC: MOP_IN(OP_BACKREF_MULTI_IC);
{
int len, is_fail;
UChar *pstart, *pend, *swork;
GET_LENGTH_INC(tlen, p);
for (i = 0; i < tlen; i++) {
GET_MEMNUM_INC(mem, p);
if (mem_end_stk[mem] == INVALID_STACK_INDEX) continue;
if (mem_start_stk[mem] == INVALID_STACK_INDEX) continue;
if (BIT_STATUS_AT(reg->bt_mem_start, mem))
pstart = STACK_AT(mem_start_stk[mem])->u.mem.pstr;
else
pstart = (UChar* )((void* )mem_start_stk[mem]);
pend = (BIT_STATUS_AT(reg->bt_mem_end, mem)
? STACK_AT(mem_end_stk[mem])->u.mem.pstr
: (UChar* )((void* )mem_end_stk[mem]));
n = pend - pstart;
DATA_ENSURE(n);
sprev = s;
swork = s;
STRING_CMP_VALUE_IC(case_fold_flag, pstart, &swork, n, is_fail);
if (is_fail) continue;
s = swork;
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * (tlen - i - 1));
break; /* success */
}
if (i == tlen) goto fail;
MOP_OUT;
continue;
}
break;
#ifdef USE_BACKREF_WITH_LEVEL
case OP_BACKREF_WITH_LEVEL:
{
int len;
OnigOptionType ic;
LengthType level;
GET_OPTION_INC(ic, p);
GET_LENGTH_INC(level, p);
GET_LENGTH_INC(tlen, p);
sprev = s;
if (backref_match_at_nested_level(reg, stk, stk_base, ic
, case_fold_flag, (int )level, (int )tlen, p, &s, end)) {
while (sprev + (len = enclen(encode, sprev)) < s)
sprev += len;
p += (SIZE_MEMNUM * tlen);
}
else
goto fail;
MOP_OUT;
continue;
}
break;
#endif
#if 0 /* no need: IS_DYNAMIC_OPTION() == 0 */
case OP_SET_OPTION_PUSH: MOP_IN(OP_SET_OPTION_PUSH);
GET_OPTION_INC(option, p);
STACK_PUSH_ALT(p, s, sprev);
p += SIZE_OP_SET_OPTION + SIZE_OP_FAIL;
MOP_OUT;
continue;
break;
case OP_SET_OPTION: MOP_IN(OP_SET_OPTION);
GET_OPTION_INC(option, p);
MOP_OUT;
continue;
break;
#endif
case OP_NULL_CHECK_START: MOP_IN(OP_NULL_CHECK_START);
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_PUSH_NULL_CHECK_START(mem, s);
MOP_OUT;
continue;
break;
case OP_NULL_CHECK_END: MOP_IN(OP_NULL_CHECK_END);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK(isnull, mem, s);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
null_check_found:
/* empty loop founded, skip next instruction */
switch (*p++) {
case OP_JUMP:
case OP_PUSH:
p += SIZE_RELADDR;
break;
case OP_REPEAT_INC:
case OP_REPEAT_INC_NG:
case OP_REPEAT_INC_SG:
case OP_REPEAT_INC_NG_SG:
p += SIZE_MEMNUM;
break;
default:
goto unexpected_bytecode_error;
break;
}
}
}
MOP_OUT;
continue;
break;
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
case OP_NULL_CHECK_END_MEMST: MOP_IN(OP_NULL_CHECK_END_MEMST);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
STACK_NULL_CHECK_MEMST(isnull, mem, s, reg);
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
}
MOP_OUT;
continue;
break;
#endif
#ifdef USE_SUBEXP_CALL
case OP_NULL_CHECK_END_MEMST_PUSH:
MOP_IN(OP_NULL_CHECK_END_MEMST_PUSH);
{
int isnull;
GET_MEMNUM_INC(mem, p); /* mem: null check id */
#ifdef USE_MONOMANIAC_CHECK_CAPTURES_IN_ENDLESS_REPEAT
STACK_NULL_CHECK_MEMST_REC(isnull, mem, s, reg);
#else
STACK_NULL_CHECK_REC(isnull, mem, s);
#endif
if (isnull) {
#ifdef ONIG_DEBUG_MATCH
fprintf(stderr, "NULL_CHECK_END_MEMST_PUSH: skip id:%d, s:%d\n",
(int )mem, (int )s);
#endif
if (isnull == -1) goto fail;
goto null_check_found;
}
else {
STACK_PUSH_NULL_CHECK_END(mem);
}
}
MOP_OUT;
continue;
break;
#endif
case OP_JUMP: MOP_IN(OP_JUMP);
GET_RELADDR_INC(addr, p);
p += addr;
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_PUSH: MOP_IN(OP_PUSH);
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
case OP_STATE_CHECK_PUSH: MOP_IN(OP_STATE_CHECK_PUSH);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
GET_RELADDR_INC(addr, p);
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
MOP_OUT;
continue;
break;
case OP_STATE_CHECK_PUSH_OR_JUMP: MOP_IN(OP_STATE_CHECK_PUSH_OR_JUMP);
GET_STATE_CHECK_NUM_INC(mem, p);
GET_RELADDR_INC(addr, p);
STATE_CHECK_VAL(scv, mem);
if (scv) {
p += addr;
}
else {
STACK_PUSH_ALT_WITH_STATE_CHECK(p + addr, s, sprev, mem);
}
MOP_OUT;
continue;
break;
case OP_STATE_CHECK: MOP_IN(OP_STATE_CHECK);
GET_STATE_CHECK_NUM_INC(mem, p);
STATE_CHECK_VAL(scv, mem);
if (scv) goto fail;
STACK_PUSH_STATE_CHECK(s, mem);
MOP_OUT;
continue;
break;
#endif /* USE_COMBINATION_EXPLOSION_CHECK */
case OP_POP: MOP_IN(OP_POP);
STACK_POP_ONE;
MOP_OUT;
continue;
break;
case OP_PUSH_OR_JUMP_EXACT1: MOP_IN(OP_PUSH_OR_JUMP_EXACT1);
GET_RELADDR_INC(addr, p);
if (*p == *s && DATA_ENSURE_CHECK1) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p += (addr + 1);
MOP_OUT;
continue;
break;
case OP_PUSH_IF_PEEK_NEXT: MOP_IN(OP_PUSH_IF_PEEK_NEXT);
GET_RELADDR_INC(addr, p);
if (*p == *s) {
p++;
STACK_PUSH_ALT(p + addr, s, sprev);
MOP_OUT;
continue;
}
p++;
MOP_OUT;
continue;
break;
case OP_REPEAT: MOP_IN(OP_REPEAT);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p + addr, s, sprev);
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_NG: MOP_IN(OP_REPEAT_NG);
{
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
GET_RELADDR_INC(addr, p);
STACK_ENSURE(1);
repeat_stk[mem] = GET_STACK_INDEX(stk);
STACK_PUSH_REPEAT(mem, p);
if (reg->repeat_range[mem].lower == 0) {
STACK_PUSH_ALT(p, s, sprev);
p += addr;
}
}
MOP_OUT;
continue;
break;
case OP_REPEAT_INC: MOP_IN(OP_REPEAT_INC);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc:
stkp->u.repeat.count++;
if (stkp->u.repeat.count >= reg->repeat_range[mem].upper) {
/* end of repeat. Nothing to do. */
}
else if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
STACK_PUSH_ALT(p, s, sprev);
p = STACK_AT(si)->u.repeat.pcode; /* Don't use stkp after PUSH. */
}
else {
p = stkp->u.repeat.pcode;
}
STACK_PUSH_REPEAT_INC(si);
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_SG: MOP_IN(OP_REPEAT_INC_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc;
break;
case OP_REPEAT_INC_NG: MOP_IN(OP_REPEAT_INC_NG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
si = repeat_stk[mem];
stkp = STACK_AT(si);
repeat_inc_ng:
stkp->u.repeat.count++;
if (stkp->u.repeat.count < reg->repeat_range[mem].upper) {
if (stkp->u.repeat.count >= reg->repeat_range[mem].lower) {
UChar* pcode = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
STACK_PUSH_ALT(pcode, s, sprev);
}
else {
p = stkp->u.repeat.pcode;
STACK_PUSH_REPEAT_INC(si);
}
}
else if (stkp->u.repeat.count == reg->repeat_range[mem].upper) {
STACK_PUSH_REPEAT_INC(si);
}
MOP_OUT;
CHECK_INTERRUPT_IN_MATCH_AT;
continue;
break;
case OP_REPEAT_INC_NG_SG: MOP_IN(OP_REPEAT_INC_NG_SG);
GET_MEMNUM_INC(mem, p); /* mem: OP_REPEAT ID */
STACK_GET_REPEAT(mem, stkp);
si = GET_STACK_INDEX(stkp);
goto repeat_inc_ng;
break;
case OP_PUSH_POS: MOP_IN(OP_PUSH_POS);
STACK_PUSH_POS(s, sprev);
MOP_OUT;
continue;
break;
case OP_POP_POS: MOP_IN(OP_POP_POS);
{
STACK_POS_END(stkp);
s = stkp->u.state.pstr;
sprev = stkp->u.state.pstr_prev;
}
MOP_OUT;
continue;
break;
case OP_PUSH_POS_NOT: MOP_IN(OP_PUSH_POS_NOT);
GET_RELADDR_INC(addr, p);
STACK_PUSH_POS_NOT(p + addr, s, sprev);
MOP_OUT;
continue;
break;
case OP_FAIL_POS: MOP_IN(OP_FAIL_POS);
STACK_POP_TIL_POS_NOT;
goto fail;
break;
case OP_PUSH_STOP_BT: MOP_IN(OP_PUSH_STOP_BT);
STACK_PUSH_STOP_BT;
MOP_OUT;
continue;
break;
case OP_POP_STOP_BT: MOP_IN(OP_POP_STOP_BT);
STACK_STOP_BT_END;
MOP_OUT;
continue;
break;
case OP_LOOK_BEHIND: MOP_IN(OP_LOOK_BEHIND);
GET_LENGTH_INC(tlen, p);
s = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(s)) goto fail;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
MOP_OUT;
continue;
break;
case OP_PUSH_LOOK_BEHIND_NOT: MOP_IN(OP_PUSH_LOOK_BEHIND_NOT);
GET_RELADDR_INC(addr, p);
GET_LENGTH_INC(tlen, p);
q = (UChar* )ONIGENC_STEP_BACK(encode, str, s, (int )tlen);
if (IS_NULL(q)) {
/* too short case -> success. ex. /(?<!XXX)a/.match("a")
If you want to change to fail, replace following line. */
p += addr;
/* goto fail; */
}
else {
STACK_PUSH_LOOK_BEHIND_NOT(p + addr, s, sprev);
s = q;
sprev = (UChar* )onigenc_get_prev_char_head(encode, str, s);
}
MOP_OUT;
continue;
break;
case OP_FAIL_LOOK_BEHIND_NOT: MOP_IN(OP_FAIL_LOOK_BEHIND_NOT);
STACK_POP_TIL_LOOK_BEHIND_NOT;
goto fail;
break;
#ifdef USE_SUBEXP_CALL
case OP_CALL: MOP_IN(OP_CALL);
GET_ABSADDR_INC(addr, p);
STACK_PUSH_CALL_FRAME(p);
p = reg->p + addr;
MOP_OUT;
continue;
break;
case OP_RETURN: MOP_IN(OP_RETURN);
STACK_RETURN(p);
STACK_PUSH_RETURN;
MOP_OUT;
continue;
break;
#endif
case OP_FINISH:
goto finish;
break;
fail:
MOP_OUT;
/* fall */
case OP_FAIL: MOP_IN(OP_FAIL);
STACK_POP;
p = stk->u.state.pcode;
s = stk->u.state.pstr;
sprev = stk->u.state.pstr_prev;
#ifdef USE_COMBINATION_EXPLOSION_CHECK
if (stk->u.state.state_check != 0) {
stk->type = STK_STATE_CHECK_MARK;
stk++;
}
#endif
MOP_OUT;
continue;
break;
default:
goto bytecode_error;
} /* end of switch */
sprev = sbegin;
} /* end of while(1) */
finish:
STACK_SAVE;
return best_len;
#ifdef ONIG_DEBUG
stack_error:
STACK_SAVE;
return ONIGERR_STACK_BUG;
#endif
bytecode_error:
STACK_SAVE;
return ONIGERR_UNDEFINED_BYTECODE;
unexpected_bytecode_error:
STACK_SAVE;
return ONIGERR_UNEXPECTED_BYTECODE;
}
static UChar*
slow_search(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *t, *p, *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static int
str_lower_case_match(OnigEncoding enc, int case_fold_flag,
const UChar* t, const UChar* tend,
const UChar* p, const UChar* end)
{
int lowlen;
UChar *q, lowbuf[ONIGENC_MBC_CASE_FOLD_MAXLEN];
while (t < tend) {
lowlen = ONIGENC_MBC_CASE_FOLD(enc, case_fold_flag, &p, end, lowbuf);
q = lowbuf;
while (lowlen > 0) {
if (*t++ != *q++) return 0;
lowlen--;
}
}
return 1;
}
static UChar*
slow_search_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* text_end, UChar* text_range)
{
UChar *s, *end;
end = (UChar* )text_end;
end -= target_end - target - 1;
if (end > text_range)
end = text_range;
s = (UChar* )text;
while (s < end) {
if (str_lower_case_match(enc, case_fold_flag, target, target_end,
s, text_end))
return s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward(OnigEncoding enc, UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *t, *p, *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (*s == *target) {
p = s + 1;
t = target + 1;
while (t < target_end) {
if (*t != *p++)
break;
t++;
}
if (t == target_end)
return s;
}
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
slow_search_backward_ic(OnigEncoding enc, int case_fold_flag,
UChar* target, UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
UChar *s;
s = (UChar* )text_end;
s -= (target_end - target);
if (s > text_start)
s = (UChar* )text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(enc, adjust_text, s);
while (s >= text) {
if (str_lower_case_match(enc, case_fold_flag,
target, target_end, s, text_end))
return s;
s = (UChar* )onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
static UChar*
bm_search_notrev(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end,
const UChar* text_range)
{
const UChar *s, *se, *t, *p, *end;
const UChar *tail;
int skip, tlen1;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "bm_search_notrev: text: %d, text_end: %d, text_range: %d\n",
(int )text, (int )text_end, (int )text_range);
#endif
tail = target_end - 1;
tlen1 = tail - target;
end = text_range;
if (end + tlen1 > text_end)
end = text_end - tlen1;
s = text;
if (IS_NULL(reg->int_map)) {
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
skip = reg->map[*se];
t = s;
do {
s += enclen(reg->enc, s);
} while ((s - t) < skip && s < end);
}
}
else {
while (s < end) {
p = se = s + tlen1;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )s;
p--; t--;
}
skip = reg->int_map[*se];
t = s;
do {
s += enclen(reg->enc, s);
} while ((s - t) < skip && s < end);
}
}
return (UChar* )NULL;
}
static UChar*
bm_search(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* text_end, const UChar* text_range)
{
const UChar *s, *t, *p, *end;
const UChar *tail;
end = text_range + (target_end - target) - 1;
if (end > text_end)
end = text_end;
tail = target_end - 1;
s = text + (target_end - target) - 1;
if (IS_NULL(reg->int_map)) {
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
s += reg->map[*s];
}
}
else { /* see int_map[] */
while (s < end) {
p = s;
t = tail;
while (*p == *t) {
if (t == target) return (UChar* )p;
p--; t--;
}
s += reg->int_map[*s];
}
}
return (UChar* )NULL;
}
#ifdef USE_INT_MAP_BACKWARD
static int
set_bm_backward_skip(UChar* s, UChar* end, OnigEncoding enc ARG_UNUSED,
int** skip)
{
int i, len;
if (IS_NULL(*skip)) {
*skip = (int* )xmalloc(sizeof(int) * ONIG_CHAR_TABLE_SIZE);
if (IS_NULL(*skip)) return ONIGERR_MEMORY;
}
len = end - s;
for (i = 0; i < ONIG_CHAR_TABLE_SIZE; i++)
(*skip)[i] = len;
for (i = len - 1; i > 0; i--)
(*skip)[s[i]] = i;
return 0;
}
static UChar*
bm_search_backward(regex_t* reg, const UChar* target, const UChar* target_end,
const UChar* text, const UChar* adjust_text,
const UChar* text_end, const UChar* text_start)
{
const UChar *s, *t, *p;
s = text_end - (target_end - target);
if (text_start < s)
s = text_start;
else
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s);
while (s >= text) {
p = s;
t = target;
while (t < target_end && *p == *t) {
p++; t++;
}
if (t == target_end)
return (UChar* )s;
s -= reg->int_map_backward[*s];
s = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, adjust_text, s);
}
return (UChar* )NULL;
}
#endif
static UChar*
map_search(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* text_range)
{
const UChar *s = text;
while (s < text_range) {
if (map[*s]) return (UChar* )s;
s += enclen(enc, s);
}
return (UChar* )NULL;
}
static UChar*
map_search_backward(OnigEncoding enc, UChar map[],
const UChar* text, const UChar* adjust_text,
const UChar* text_start)
{
const UChar *s = text_start;
while (s >= text) {
if (map[*s]) return (UChar* )s;
s = onigenc_get_prev_char_head(enc, adjust_text, s);
}
return (UChar* )NULL;
}
extern int
onig_match(regex_t* reg, const UChar* str, const UChar* end, const UChar* at, OnigRegion* region,
OnigOptionType option)
{
int r;
UChar *prev;
OnigMatchArg msa;
MATCH_ARG_INIT(msa, reg, option, region, at);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
{
int offset = at - str;
STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check);
}
#endif
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
}
else
r = 0;
if (r == 0) {
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto end;
}
}
prev = (UChar* )onigenc_get_prev_char_head(reg->enc, str, at);
r = match_at(reg, str, end,
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
end,
#endif
at, prev, &msa);
}
end:
MATCH_ARG_FREE(msa);
return r;
}
static int
forward_search_range(regex_t* reg, const UChar* str, const UChar* end, UChar* s,
UChar* range, UChar** low, UChar** high, UChar** low_prev)
{
UChar *p, *pprev = (UChar* )NULL;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "forward_search_range: str: %d, end: %d, s: %d, range: %d\n",
(int )str, (int )end, (int )s, (int )range);
#endif
p = s;
if (reg->dmin > 0) {
if (ONIGENC_IS_SINGLEBYTE(reg->enc)) {
p += reg->dmin;
}
else {
UChar *q = p + reg->dmin;
while (p < q) p += enclen(reg->enc, p);
}
}
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
p = slow_search(reg->enc, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM:
p = bm_search(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
p = bm_search_notrev(reg, reg->exact, reg->exact_end, p, end, range);
break;
case ONIG_OPTIMIZE_MAP:
p = map_search(reg->enc, reg->map, p, range);
break;
}
if (p && p < range) {
if (p - reg->dmin < s) {
retry_gate:
pprev = p;
p += enclen(reg->enc, p);
goto retry;
}
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = (UChar* )onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
if (prev && ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end))
goto retry_gate;
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
)
goto retry_gate;
break;
}
}
if (reg->dmax == 0) {
*low = p;
if (low_prev) {
if (*low > s)
*low_prev = onigenc_get_prev_char_head(reg->enc, s, p);
else
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), p);
}
}
else {
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
if (*low > s) {
*low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
*low, (const UChar** )low_prev);
if (low_prev && IS_NULL(*low_prev))
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : s), *low);
}
else {
if (low_prev)
*low_prev = onigenc_get_prev_char_head(reg->enc,
(pprev ? pprev : str), *low);
}
}
}
/* no needs to adjust *high, *high is used as range check only */
*high = p - reg->dmin;
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"forward_search_range success: low: %d, high: %d, dmin: %d, dmax: %d\n",
(int )(*low - str), (int )(*high - str), reg->dmin, reg->dmax);
#endif
return 1; /* success */
}
return 0; /* fail */
}
#define BM_BACKWARD_SEARCH_LENGTH_THRESHOLD 100
static int
backward_search_range(regex_t* reg, const UChar* str, const UChar* end,
UChar* s, const UChar* range, UChar* adjrange,
UChar** low, UChar** high)
{
UChar *p;
range += reg->dmin;
p = s;
retry:
switch (reg->optimize) {
case ONIG_OPTIMIZE_EXACT:
exact_method:
p = slow_search_backward(reg->enc, reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case ONIG_OPTIMIZE_EXACT_IC:
p = slow_search_backward_ic(reg->enc, reg->case_fold_flag,
reg->exact, reg->exact_end,
range, adjrange, end, p);
break;
case ONIG_OPTIMIZE_EXACT_BM:
case ONIG_OPTIMIZE_EXACT_BM_NOT_REV:
#ifdef USE_INT_MAP_BACKWARD
if (IS_NULL(reg->int_map_backward)) {
int r;
if (s - range < BM_BACKWARD_SEARCH_LENGTH_THRESHOLD)
goto exact_method;
r = set_bm_backward_skip(reg->exact, reg->exact_end, reg->enc,
&(reg->int_map_backward));
if (r) return r;
}
p = bm_search_backward(reg, reg->exact, reg->exact_end, range, adjrange,
end, p);
#else
goto exact_method;
#endif
break;
case ONIG_OPTIMIZE_MAP:
p = map_search_backward(reg->enc, reg->map, range, adjrange, p);
break;
}
if (p) {
if (reg->sub_anchor) {
UChar* prev;
switch (reg->sub_anchor) {
case ANCHOR_BEGIN_LINE:
if (!ON_STR_BEGIN(p)) {
prev = onigenc_get_prev_char_head(reg->enc, str, p);
if (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
}
break;
case ANCHOR_END_LINE:
if (ON_STR_END(p)) {
#ifndef USE_NEWLINE_AT_END_OF_STRING_HAS_EMPTY_LINE
prev = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(prev)) goto fail;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end)) {
p = prev;
goto retry;
}
#endif
}
else if (! ONIGENC_IS_MBC_NEWLINE(reg->enc, p, end)
#ifdef USE_CRNL_AS_LINE_TERMINATOR
&& ! ONIGENC_IS_MBC_CRNL(reg->enc, p, end)
#endif
) {
p = onigenc_get_prev_char_head(reg->enc, adjrange, p);
if (IS_NULL(p)) goto fail;
goto retry;
}
break;
}
}
/* no needs to adjust *high, *high is used as range check only */
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
*low = p - reg->dmax;
*high = p - reg->dmin;
*high = onigenc_get_right_adjust_char_head(reg->enc, adjrange, *high);
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: low: %d, high: %d\n",
(int )(*low - str), (int )(*high - str));
#endif
return 1; /* success */
}
fail:
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "backward_search_range: fail.\n");
#endif
return 0; /* fail */
}
extern int
onig_search(regex_t* reg, const UChar* str, const UChar* end,
const UChar* start, const UChar* range, OnigRegion* region, OnigOptionType option)
{
int r;
UChar *s, *prev;
OnigMatchArg msa;
const UChar *orig_start = start;
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
const UChar *orig_range = range;
#endif
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr,
"onig_search (entry point): str: %d, end: %d, start: %d, range: %d\n",
(int )str, (int )(end - str), (int )(start - str), (int )(range - str));
#endif
if (region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
r = onig_region_resize_clear(region, reg->num_mem + 1);
if (r) goto finish_no_msa;
}
if (start > end || start < str) goto mismatch_no_msa;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end)) {
r = ONIGERR_INVALID_WIDE_CHAR_VALUE;
goto finish_no_msa;
}
}
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(upper_range) \
r = match_at(reg, str, end, (upper_range), s, prev, &msa); \
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#else
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
if (! IS_FIND_LONGEST(reg->options)) {\
goto match;\
}\
}\
else goto finish; /* error */ \
}
#else
#define MATCH_AND_RETURN_CHECK(none) \
r = match_at(reg, str, end, s, prev, &msa);\
if (r != ONIG_MISMATCH) {\
if (r >= 0) {\
goto match;\
}\
else goto finish; /* error */ \
}
#endif /* USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE */
#endif /* USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE */
/* anchor optimize: resume search range */
if (reg->anchor != 0 && str < end) {
UChar *min_semi_end, *max_semi_end;
if (reg->anchor & ANCHOR_BEGIN_POSITION) {
/* search start-position only */
begin_position:
if (range > start)
range = start + 1;
else
range = start;
}
else if (reg->anchor & ANCHOR_BEGIN_BUF) {
/* search str-position only */
if (range > start) {
if (start != str) goto mismatch_no_msa;
range = str + 1;
}
else {
if (range <= str) {
start = str;
range = str;
}
else
goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_END_BUF) {
min_semi_end = max_semi_end = (UChar* )end;
end_buf:
if ((OnigLen )(max_semi_end - str) < reg->anchor_dmin)
goto mismatch_no_msa;
if (range > start) {
if ((OnigLen )(min_semi_end - start) > reg->anchor_dmax) {
start = min_semi_end - reg->anchor_dmax;
if (start < end)
start = onigenc_get_right_adjust_char_head(reg->enc, str, start);
}
if ((OnigLen )(max_semi_end - (range - 1)) < reg->anchor_dmin) {
range = max_semi_end - reg->anchor_dmin + 1;
}
if (start > range) goto mismatch_no_msa;
/* If start == range, match with empty at end.
Backward search is used. */
}
else {
if ((OnigLen )(min_semi_end - range) > reg->anchor_dmax) {
range = min_semi_end - reg->anchor_dmax;
}
if ((OnigLen )(max_semi_end - start) < reg->anchor_dmin) {
start = max_semi_end - reg->anchor_dmin;
start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, start);
}
if (range > start) goto mismatch_no_msa;
}
}
else if (reg->anchor & ANCHOR_SEMI_END_BUF) {
UChar* pre_end = ONIGENC_STEP_BACK(reg->enc, str, end, 1);
max_semi_end = (UChar* )end;
if (ONIGENC_IS_MBC_NEWLINE(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
#ifdef USE_CRNL_AS_LINE_TERMINATOR
pre_end = ONIGENC_STEP_BACK(reg->enc, str, pre_end, 1);
if (IS_NOT_NULL(pre_end) &&
ONIGENC_IS_MBC_CRNL(reg->enc, pre_end, end)) {
min_semi_end = pre_end;
}
#endif
if (min_semi_end > str && start <= min_semi_end) {
goto end_buf;
}
}
else {
min_semi_end = (UChar* )end;
goto end_buf;
}
}
else if ((reg->anchor & ANCHOR_ANYCHAR_STAR_ML)) {
goto begin_position;
}
}
else if (str == end) { /* empty string */
static const UChar* address_for_empty_string = (UChar* )"";
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search: empty string.\n");
#endif
if (reg->threshold_len == 0) {
start = end = str = address_for_empty_string;
s = (UChar* )start;
prev = (UChar* )NULL;
MATCH_ARG_INIT(msa, reg, option, region, start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
msa.state_check_buff = (void* )0;
msa.state_check_buff_size = 0; /* NO NEED, for valgrind */
#endif
MATCH_AND_RETURN_CHECK(end);
goto mismatch;
}
goto mismatch_no_msa;
}
#ifdef ONIG_DEBUG_SEARCH
fprintf(stderr, "onig_search(apply anchor): end: %d, start: %d, range: %d\n",
(int )(end - str), (int )(start - str), (int )(range - str));
#endif
MATCH_ARG_INIT(msa, reg, option, region, orig_start);
#ifdef USE_COMBINATION_EXPLOSION_CHECK
{
int offset = (MIN(start, range) - str);
STATE_CHECK_BUFF_INIT(msa, end - str, offset, reg->num_comb_exp_check);
}
#endif
s = (UChar* )start;
if (range > start) { /* forward search */
if (s > str)
prev = onigenc_get_prev_char_head(reg->enc, str, s);
else
prev = (UChar* )NULL;
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *sch_range, *low, *high, *low_prev;
sch_range = (UChar* )range;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_range = (UChar* )end;
else {
sch_range += reg->dmax;
if (sch_range > end) sch_range = (UChar* )end;
}
}
if ((end - start) < reg->threshold_len)
goto mismatch;
if (reg->dmax != ONIG_INFINITE_DISTANCE) {
do {
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, &low_prev)) goto mismatch;
if (s < low) {
s = low;
prev = low_prev;
}
while (s <= high) {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
}
} while (s < range);
goto mismatch;
}
else { /* check only. */
if (! forward_search_range(reg, str, end, s, sch_range,
&low, &high, (UChar** )NULL)) goto mismatch;
if ((reg->anchor & ANCHOR_ANYCHAR_STAR) != 0) {
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
if ((reg->anchor & (ANCHOR_LOOK_BEHIND | ANCHOR_PREC_READ_NOT)) == 0) {
while (!ONIGENC_IS_MBC_NEWLINE(reg->enc, prev, end) && s < range) {
prev = s;
s += enclen(reg->enc, s);
}
}
} while (s < range);
goto mismatch;
}
}
}
do {
MATCH_AND_RETURN_CHECK(orig_range);
prev = s;
s += enclen(reg->enc, s);
} while (s < range);
if (s == range) { /* because empty match with /$/. */
MATCH_AND_RETURN_CHECK(orig_range);
}
}
else { /* backward search */
#ifdef USE_MATCH_RANGE_MUST_BE_INSIDE_OF_SPECIFIED_RANGE
if (orig_start < end)
orig_start += enclen(reg->enc, orig_start); /* is upper range */
#endif
if (reg->optimize != ONIG_OPTIMIZE_NONE) {
UChar *low, *high, *adjrange, *sch_start;
if (range < end)
adjrange = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc, str, range);
else
adjrange = (UChar* )end;
if (reg->dmax != ONIG_INFINITE_DISTANCE &&
(end - range) >= reg->threshold_len) {
do {
sch_start = s + reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0)
goto mismatch;
if (s > high)
s = high;
while (s >= low) {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
}
} while (s >= range);
goto mismatch;
}
else { /* check only. */
if ((end - range) < reg->threshold_len) goto mismatch;
sch_start = s;
if (reg->dmax != 0) {
if (reg->dmax == ONIG_INFINITE_DISTANCE)
sch_start = (UChar* )end;
else {
sch_start += reg->dmax;
if (sch_start > end) sch_start = (UChar* )end;
else
sch_start = ONIGENC_LEFT_ADJUST_CHAR_HEAD(reg->enc,
start, sch_start);
}
}
if (backward_search_range(reg, str, end, sch_start, range, adjrange,
&low, &high) <= 0) goto mismatch;
}
}
do {
prev = onigenc_get_prev_char_head(reg->enc, str, s);
MATCH_AND_RETURN_CHECK(orig_start);
s = prev;
} while (s >= range);
}
mismatch:
#ifdef USE_FIND_LONGEST_SEARCH_ALL_OF_RANGE
if (IS_FIND_LONGEST(reg->options)) {
if (msa.best_len >= 0) {
s = msa.best_s;
goto match;
}
}
#endif
r = ONIG_MISMATCH;
finish:
MATCH_ARG_FREE(msa);
/* If result is mismatch and no FIND_NOT_EMPTY option,
then the region is not set in match_at(). */
if (IS_FIND_NOT_EMPTY(reg->options) && region
#ifdef USE_POSIX_API_REGION_OPTION
&& !IS_POSIX_REGION(option)
#endif
) {
onig_region_clear(region);
}
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
mismatch_no_msa:
r = ONIG_MISMATCH;
finish_no_msa:
#ifdef ONIG_DEBUG
if (r != ONIG_MISMATCH)
fprintf(stderr, "onig_search: error %d\n", r);
#endif
return r;
match:
MATCH_ARG_FREE(msa);
return s - str;
}
extern int
onig_scan(regex_t* reg, const UChar* str, const UChar* end,
OnigRegion* region, OnigOptionType option,
int (*scan_callback)(int, int, OnigRegion*, void*),
void* callback_arg)
{
int r;
int n;
int rs;
const UChar* start;
if (ONIG_IS_OPTION_ON(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING)) {
if (! ONIGENC_IS_VALID_MBC_STRING(reg->enc, str, end))
return ONIGERR_INVALID_WIDE_CHAR_VALUE;
ONIG_OPTION_OFF(option, ONIG_OPTION_CHECK_VALIDITY_OF_STRING);
}
n = 0;
start = str;
while (1) {
r = onig_search(reg, str, end, start, end, region, option);
if (r >= 0) {
rs = scan_callback(n, r, region, callback_arg);
n++;
if (rs != 0)
return rs;
if (region->end[0] == start - str)
start++;
else
start = str + region->end[0];
if (start > end)
break;
}
else if (r == ONIG_MISMATCH) {
break;
}
else { /* error */
return r;
}
}
return n;
}
extern OnigEncoding
onig_get_encoding(regex_t* reg)
{
return reg->enc;
}
extern OnigOptionType
onig_get_options(regex_t* reg)
{
return reg->options;
}
extern OnigCaseFoldType
onig_get_case_fold_flag(regex_t* reg)
{
return reg->case_fold_flag;
}
extern OnigSyntaxType*
onig_get_syntax(regex_t* reg)
{
return reg->syntax;
}
extern int
onig_number_of_captures(regex_t* reg)
{
return reg->num_mem;
}
extern int
onig_number_of_capture_histories(regex_t* reg)
{
#ifdef USE_CAPTURE_HISTORY
int i, n;
n = 0;
for (i = 0; i <= ONIG_MAX_CAPTURE_HISTORY_GROUP; i++) {
if (BIT_STATUS_AT(reg->capture_history, i) != 0)
n++;
}
return n;
#else
return 0;
#endif
}
extern void
onig_copy_encoding(OnigEncoding to, OnigEncoding from)
{
*to = *from;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3376_0 |
crossvul-cpp_data_good_800_0 | /*
* MPEG-4 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* 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 UNCHECKED_BITSTREAM_READER 1
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "error_resilience.h"
#include "hwaccel.h"
#include "idctdsp.h"
#include "internal.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "mpegvideodata.h"
#include "mpeg4video.h"
#include "h263.h"
#include "profiles.h"
#include "thread.h"
#include "xvididct.h"
#include "unary.h"
/* The defines below define the number of bits that are read at once for
* reading vlc values. Changing these may improve speed and data cache needs
* be aware though that decreasing them may need the number of stages that is
* passed to get_vlc* to be increased. */
#define SPRITE_TRAJ_VLC_BITS 6
#define DC_VLC_BITS 9
#define MB_TYPE_B_VLC_BITS 4
#define STUDIO_INTRA_BITS 9
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
static VLC dc_lum, dc_chrom;
static VLC sprite_trajectory;
static VLC mb_type_b_vlc;
static const int mb_type_b_map[4] = {
MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
MB_TYPE_L0L1 | MB_TYPE_16x16,
MB_TYPE_L1 | MB_TYPE_16x16,
MB_TYPE_L0 | MB_TYPE_16x16,
};
/**
* Predict the ac.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir the ac prediction direction
*/
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
{
int i;
int16_t *ac_val, *ac_val1;
int8_t *const qscale_table = s->current_picture.qscale_table;
/* find prediction */
ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (s->ac_pred) {
if (dir == 0) {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
}
} else {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= 16 * s->block_wrap[n];
if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
}
}
}
/* left copy */
for (i = 1; i < 8; i++)
ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
/* top copy */
for (i = 1; i < 8; i++)
ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
}
/**
* check if the next stuff is a resync marker or the end.
* @return 0 if not
*/
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int bits_count = get_bits_count(&s->gb);
int v = show_bits(&s->gb, 16);
if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
return 0;
while (v <= 0xFF) {
if (s->pict_type == AV_PICTURE_TYPE_B ||
(v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
break;
skip_bits(&s->gb, 8 + s->pict_type);
bits_count += 8 + s->pict_type;
v = show_bits(&s->gb, 16);
}
if (bits_count + 8 >= s->gb.size_in_bits) {
v >>= 8;
v |= 0x7F >> (7 - (bits_count & 7));
if (v == 0x7F)
return s->mb_num;
} else {
if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
int len, mb_num;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
GetBitContext gb = s->gb;
skip_bits(&s->gb, 1);
align_get_bits(&s->gb);
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
mb_num = get_bits(&s->gb, mb_num_bits);
if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
mb_num= -1;
s->gb = gb;
if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
return mb_num;
}
}
return 0;
}
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int a = 2 << s->sprite_warping_accuracy;
int rho = 3 - s->sprite_warping_accuracy;
int r = 16 / a;
int alpha = 1;
int beta = 0;
int w = s->width;
int h = s->height;
int min_ab, i, w2, h2, w3, h3;
int sprite_ref[4][2];
int virtual_ref[2][2];
int64_t sprite_offset[2][2];
int64_t sprite_delta[2][2];
// only true for rectangle shapes
const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 },
{ 0, s->height }, { s->width, s->height } };
int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (w <= 0 || h <= 0)
return AVERROR_INVALIDDATA;
/* the decoder was not properly initialized and we cannot continue */
if (sprite_trajectory.table == NULL)
return AVERROR_INVALIDDATA;
for (i = 0; i < ctx->num_sprite_warping_points; i++) {
int length;
int x = 0, y = 0;
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
x = get_xbits(gb, length);
if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
check_marker(s->avctx, gb, "before sprite_trajectory");
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
y = get_xbits(gb, length);
check_marker(s->avctx, gb, "after sprite_trajectory");
ctx->sprite_traj[i][0] = d[i][0] = x;
ctx->sprite_traj[i][1] = d[i][1] = y;
}
for (; i < 4; i++)
ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
while ((1 << alpha) < w)
alpha++;
while ((1 << beta) < h)
beta++; /* typo in the MPEG-4 std for the definition of w' and h' */
w2 = 1 << alpha;
h2 = 1 << beta;
// Note, the 4th point isn't used for GMC
if (ctx->divx_version == 500 && ctx->divx_build == 413) {
sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
} else {
sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
}
/* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
* sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
/* This is mostly identical to the MPEG-4 std (and is totally unreadable
* because of that...). Perhaps it should be reordered to be more readable.
* The idea behind this virtual_ref mess is to be able to use shifts later
* per pixel instead of divides so the distance between points is converted
* from w&h based to w2&h2 based which are of the 2^x form. */
virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
virtual_ref[0][1] = 16 * vop_ref[0][1] +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
virtual_ref[1][0] = 16 * vop_ref[0][0] +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
switch (ctx->num_sprite_warping_points) {
case 0:
sprite_offset[0][0] =
sprite_offset[0][1] =
sprite_offset[1][0] =
sprite_offset[1][1] = 0;
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 1: // GMC only
sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
a * (vop_ref[0][0] / 2);
sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
a * (vop_ref[0][1] / 2);
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 2:
sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
ctx->sprite_shift[0] = alpha + rho;
ctx->sprite_shift[1] = alpha + rho + 2;
break;
case 3:
min_ab = FFMIN(alpha, beta);
w3 = w2 >> min_ab;
h3 = h2 >> min_ab;
sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
ctx->sprite_shift[0] = alpha + beta + rho - min_ab;
ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2;
break;
}
/* try to simplify the situation */
if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
sprite_delta[0][1] == 0 &&
sprite_delta[1][0] == 0 &&
sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
sprite_offset[0][0] >>= ctx->sprite_shift[0];
sprite_offset[0][1] >>= ctx->sprite_shift[0];
sprite_offset[1][0] >>= ctx->sprite_shift[1];
sprite_offset[1][1] >>= ctx->sprite_shift[1];
sprite_delta[0][0] = a;
sprite_delta[0][1] = 0;
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] = 0;
ctx->sprite_shift[1] = 0;
s->real_sprite_warping_points = 1;
} else {
int shift_y = 16 - ctx->sprite_shift[0];
int shift_c = 16 - ctx->sprite_shift[1];
for (i = 0; i < 2; i++) {
if (shift_c < 0 || shift_y < 0 ||
FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c ||
FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y
) {
avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
goto overflow;
}
}
for (i = 0; i < 2; i++) {
sprite_offset[0][i] *= 1 << shift_y;
sprite_offset[1][i] *= 1 << shift_c;
sprite_delta[0][i] *= 1 << shift_y;
sprite_delta[1][i] *= 1 << shift_y;
ctx->sprite_shift[i] = 16;
}
for (i = 0; i < 2; i++) {
int64_t sd[2] = {
sprite_delta[i][0] - a * (1LL<<16),
sprite_delta[i][1] - a * (1LL<<16)
};
if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sd[0]) >= INT_MAX ||
llabs(sd[1]) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
) {
avpriv_request_sample(s->avctx, "Overflow on sprite points");
goto overflow;
}
}
s->real_sprite_warping_points = ctx->num_sprite_warping_points;
}
for (i = 0; i < 4; i++) {
s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
}
return 0;
overflow:
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
return AVERROR_PATCHWELCOME;
}
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
MpegEncContext *s = &ctx->m;
int len = FFMIN(ctx->time_increment_bits + 3, 15);
get_bits(gb, len);
if (get_bits1(gb))
get_bits(gb, len);
check_marker(s->avctx, gb, "after new_pred");
return 0;
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
int header_extension = 0, mb_num, len;
/* is there enough space left for a video packet + header */
if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
return AVERROR_INVALIDDATA;
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
return AVERROR_INVALIDDATA;
}
if (ctx->shape != RECT_SHAPE) {
header_extension = get_bits1(&s->gb);
// FIXME more stuff here
}
mb_num = get_bits(&s->gb, mb_num_bits);
if (mb_num >= s->mb_num || !mb_num) {
av_log(s->avctx, AV_LOG_ERROR,
"illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
return AVERROR_INVALIDDATA;
}
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE) {
int qscale = get_bits(&s->gb, s->quant_precision);
if (qscale)
s->chroma_qscale = s->qscale = qscale;
}
if (ctx->shape == RECT_SHAPE)
header_extension = get_bits1(&s->gb);
if (header_extension) {
int time_incr = 0;
while (get_bits1(&s->gb) != 0)
time_incr++;
check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */
check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
skip_bits(&s->gb, 2); /* vop coding type */
// FIXME not rect stuff here
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits(&s->gb, 3); /* intra dc vlc threshold */
// FIXME don't just ignore everything
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
return AVERROR_INVALIDDATA;
av_log(s->avctx, AV_LOG_ERROR, "untested\n");
}
// FIXME reduced res stuff here
if (s->pict_type != AV_PICTURE_TYPE_I) {
int f_code = get_bits(&s->gb, 3); /* fcode_for */
if (f_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (f_code=0)\n");
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
int b_code = get_bits(&s->gb, 3);
if (b_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (b_code=0)\n");
}
}
}
if (ctx->new_pred)
decode_new_pred(ctx, &s->gb);
return 0;
}
static void reset_studio_dc_predictors(MpegEncContext *s)
{
/* Reset DC Predictors */
s->last_dc[0] =
s->last_dc[1] =
s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
GetBitContext *gb = &s->gb;
unsigned vlc_len;
uint16_t mb_num;
if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
mb_num = get_bits(gb, vlc_len);
if (mb_num >= s->mb_num)
return AVERROR_INVALIDDATA;
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE)
s->qscale = mpeg_get_qscale(s);
if (get_bits1(gb)) { /* slice_extension_flag */
skip_bits1(gb); /* intra_slice */
skip_bits1(gb); /* slice_VOP_id_enable */
skip_bits(gb, 6); /* slice_VOP_id */
while (get_bits1(gb)) /* extra_bit_slice */
skip_bits(gb, 8); /* extra_information_slice */
}
reset_studio_dc_predictors(s);
}
else {
return AVERROR_INVALIDDATA;
}
return 0;
}
/**
* Get the average motion vector for a GMC MB.
* @param n either 0 for the x component or 1 for y
* @return the average MV for a GMC MB
*/
static inline int get_amv(Mpeg4DecContext *ctx, int n)
{
MpegEncContext *s = &ctx->m;
int x, y, mb_v, sum, dx, dy, shift;
int len = 1 << (s->f_code + 4);
const int a = s->sprite_warping_accuracy;
if (s->workaround_bugs & FF_BUG_AMV)
len >>= s->quarter_sample;
if (s->real_sprite_warping_points == 1) {
if (ctx->divx_version == 500 && ctx->divx_build == 413 && a >= s->quarter_sample)
sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
else
sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
} else {
dx = s->sprite_delta[n][0];
dy = s->sprite_delta[n][1];
shift = ctx->sprite_shift[0];
if (n)
dy -= 1 << (shift + a + 1);
else
dx -= 1 << (shift + a + 1);
mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
sum = 0;
for (y = 0; y < 16; y++) {
int v;
v = mb_v + dy * y;
// FIXME optimize
for (x = 0; x < 16; x++) {
sum += v >> shift;
v += dx;
}
}
sum = RSHIFT(sum, a + 8 - s->quarter_sample);
}
if (sum < -len)
sum = -len;
else if (sum >= len)
sum = len - 1;
return sum;
}
/**
* Decode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir_ptr the prediction direction will be stored here
* @return the quantized dc
*/
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
{
int level, code;
if (n < 4)
code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
else
code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
if (code < 0 || code > 9 /* && s->nbit < 9 */) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
return AVERROR_INVALIDDATA;
}
if (code == 0) {
level = 0;
} else {
if (IS_3IV1) {
if (code == 1)
level = 2 * get_bits1(&s->gb) - 1;
else {
if (get_bits1(&s->gb))
level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
else
level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
}
} else {
level = get_xbits(&s->gb, code);
}
if (code > 8) {
if (get_bits1(&s->gb) == 0) { /* marker */
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
return AVERROR_INVALIDDATA;
}
}
}
}
return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
}
/**
* Decode first partition.
* @return number of MBs decoded or <0 if an error occurred
*/
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
/* decode first partition */
s->first_slice_line = 1;
for (; s->mb_y < s->mb_height; s->mb_y++) {
ff_init_block_index(s);
for (; s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
int cbpc;
int dir = 0;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int i;
do {
if (show_bits_long(&s->gb, 19) == DC_MARKER)
return mb_num - 1;
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
s->cbp_table[xy] = cbpc & 3;
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mb_intra = 1;
if (cbpc & 4)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->mbintra_table[xy] = 1;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->pred_dir_table[xy] = dir;
} else { /* P/S_TYPE */
int mx, my, pred_x, pred_y, bits;
int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
const int stride = s->b8_stride * 2;
try_again:
bits = show_bits(&s->gb, 17);
if (bits == MOTION_MARKER)
return mb_num - 1;
skip_bits1(&s->gb);
if (bits & 0x10000) {
/* skip mb */
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
mx = my = 0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
continue;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (cbpc == 20)
goto try_again;
s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra) {
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mbintra_table[xy] = 1;
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = 0;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = 0;
} else {
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE &&
(cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
if ((cbpc & 16) == 0) {
/* 16x16 motion prediction */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->mcsel) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_L0;
} else {
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
} else {
int i;
s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
MB_TYPE_L0;
for (i = 0; i < 4; i++) {
int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
mot_val[0] = mx;
mot_val[1] = my;
}
}
}
}
}
s->mb_x = 0;
}
return mb_num;
}
/**
* decode second partition.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
{
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
s->mb_x = s->resync_mb_x;
s->first_slice_line = 1;
for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
ff_init_block_index(s);
for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
} else { /* P || S_TYPE */
if (IS_INTRA(s->current_picture.mb_type[xy])) {
int i;
int dir = 0;
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
s->pred_dir_table[xy] = dir;
} else if (IS_SKIP(s->current_picture.mb_type[xy])) {
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] = 0;
} else {
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
}
}
}
if (mb_num >= mb_count)
return 0;
s->mb_x = 0;
}
return 0;
}
/**
* Decode the first and second partition.
* @return <0 if error (and sets error type in the error_status_table)
*/
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num;
int ret;
const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END;
mb_num = mpeg4_decode_partition_a(ctx);
if (mb_num <= 0) {
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return mb_num ? mb_num : AVERROR_INVALIDDATA;
}
if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return AVERROR_INVALIDDATA;
}
s->mb_num_left = mb_num;
if (s->pict_type == AV_PICTURE_TYPE_I) {
while (show_bits(&s->gb, 9) == 1)
skip_bits(&s->gb, 9);
if (get_bits_long(&s->gb, 19) != DC_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first I partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} else {
while (show_bits(&s->gb, 10) == 1)
skip_bits(&s->gb, 10);
if (get_bits(&s->gb, 17) != MOTION_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first P partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
}
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, part_a_end);
ret = mpeg4_decode_partition_b(s, mb_num);
if (ret < 0) {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, ER_DC_ERROR);
return ret;
} else {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, ER_DC_END);
}
return 0;
}
/**
* Decode a block.
* @return <0 if an error occurred
*/
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
int n, int coded, int intra, int rvlc)
{
MpegEncContext *s = &ctx->m;
int level, i, last, run, qmul, qadd;
int av_uninit(dc_pred_dir);
RLTable *rl;
RL_VLC_ELEM *rl_vlc;
const uint8_t *scan_table;
// Note intra & rvlc should be optimized away if this is inlined
if (intra) {
if (ctx->use_intra_dc_vlc) {
/* DC coef */
if (s->partitioned_frame) {
level = s->dc_val[0][s->block_index[n]];
if (n < 4)
level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
else
level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
} else {
level = mpeg4_decode_dc(s, n, &dc_pred_dir);
if (level < 0)
return level;
}
block[0] = level;
i = 0;
} else {
i = -1;
ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
}
if (!coded)
goto not_coded;
if (rvlc) {
rl = &ff_rvlc_rl_intra;
rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
} else {
rl = &ff_mpeg4_rl_intra;
rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
}
if (s->ac_pred) {
if (dc_pred_dir == 0)
scan_table = s->intra_v_scantable.permutated; /* left */
else
scan_table = s->intra_h_scantable.permutated; /* top */
} else {
scan_table = s->intra_scantable.permutated;
}
qmul = 1;
qadd = 0;
} else {
i = -1;
if (!coded) {
s->block_last_index[n] = i;
return 0;
}
if (rvlc)
rl = &ff_rvlc_rl_inter;
else
rl = &ff_h263_rl_inter;
scan_table = s->intra_scantable.permutated;
if (s->mpeg_quant) {
qmul = 1;
qadd = 0;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[0];
} else {
qmul = s->qscale << 1;
qadd = (s->qscale - 1) | 1;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
}
}
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
if (level == 0) {
/* escape */
if (rvlc) {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_UBITS(re, &s->gb, 11);
SKIP_CACHE(re, &s->gb, 11);
if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 5);
level = level * qmul + qadd;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
i += run + 1;
if (last)
i += 192;
} else {
int cache;
cache = GET_CACHE(re, &s->gb);
if (IS_3IV1)
cache ^= 0xC0000000;
if (cache & 0x80000000) {
if (cache & 0x40000000) {
/* third escape */
SKIP_CACHE(re, &s->gb, 2);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (IS_3IV1) {
level = SHOW_SBITS(re, &s->gb, 12);
LAST_SKIP_BITS(re, &s->gb, 12);
} else {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_SBITS(re, &s->gb, 12);
SKIP_CACHE(re, &s->gb, 12);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
}
#if 0
if (s->error_recognition >= FF_ER_COMPLIANT) {
const int abs_level= FFABS(level);
if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
const int run1= run - rl->max_run[last][abs_level] - 1;
if (abs_level <= rl->max_level[last][run]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (s->error_recognition > FF_ER_COMPLIANT) {
if (abs_level <= rl->max_level[last][run]*2) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
return AVERROR_INVALIDDATA;
}
}
}
}
#endif
if (level > 0)
level = level * qmul + qadd;
else
level = level * qmul - qadd;
if ((unsigned)(level + 2048) > 4095) {
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
if (level > 2560 || level < -2560) {
av_log(s->avctx, AV_LOG_ERROR,
"|level| overflow in 3. esc, qp=%d\n",
s->qscale);
return AVERROR_INVALIDDATA;
}
}
level = level < 0 ? -2048 : 2047;
}
i += run + 1;
if (last)
i += 192;
} else {
/* second escape */
SKIP_BITS(re, &s->gb, 2);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
} else {
/* first escape */
SKIP_BITS(re, &s->gb, 1);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run;
level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
}
} else {
i += run;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
if (i > 62) {
i -= 192;
if (i & (~63)) {
av_log(s->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
block[scan_table[i]] = level;
break;
}
block[scan_table[i]] = level;
}
CLOSE_READER(re, &s->gb);
}
not_coded:
if (intra) {
if (!ctx->use_intra_dc_vlc) {
block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
i -= i >> 31; // if (i == -1) i = 0;
}
ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
if (s->ac_pred)
i = 63; // FIXME not optimal
}
s->block_last_index[n] = i;
return 0;
}
/**
* decode partition C of one MB.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbp, mb_type;
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
mb_type = s->current_picture.mb_type[xy];
cbp = s->cbp_table[xy];
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (s->current_picture.qscale_table[xy] != s->qscale)
ff_set_qscale(s, s->current_picture.qscale_table[xy]);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
int i;
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
}
s->mb_intra = IS_INTRA(mb_type);
if (IS_SKIP(mb_type)) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S
&& ctx->vol_sprite_usage == GMC_SPRITE) {
s->mcsel = 1;
s->mb_skipped = 0;
} else {
s->mcsel = 0;
s->mb_skipped = 1;
}
} else if (s->mb_intra) {
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
} else if (!s->mb_intra) {
// s->mcsel = 0; // FIXME do we need to init that?
s->mv_dir = MV_DIR_FORWARD;
if (IS_8X8(mb_type)) {
s->mv_type = MV_TYPE_8X8;
} else {
s->mv_type = MV_TYPE_16X16;
}
}
} else { /* I-Frame */
s->mb_intra = 1;
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
}
if (!IS_SKIP(mb_type)) {
int i;
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"texture corrupted at %d %d %d\n",
s->mb_x, s->mb_y, s->mb_intra);
return AVERROR_INVALIDDATA;
}
cbp += cbp;
}
}
/* per-MB end of slice check */
if (--s->mb_num_left <= 0) {
if (mpeg4_is_resync(ctx))
return SLICE_END;
else
return SLICE_NOEND;
} else {
if (mpeg4_is_resync(ctx)) {
const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
if (s->cbp_table[xy + delta])
return SLICE_END;
}
return SLICE_OK;
}
}
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
int16_t *mot_val;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
av_assert2(s->h263_pred);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
do {
if (get_bits1(&s->gb)) {
/* skip mb */
s->mb_intra = 0;
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 1;
s->mv[0][0][0] = get_amv(ctx, 0);
s->mv[0][0][1] = get_amv(ctx, 1);
s->mb_skipped = 0;
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 0;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
}
goto end;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 20);
s->bdsp.clear_blocks(s->block[0]);
dquant = cbpc & 8;
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra)
goto intra;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if ((!s->progressive_sequence) &&
(cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
s->interlaced_dct = get_bits1(&s->gb);
s->mv_dir = MV_DIR_FORWARD;
if ((cbpc & 16) == 0) {
if (s->mcsel) {
s->current_picture.mb_type[xy] = MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
/* 16x16 global motion prediction */
s->mv_type = MV_TYPE_16X16;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
} else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
MB_TYPE_L0 |
MB_TYPE_INTERLACED;
/* 16x8 field motion prediction */
s->mv_type = MV_TYPE_FIELD;
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
/* 16x16 motion prediction */
s->mv_type = MV_TYPE_16X16;
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
s->mv_type = MV_TYPE_8X8;
for (i = 0; i < 4; i++) {
mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
mot_val[0] = mx;
mot_val[1] = my;
}
}
} else if (s->pict_type == AV_PICTURE_TYPE_B) {
int modb1; // first bit of modb
int modb2; // second bit of modb
int mb_type;
s->mb_intra = 0; // B-frames never contain intra blocks
s->mcsel = 0; // ... true gmc blocks
if (s->mb_x == 0) {
for (i = 0; i < 2; i++) {
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
}
/* if we skipped it in the future P-frame than skip it now too */
s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
if (s->mb_skipped) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
goto end;
}
modb1 = get_bits1(&s->gb);
if (modb1) {
// like MB_TYPE_B_DIRECT but no vectors coded
mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
cbp = 0;
} else {
modb2 = get_bits1(&s->gb);
mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
if (mb_type < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
return AVERROR_INVALIDDATA;
}
mb_type = mb_type_b_map[mb_type];
if (modb2) {
cbp = 0;
} else {
s->bdsp.clear_blocks(s->block[0]);
cbp = get_bits(&s->gb, 6);
}
if ((!IS_DIRECT(mb_type)) && cbp) {
if (get_bits1(&s->gb))
ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
}
if (!s->progressive_sequence) {
if (cbp)
s->interlaced_dct = get_bits1(&s->gb);
if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
mb_type &= ~MB_TYPE_16x16;
if (USES_LIST(mb_type, 0)) {
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
}
if (USES_LIST(mb_type, 1)) {
s->field_select[1][0] = get_bits1(&s->gb);
s->field_select[1][1] = get_bits1(&s->gb);
}
}
}
s->mv_dir = 0;
if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
s->mv_type = MV_TYPE_16X16;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
s->last_mv[0][1][0] =
s->last_mv[0][0][0] =
s->mv[0][0][0] = mx;
s->last_mv[0][1][1] =
s->last_mv[0][0][1] =
s->mv[0][0][1] = my;
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
s->last_mv[1][1][0] =
s->last_mv[1][0][0] =
s->mv[1][0][0] = mx;
s->last_mv[1][1][1] =
s->last_mv[1][0][1] =
s->mv[1][0][1] = my;
}
} else if (!IS_DIRECT(mb_type)) {
s->mv_type = MV_TYPE_FIELD;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
s->last_mv[0][i][0] =
s->mv[0][i][0] = mx;
s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
}
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
s->last_mv[1][i][0] =
s->mv[1][i][0] = mx;
s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
}
}
}
}
if (IS_DIRECT(mb_type)) {
if (IS_SKIP(mb_type)) {
mx =
my = 0;
} else {
mx = ff_h263_decode_motion(s, 0, 1);
my = ff_h263_decode_motion(s, 0, 1);
}
s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
}
s->current_picture.mb_type[xy] = mb_type;
} else { /* I-Frame */
do {
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
dquant = cbpc & 4;
s->mb_intra = 1;
intra:
s->ac_pred = get_bits1(&s->gb);
if (s->ac_pred)
s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
else
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if (!s->progressive_sequence)
s->interlaced_dct = get_bits1(&s->gb);
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
goto end;
}
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
end:
/* per-MB end of slice check */
if (s->codec_id == AV_CODEC_ID_MPEG4) {
int next = mpeg4_is_resync(ctx);
if (next) {
if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
return AVERROR_INVALIDDATA;
} else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
return SLICE_END;
if (s->pict_type == AV_PICTURE_TYPE_B) {
const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
ff_thread_await_progress(&s->next_picture_ptr->tf,
(s->mb_x + delta >= s->mb_width)
? FFMIN(s->mb_y + 1, s->mb_height - 1)
: s->mb_y, 0);
if (s->next_picture.mbskip_table[xy + delta])
return SLICE_OK;
}
return SLICE_END;
}
}
return SLICE_OK;
}
/* As per spec, studio start code search isn't the same as the old type of start code */
static void next_start_code_studio(GetBitContext *gb)
{
align_get_bits(gb);
while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) {
get_bits(gb, 8);
}
}
/* additional_code, vlc index */
static const uint8_t ac_state_tab[22][2] =
{
{0, 0},
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{1, 2},
{2, 2},
{3, 2},
{4, 2},
{5, 2},
{6, 2},
{1, 3},
{2, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 8},
{7, 9},
{8, 10},
{0, 11}
};
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
static int mpeg4_decode_dpcm_macroblock(MpegEncContext *s, int16_t macroblock[256], int n)
{
int i, j, w, h, idx = 0;
int block_mean, rice_parameter, rice_prefix_code, rice_suffix_code,
dpcm_residual, left, top, topleft, min_left_top, max_left_top, p, p2, output;
h = 16 >> (n ? s->chroma_y_shift : 0);
w = 16 >> (n ? s->chroma_x_shift : 0);
block_mean = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
if (block_mean == 0){
av_log(s->avctx, AV_LOG_ERROR, "Forbidden block_mean\n");
return AVERROR_INVALIDDATA;
}
s->last_dc[n] = block_mean * (1 << (s->dct_precision + s->intra_dc_precision));
rice_parameter = get_bits(&s->gb, 4);
if (rice_parameter == 0) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
if (rice_parameter == 15)
rice_parameter = 0;
if (rice_parameter > 11) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_parameter\n");
return AVERROR_INVALIDDATA;
}
for (i = 0; i < h; i++) {
output = 1 << (s->avctx->bits_per_raw_sample - 1);
top = 1 << (s->avctx->bits_per_raw_sample - 1);
for (j = 0; j < w; j++) {
left = output;
topleft = top;
rice_prefix_code = get_unary(&s->gb, 1, 12);
/* Escape */
if (rice_prefix_code == 11)
dpcm_residual = get_bits(&s->gb, s->avctx->bits_per_raw_sample);
else {
if (rice_prefix_code == 12) {
av_log(s->avctx, AV_LOG_ERROR, "Forbidden rice_prefix_code\n");
return AVERROR_INVALIDDATA;
}
rice_suffix_code = get_bitsz(&s->gb, rice_parameter);
dpcm_residual = (rice_prefix_code << rice_parameter) + rice_suffix_code;
}
/* Map to a signed residual */
if (dpcm_residual & 1)
dpcm_residual = (-1 * dpcm_residual) >> 1;
else
dpcm_residual = (dpcm_residual >> 1);
if (i != 0)
top = macroblock[idx-w];
p = left + top - topleft;
min_left_top = FFMIN(left, top);
if (p < min_left_top)
p = min_left_top;
max_left_top = FFMAX(left, top);
if (p > max_left_top)
p = max_left_top;
p2 = (FFMIN(min_left_top, topleft) + FFMAX(max_left_top, topleft)) >> 1;
if (p2 == p)
p2 = block_mean;
if (p2 > p)
dpcm_residual *= -1;
macroblock[idx++] = output = (dpcm_residual + p) & ((1 << s->avctx->bits_per_raw_sample) - 1);
}
}
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
s->dpcm_direction = 0;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
s->dpcm_direction = get_bits1(&s->gb) ? -1 : 1;
for (i = 0; i < 3; i++) {
if (mpeg4_decode_dpcm_macroblock(s, (*s->dpcm_macroblock)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
//vcon-stp9L1.bits (first frame)
if (get_bits_left(&s->gb) == 0)
return SLICE_END;
//vcon-stp2L1.bits, vcon-stp3L1.bits, vcon-stp6L1.bits, vcon-stp7L1.bits, vcon-stp8L1.bits, vcon-stp10L1.bits (first frame)
if (get_bits_left(&s->gb) < 8U && show_bits(&s->gb, get_bits_left(&s->gb)) == 0)
return SLICE_END;
return SLICE_OK;
}
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
{
int hours, minutes, seconds;
if (!show_bits(gb, 23)) {
av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
return AVERROR_INVALIDDATA;
}
hours = get_bits(gb, 5);
minutes = get_bits(gb, 6);
check_marker(s->avctx, gb, "in gop_header");
seconds = get_bits(gb, 6);
s->time_base = seconds + 60*(minutes + 60*hours);
skip_bits1(gb);
skip_bits1(gb);
return 0;
}
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
{
*profile = get_bits(gb, 4);
*level = get_bits(gb, 4);
// for Simple profile, level 0
if (*profile == 0 && *level == 8) {
*level = 0;
}
return 0;
}
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
{
int visual_object_type;
int is_visual_object_identifier = get_bits1(gb);
if (is_visual_object_identifier) {
skip_bits(gb, 4+3);
}
visual_object_type = get_bits(gb, 4);
if (visual_object_type == VOT_VIDEO_ID ||
visual_object_type == VOT_STILL_TEXTURE_ID) {
int video_signal_type = get_bits1(gb);
if (video_signal_type) {
int video_range, color_description;
skip_bits(gb, 3); // video_format
video_range = get_bits1(gb);
color_description = get_bits1(gb);
s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (color_description) {
s->avctx->color_primaries = get_bits(gb, 8);
s->avctx->color_trc = get_bits(gb, 8);
s->avctx->colorspace = get_bits(gb, 8);
}
}
}
return 0;
}
static void mpeg4_load_default_matrices(MpegEncContext *s)
{
int i, v;
/* load default matrices */
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg4_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
v = ff_mpeg4_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height, vo_ver_id;
/* vol header */
skip_bits(gb, 1); /* random access */
s->vo_type = get_bits(gb, 8);
/* If we are in studio profile (per vo_type), check if its all consistent
* and if so continue pass control to decode_studio_vol_header().
* elIf something is inconsistent, error out
* else continue with (non studio) vol header decpoding.
*/
if (s->vo_type == CORE_STUDIO_VO_TYPE ||
s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
return AVERROR_INVALIDDATA;
s->studio_profile = 1;
s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
return decode_studio_vol_header(ctx, gb);
} else if (s->studio_profile) {
return AVERROR_PATCHWELCOME;
}
if (get_bits1(gb) != 0) { /* is_ol_id */
vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
skip_bits(gb, 3); /* vo_priority */
} else {
vo_ver_id = 1;
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
int chroma_format = get_bits(gb, 2);
if (chroma_format != CHROMA_420)
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
s->low_delay = get_bits1(gb);
if (get_bits1(gb)) { /* vbv parameters */
get_bits(gb, 15); /* first_half_bitrate */
check_marker(s->avctx, gb, "after first_half_bitrate");
get_bits(gb, 15); /* latter_half_bitrate */
check_marker(s->avctx, gb, "after latter_half_bitrate");
get_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
get_bits(gb, 3); /* latter_half_vbv_buffer_size */
get_bits(gb, 11); /* first_half_vbv_occupancy */
check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
get_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
}
} else {
/* is setting low delay flag only once the smartest thing to do?
* low delay detection will not be overridden. */
if (s->picture_number == 0) {
switch(s->vo_type) {
case SIMPLE_VO_TYPE:
case ADV_SIMPLE_VO_TYPE:
s->low_delay = 1;
break;
default:
s->low_delay = 0;
}
}
}
ctx->shape = get_bits(gb, 2); /* vol shape */
if (ctx->shape != RECT_SHAPE)
av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
skip_bits(gb, 4); /* video_object_layer_shape_extension */
}
check_marker(s->avctx, gb, "before time_increment_resolution");
s->avctx->framerate.num = get_bits(gb, 16);
if (!s->avctx->framerate.num) {
av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
return AVERROR_INVALIDDATA;
}
ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
if (ctx->time_increment_bits < 1)
ctx->time_increment_bits = 1;
check_marker(s->avctx, gb, "before fixed_vop_rate");
if (get_bits1(gb) != 0) /* fixed_vop_rate */
s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
else
s->avctx->framerate.den = 1;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
ctx->t_frame = 0;
if (ctx->shape != BIN_ONLY_SHAPE) {
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before width");
width = get_bits(gb, 13);
check_marker(s->avctx, gb, "before height");
height = get_bits(gb, 13);
check_marker(s->avctx, gb, "after height");
if (width && height && /* they should be non zero but who knows */
!(s->width && s->codec_tag == AV_RL32("MP4S"))) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->progressive_sequence =
s->progressive_frame = get_bits1(gb) ^ 1;
s->interlaced_dct = 0;
if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */
"MPEG-4 OBMC not supported (very likely buggy encoder)\n");
if (vo_ver_id == 1)
ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
else
ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE) {
if (ctx->vol_sprite_usage == STATIC_SPRITE) {
skip_bits(gb, 13); // sprite_width
check_marker(s->avctx, gb, "after sprite_width");
skip_bits(gb, 13); // sprite_height
check_marker(s->avctx, gb, "after sprite_height");
skip_bits(gb, 13); // sprite_left
check_marker(s->avctx, gb, "after sprite_left");
skip_bits(gb, 13); // sprite_top
check_marker(s->avctx, gb, "after sprite_top");
}
ctx->num_sprite_warping_points = get_bits(gb, 6);
if (ctx->num_sprite_warping_points > 3) {
av_log(s->avctx, AV_LOG_ERROR,
"%d sprite_warping_points\n",
ctx->num_sprite_warping_points);
ctx->num_sprite_warping_points = 0;
return AVERROR_INVALIDDATA;
}
s->sprite_warping_accuracy = get_bits(gb, 2);
ctx->sprite_brightness_change = get_bits1(gb);
if (ctx->vol_sprite_usage == STATIC_SPRITE)
skip_bits1(gb); // low_latency_sprite
}
// FIXME sadct disable bit if verid!=1 && shape not rect
if (get_bits1(gb) == 1) { /* not_8_bit */
s->quant_precision = get_bits(gb, 4); /* quant_precision */
if (get_bits(gb, 4) != 8) /* bits_per_pixel */
av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
if (s->quant_precision != 5)
av_log(s->avctx, AV_LOG_ERROR,
"quant precision %d\n", s->quant_precision);
if (s->quant_precision<3 || s->quant_precision>9) {
s->quant_precision = 5;
}
} else {
s->quant_precision = 5;
}
// FIXME a bunch of grayscale shape things
if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
int i, v;
mpeg4_load_default_matrices(s);
/* load custom intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
}
/* load custom non intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = last;
s->chroma_inter_matrix[j] = last;
}
}
// FIXME a bunch of grayscale shape things
}
if (vo_ver_id != 1)
s->quarter_sample = get_bits1(gb);
else
s->quarter_sample = 0;
if (get_bits_left(gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
return AVERROR_INVALIDDATA;
}
if (!get_bits1(gb)) {
int pos = get_bits_count(gb);
int estimation_method = get_bits(gb, 2);
if (estimation_method < 2) {
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */
ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */
ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (estimation_method == 1) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */
}
} else
av_log(s->avctx, AV_LOG_ERROR,
"Invalid Complexity estimation method %d\n",
estimation_method);
} else {
no_cplx_est:
ctx->cplx_estimation_trash_i =
ctx->cplx_estimation_trash_p =
ctx->cplx_estimation_trash_b = 0;
}
ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
s->data_partitioning = get_bits1(gb);
if (s->data_partitioning)
ctx->rvlc = get_bits1(gb);
if (vo_ver_id != 1) {
ctx->new_pred = get_bits1(gb);
if (ctx->new_pred) {
av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
skip_bits(gb, 2); /* requested upstream message type */
skip_bits1(gb); /* newpred segment type */
}
if (get_bits1(gb)) // reduced_res_vop
av_log(s->avctx, AV_LOG_ERROR,
"reduced resolution VOP not supported\n");
} else {
ctx->new_pred = 0;
}
ctx->scalability = get_bits1(gb);
if (ctx->scalability) {
GetBitContext bak = *gb;
int h_sampling_factor_n;
int h_sampling_factor_m;
int v_sampling_factor_n;
int v_sampling_factor_m;
skip_bits1(gb); // hierarchy_type
skip_bits(gb, 4); /* ref_layer_id */
skip_bits1(gb); /* ref_layer_sampling_dir */
h_sampling_factor_n = get_bits(gb, 5);
h_sampling_factor_m = get_bits(gb, 5);
v_sampling_factor_n = get_bits(gb, 5);
v_sampling_factor_m = get_bits(gb, 5);
ctx->enhancement_type = get_bits1(gb);
if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
/* illegal scalability header (VERY broken encoder),
* trying to workaround */
ctx->scalability = 0;
*gb = bak;
} else
av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
// bin shape stuff FIXME
}
}
if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n",
s->avctx->framerate.den, s->avctx->framerate.num,
ctx->time_increment_bits,
s->quant_precision,
s->progressive_sequence,
s->low_delay,
ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
);
}
return 0;
}
/**
* Decode the user data stuff in the header.
* Also initializes divx/xvid/lavc_version/build.
*/
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
char buf[256];
int i;
int e;
int ver = 0, build = 0, ver2 = 0, ver3 = 0;
char last;
for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
if (show_bits(gb, 23) == 0)
break;
buf[i] = get_bits(gb, 8);
}
buf[i] = 0;
/* divx detection */
e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
if (e < 2)
e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
if (e >= 2) {
ctx->divx_version = ver;
ctx->divx_build = build;
s->divx_packed = e == 3 && last == 'p';
}
/* libavcodec detection */
e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
if (e != 4)
e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
if (e != 4) {
e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
if (e > 1) {
if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
av_log(s->avctx, AV_LOG_WARNING,
"Unknown Lavc version string encountered, %d.%d.%d; "
"clamping sub-version values to 8-bits.\n",
ver, ver2, ver3);
}
build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
}
}
if (e != 4) {
if (strcmp(buf, "ffmpeg") == 0)
ctx->lavc_build = 4600;
}
if (e == 4)
ctx->lavc_build = build;
/* Xvid detection */
e = sscanf(buf, "XviD%d", &build);
if (e == 1)
ctx->xvid_build = build;
return 0;
}
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
if (s->codec_tag == AV_RL32("XVID") ||
s->codec_tag == AV_RL32("XVIX") ||
s->codec_tag == AV_RL32("RMP4") ||
s->codec_tag == AV_RL32("ZMP4") ||
s->codec_tag == AV_RL32("SIPP"))
ctx->xvid_build = 0;
}
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
ctx->vol_control_parameters == 0)
ctx->divx_version = 400; // divx 4
if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
ctx->divx_version =
ctx->divx_build = -1;
}
if (s->workaround_bugs & FF_BUG_AUTODETECT) {
if (s->codec_tag == AV_RL32("XVIX"))
s->workaround_bugs |= FF_BUG_XVID_ILACE;
if (s->codec_tag == AV_RL32("UMP4"))
s->workaround_bugs |= FF_BUG_UMP4;
if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->divx_version > 502 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
if (ctx->xvid_build <= 3U)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->xvid_build <= 1U)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->xvid_build <= 12U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->xvid_build <= 32U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \
s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \
s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if (ctx->lavc_build < 4653U)
s->workaround_bugs |= FF_BUG_STD_QPEL;
if (ctx->lavc_build < 4655U)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->lavc_build < 4670U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->lavc_build <= 4712U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
if ((ctx->lavc_build&0xFF) >= 100) {
if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
(ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
)
s->workaround_bugs |= FF_BUG_IEDGE;
}
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->divx_version < 500U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
}
if (s->workaround_bugs & FF_BUG_STD_QPEL) {
SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if (avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG,
"bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
s->codec_id == AV_CODEC_ID_MPEG4 &&
avctx->idct_algo == FF_IDCT_AUTO) {
avctx->idct_algo = FF_IDCT_XVID;
ff_mpv_idct_init(s);
return 1;
}
return 0;
}
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int time_incr, time_increment;
int64_t pts;
s->mcsel = 0;
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */
if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
s->low_delay = 0;
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
if (s->partitioned_frame)
s->decode_mb = mpeg4_decode_partitioned_mb;
else
s->decode_mb = mpeg4_decode_mb;
time_incr = 0;
while (get_bits1(gb) != 0)
time_incr++;
check_marker(s->avctx, gb, "before time_increment");
if (ctx->time_increment_bits == 0 ||
!(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
for (ctx->time_increment_bits = 1;
ctx->time_increment_bits < 16;
ctx->time_increment_bits++) {
if (s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE)) {
if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
break;
} else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
break;
}
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
s->avctx->framerate.num = 1<<ctx->time_increment_bits;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
}
}
if (IS_3IV1)
time_increment = get_bits1(gb); // FIXME investigate further
else
time_increment = get_bits(gb, ctx->time_increment_bits);
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_time_base = s->time_base;
s->time_base += time_incr;
s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
if (s->workaround_bugs & FF_BUG_UMP4) {
if (s->time < s->last_non_b_time) {
/* header is not mpeg-4-compatible, broken encoder,
* trying to workaround */
s->time_base++;
s->time += s->avctx->framerate.num;
}
}
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
if (s->pp_time <= s->pb_time ||
s->pp_time <= s->pp_time - s->pb_time ||
s->pp_time <= 0) {
/* messed up order, maybe after seeking? skipping current B-frame */
return FRAME_SKIPPED;
}
ff_mpeg4_init_direct_mv(s);
if (ctx->t_frame == 0)
ctx->t_frame = s->pb_time;
if (ctx->t_frame == 0)
ctx->t_frame = 1; // 1/0 protection
s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
s->pb_field_time = 2;
s->pp_field_time = 4;
if (!s->progressive_sequence)
return FRAME_SKIPPED;
}
}
if (s->avctx->framerate.den)
pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
else
pts = AV_NOPTS_VALUE;
ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
check_marker(s->avctx, gb, "before vop_coded");
/* vop coded */
if (get_bits1(gb) != 1) {
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
return FRAME_SKIPPED;
}
if (ctx->new_pred)
decode_new_pred(ctx, gb);
if (ctx->shape != BIN_ONLY_SHAPE &&
(s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE))) {
/* rounding type for motion estimation */
s->no_rounding = get_bits1(gb);
} else {
s->no_rounding = 0;
}
// FIXME reduced res stuff
if (ctx->shape != RECT_SHAPE) {
if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
skip_bits(gb, 13); /* width */
check_marker(s->avctx, gb, "after width");
skip_bits(gb, 13); /* height */
check_marker(s->avctx, gb, "after height");
skip_bits(gb, 13); /* hor_spat_ref */
check_marker(s->avctx, gb, "after hor_spat_ref");
skip_bits(gb, 13); /* ver_spat_ref */
}
skip_bits1(gb); /* change_CR_disable */
if (get_bits1(gb) != 0)
skip_bits(gb, 8); /* constant_alpha_value */
}
// FIXME complexity estimation stuff
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits_long(gb, ctx->cplx_estimation_trash_i);
if (s->pict_type != AV_PICTURE_TYPE_I)
skip_bits_long(gb, ctx->cplx_estimation_trash_p);
if (s->pict_type == AV_PICTURE_TYPE_B)
skip_bits_long(gb, ctx->cplx_estimation_trash_b);
if (get_bits_left(gb) < 3) {
av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
return AVERROR_INVALIDDATA;
}
ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
if (!s->progressive_sequence) {
s->top_field_first = get_bits1(gb);
s->alternate_scan = get_bits1(gb);
} else
s->alternate_scan = 0;
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
if (s->pict_type == AV_PICTURE_TYPE_S) {
if((ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE)) {
if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
return AVERROR_INVALIDDATA;
if (ctx->sprite_brightness_change)
av_log(s->avctx, AV_LOG_ERROR,
"sprite_brightness_change not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
} else {
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
}
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (qscale=0)\n");
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
if (s->pict_type != AV_PICTURE_TYPE_I) {
s->f_code = get_bits(gb, 3); /* fcode_for */
if (s->f_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (f_code=0)\n");
s->f_code = 1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
} else
s->f_code = 1;
if (s->pict_type == AV_PICTURE_TYPE_B) {
s->b_code = get_bits(gb, 3);
if (s->b_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG4 header (b_code=0)\n");
s->b_code=1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
}
} else
s->b_code = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG,
"qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
s->qscale, s->f_code, s->b_code,
s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
s->top_field_first, s->quarter_sample ? "q" : "h",
s->data_partitioning, ctx->resync_marker,
ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
1 - s->no_rounding, s->vo_type,
ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
ctx->cplx_estimation_trash_b,
s->time,
time_increment
);
}
if (!ctx->scalability) {
if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
skip_bits1(gb); // vop shape coding type
} else {
if (ctx->enhancement_type) {
int load_backward_shape = get_bits1(gb);
if (load_backward_shape)
av_log(s->avctx, AV_LOG_ERROR,
"load backward shape isn't supported\n");
}
skip_bits(gb, 2); // ref_select_code
}
}
/* detect buggy encoders which don't set the low_delay flag
* (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
* easily (although it's buggy too) */
if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
ctx->divx_version == -1 && s->picture_number == 0) {
av_log(s->avctx, AV_LOG_WARNING,
"looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
s->low_delay = 1;
}
s->picture_number++; // better than pic number==0 always ;)
// FIXME add short header support
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->workaround_bugs & FF_BUG_EDGE) {
s->h_edge_pos = s->width;
s->v_edge_pos = s->height;
}
return 0;
}
static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
if (get_bits_left(gb) < 64*8)
return AVERROR_INVALIDDATA;
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
return 0;
}
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
{
uint32_t startcode;
uint8_t extension_type;
startcode = show_bits_long(gb, 32);
if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
skip_bits_long(gb, 32);
extension_type = get_bits(gb, 4);
if (extension_type == QUANT_MATRIX_EXT_ID)
read_quant_matrix_ext(s, gb);
}
}
}
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
skip_bits(gb, 16); /* Time_code[63..48] */
check_marker(s->avctx, gb, "after Time_code[63..48]");
skip_bits(gb, 16); /* Time_code[47..32] */
check_marker(s->avctx, gb, "after Time_code[47..32]");
skip_bits(gb, 16); /* Time_code[31..16] */
check_marker(s->avctx, gb, "after Time_code[31..16]");
skip_bits(gb, 16); /* Time_code[15..0] */
check_marker(s->avctx, gb, "after Time_code[15..0]");
skip_bits(gb, 4); /* reserved_bits */
}
/**
* Decode the next studio vop header.
* @return <0 if something went wrong
*/
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->partitioned_frame = 0;
s->interlaced_dct = 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int visual_object_type;
skip_bits(gb, 4); /* visual_object_verid */
visual_object_type = get_bits(gb, 4);
if (visual_object_type != VOT_VIDEO_ID) {
avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
return AVERROR_PATCHWELCOME;
}
next_start_code_studio(gb);
extension_and_user_data(s, gb, 1);
return 0;
}
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height;
int bits_per_raw_sample;
// random_accessible_vol and video_object_type_indication have already
// been read by the caller decode_vol_header()
skip_bits(gb, 4); /* video_object_layer_verid */
ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
skip_bits(gb, 4); /* video_object_layer_shape_extension */
skip_bits1(gb); /* progressive_sequence */
if (ctx->shape != BIN_ONLY_SHAPE) {
ctx->rgb = get_bits1(gb); /* rgb_components */
s->chroma_format = get_bits(gb, 2); /* chroma_format */
if (!s->chroma_format) {
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
return AVERROR_INVALIDDATA;
}
bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
if (bits_per_raw_sample == 10) {
if (ctx->rgb) {
s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
}
else {
s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
}
}
else {
avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = bits_per_raw_sample;
}
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before video_object_layer_width");
width = get_bits(gb, 14); /* video_object_layer_width */
check_marker(s->avctx, gb, "before video_object_layer_height");
height = get_bits(gb, 14); /* video_object_layer_height */
check_marker(s->avctx, gb, "after video_object_layer_height");
/* Do the same check as non-studio profile */
if (width && height) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
skip_bits(gb, 4); /* frame_rate_code */
skip_bits(gb, 15); /* first_half_bit_rate */
check_marker(s->avctx, gb, "after first_half_bit_rate");
skip_bits(gb, 15); /* latter_half_bit_rate */
check_marker(s->avctx, gb, "after latter_half_bit_rate");
skip_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
skip_bits(gb, 11); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
s->low_delay = get_bits1(gb);
s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
next_start_code_studio(gb);
extension_and_user_data(s, gb, 2);
return 0;
}
/**
* Decode MPEG-4 headers.
* @return <0 if no VOP found (or a damaged one)
* FRAME_SKIPPED if a not coded VOP is found
* 0 if a VOP is found
*/
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
// If we have not switched to studio profile than we also did not switch bps
// that means something else (like a previous instance) outside set bps which
// would be inconsistant with the currect state, thus reset it
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
av_cold void ff_mpeg4videodec_static_init(void) {
static int done = 0;
if (!done) {
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_lum[0][1], 2, 1,
&ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_chrom[0][1], 2, 1,
&ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
&ff_sprite_trajectory_tab[0][1], 4, 2,
&ff_sprite_trajectory_tab[0][0], 4, 2, 128);
INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
&ff_mb_type_b_tab[0][1], 2, 1,
&ff_mb_type_b_tab[0][0], 2, 1, 16);
done = 1;
}
}
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
/* divx 5.01+ bitstream reorder stuff */
/* Since this clobbers the input buffer and hwaccel codecs still need the
* data during hwaccel->end_frame we should not do this any earlier */
if (s->divx_packed) {
int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
int startcode_found = 0;
if (buf_size - current_pos > 7) {
int i;
for (i = current_pos; i < buf_size - 4; i++)
if (buf[i] == 0 &&
buf[i + 1] == 0 &&
buf[i + 2] == 1 &&
buf[i + 3] == 0xB6) {
startcode_found = !(buf[i + 4] & 0x40);
break;
}
}
if (startcode_found) {
if (!ctx->showed_packed_warning) {
av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
"wasteful way to store B-frames ('packed B-frames'). "
"Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
ctx->showed_packed_warning = 1;
}
av_fast_padded_malloc(&s->bitstream_buffer,
&s->allocated_bitstream_buffer_size,
buf_size - current_pos);
if (!s->bitstream_buffer) {
s->bitstream_buffer_size = 0;
return AVERROR(ENOMEM);
}
memcpy(s->bitstream_buffer, buf + current_pos,
buf_size - current_pos);
s->bitstream_buffer_size = buf_size - current_pos;
}
}
return 0;
}
#if HAVE_THREADS
static int mpeg4_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
Mpeg4DecContext *s = dst->priv_data;
const Mpeg4DecContext *s1 = src->priv_data;
int init = s->m.context_initialized;
int ret = ff_mpeg_update_thread_context(dst, src);
if (ret < 0)
return ret;
memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
ff_xvid_idct_init(&s->m.idsp, dst);
return 0;
}
#endif
static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
int ret;
ctx->divx_version =
ctx->divx_build =
ctx->xvid_build =
ctx->lavc_build = -1;
if ((ret = ff_h263_decode_init(avctx)) < 0)
return ret;
ff_mpeg4videodec_static_init();
if ((ret = init_studio_vlcs(ctx)) < 0)
return ret;
s->h263_pred = 1;
s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
s->decode_mb = mpeg4_decode_mb;
ctx->time_increment_bits = 4; /* default value for broken headers */
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
avctx->internal->allocate_progress = 1;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
int i;
if (!avctx->internal->is_copy) {
for (i = 0; i < 12; i++)
ff_free_vlc(&ctx->studio_intra_tab[i]);
ff_free_vlc(&ctx->studio_luma_dc);
ff_free_vlc(&ctx->studio_chroma_dc);
}
return ff_h263_decode_end(avctx);
}
static const AVOption mpeg4_options[] = {
{"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{NULL}
};
static const AVClass mpeg4_class = {
.class_name = "MPEG4 Video Decoder",
.item_name = av_default_item_name,
.option = mpeg4_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_decoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(Mpeg4DecContext),
.init = decode_init,
.close = decode_end,
.decode = ff_h263_decode_frame,
.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_h263_hwaccel_pixfmt_list_420,
.profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
.update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
.priv_class = &mpeg4_class,
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_MPEG4_NVDEC_HWACCEL
HWACCEL_NVDEC(mpeg4),
#endif
#if CONFIG_MPEG4_VAAPI_HWACCEL
HWACCEL_VAAPI(mpeg4),
#endif
#if CONFIG_MPEG4_VDPAU_HWACCEL
HWACCEL_VDPAU(mpeg4),
#endif
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(mpeg4),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_800_0 |
crossvul-cpp_data_bad_149_0 | /* radare - LGPL - Copyright 2010-2013 eloi<limited-entropy.com> */
#include <string.h>
#include <r_types.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
#define API static
#define LONG_SIZE 4
#define WORD_SIZE 2
#define BYTE_SIZE 1
/* missing opcodes :
- FPU (opcodes 0xF___)
- opcodes > SH2E
- cmp*
- "special" regs : PR, SR, VBR, GBR, MACL, MACH
- T flag handling
- 0x0___
- 0x2___
- 0x3___ ops : cmp*, div, dmul
- 0x4___ ops : ld*, st*
- 0x6___ implement (ext*, pop, swap, ...)
- 0x8___ implement cmp/eq imm,Rn
- 0xC___ implement {mova, T flag dest, (disp,GBR) src/dst}
- 0xF___ FPU: everything
*** complete :
0x1___
0x5___
0x7___
0x9___ (XXX verify if @(disp,PC) works)
0xA___
0xB___
0xD___
0xE___
*/
//Macros for different instruction types
#define IS_CLRT(x) x == 0x0008
#define IS_NOP(x) x == 0x0009
#define IS_RTS(x) x == 0x000b
#define IS_SETT(x) x == 0x0018
#define IS_DIV0U(x) x == 0x0019
#define IS_SLEEP(x) x == 0x001b
#define IS_CLRMAC(x) x == 0x0028
#define IS_RTE(x) x == 0x002b
//#define IS_CLRS(x)
#define IS_STCSR1(x) (((x) & 0xF0CF) == 0x0002) //mask stc Rn,{SR,GBR,VBR,SSR}
#define IS_BSRF(x) (x & 0xf0ff) == 0x0003
#define IS_BRAF(x) (((x) & 0xf0ff) == 0x0023)
#define IS_MOVB_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0004)
#define IS_MOVW_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0005)
#define IS_MOVL_REG_TO_R0REL(x) (((x) & 0xF00F) == 0x0006)
#define IS_MULL(x) (((x) & 0xF00F) == 0x0007)
#define IS_MOVB_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000C)
#define IS_MOVW_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000D)
#define IS_MOVL_R0REL_TO_REG(x) (((x) & 0xF00F) == 0x000E)
//#define IS_MACL(x) (((x) & 0xF00F) == 0x000F) //complicated !
#define IS_MOVT(x) (((x) & 0xF0FF) == 0x0029)
#define IS_STSMAC(x) (((x) & 0xF0EF) == 0x000A) //mask sts Rn, MAC*
#define IS_STSPR(x) (((x) & 0xF0FF) == 0x002A)
//#define IS_STSFPUL(x) (((x) & 0xF0FF) == 0x005A) //FP*: todo maybe someday
//#define IS_STSFPSCR(x) (((x) & 0xF0FF) == 0x006A)
#define IS_MOVB_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2000)
#define IS_MOVW_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2001)
#define IS_MOVL_REG_TO_REGREF(x) (((x) & 0xF00F) == 0x2002)
//#define invalid?(x) (((x) & 0xF00F) == 0x2003) //illegal on sh2e
#define IS_PUSHB(x) (((x) & 0xF00F) == 0x2004)
#define IS_PUSHW(x) (((x) & 0xF00F) == 0x2005)
#define IS_PUSHL(x) (((x) & 0xF00F) == 0x2006)
#define IS_DIV0S(x) (((x) & 0xF00F) == 0x2007)
#define IS_TSTRR(x) (((x) & 0xF00F) == 0x2008)
#define IS_AND_REGS(x) (((x) & 0xF00F) == 0x2009)
#define IS_XOR_REGS(x) (((x) & 0xF00F) == 0x200A)
#define IS_OR_REGS(x) (((x) & 0xF00F) == 0x200B)
#define IS_CMPSTR(x) (((x) & 0xF00F) == 0x200C)
#define IS_XTRCT(x) (((x) & 0xF00F) == 0x200D)
#define IS_MULUW(x) (((x) & 0xF00F) == 0x200E)
#define IS_MULSW(x) (((x) & 0xF00F) == 0x200F)
#define IS_CMPEQ(x) (((x) & 0xF00F) == 0x3000)
//#define invalid?(x) (((x) & 0xF00F) == 0x3001)
#define IS_CMPHS(x) (((x) & 0xF00F) == 0x3002)
#define IS_CMPGE(x) (((x) & 0xF00F) == 0x3003)
#define IS_CMPHI(x) (((x) & 0xF00F) == 0x3006)
#define IS_CMPGT(x) (((x) & 0xF00F) == 0x3007)
#define IS_DIV1(x) (((x) & 0xF00F) == 0x3004)
#define IS_DMULU(x) (((x) & 0xF00F) == 0x3005)
#define IS_DMULS(x) (((x) & 0xF00F) == 0x300D)
#define IS_SUB(x) (((x) & 0xF00F) == 0x3008)
//#define invalid?(x) (((x) & 0xF00F) == 0x3009)
#define IS_SUBC(x) (((x) & 0xF00F) == 0x300A)
#define IS_SUBV(x) (((x) & 0xF00F) == 0x300B)
#define IS_ADD(x) (((x) & 0xF00F) == 0x300C)
#define IS_ADDC(x) (((x) & 0xF00F) == 0x300E)
#define IS_ADDV(x) (((x) & 0xF00F) == 0x300F)
//#define IS_MACW(x) (((x) & 0xF00F) == 0x400F) //complex
#define IS_JSR(x) (((x) & 0xf0ff) == 0x400b)
#define IS_JMP(x) (((x) & 0xf0ff) == 0x402b)
#define IS_CMPPL(x) (((x) & 0xf0ff) == 0x4015)
#define IS_CMPPZ(x) (((x) & 0xf0ff) == 0x4011)
#define IS_LDCSR1(x) (((x) & 0xF0CF) == 0x400E) //mask ldc Rn,{SR,GBR,VBR,SSR}
#define IS_LDCLSR1(x) (((x) & 0xF0CF) == 0x4007) //mask ldc.l @Rn+,{SR,GBR,VBR,SSR}
#define IS_LDSMAC(x) (((x) & 0xF0EF) == 0x400A) //mask lds Rn, MAC*
#define IS_LDSLMAC(x) (((x) & 0xF0EF) == 0x4006) //mask lds.l @Rn+, MAC*
#define IS_LDSPR(x) (((x) & 0xF0FF) == 0x402A)
#define IS_LDSLPR(x) (((x) & 0xF0FF) == 0x4026)
//#define IS_LDSFPUL(x) (((x) & 0xF0FF) == 0x405A) //FP*: todo maybe someday
//#define IS_LDSFPSCR(x) (((x) & 0xF0FF) == 0x406A)
//#define IS_LDSLFPUL(x) (((x) & 0xF0FF) == 0x4066)
//#define IS_LDSLFPSCR(x) (((x) & 0xF0FF) == 0x4056)
#define IS_ROT(x) (((x) & 0xF0DE) == 0x4004) //mask rot{,c}{l,r}
//not on sh2e : shad, shld
//#define IS_SHIFT1(x) (((x) & 0xF0DE) == 0x4000) //unused (treated as switch-case)
//other shl{l,r}{,2,8,16} in switch case also.
#define IS_STSLMAC(x) (((x) & 0xF0EF) == 0x4002) //mask sts.l mac*, @-Rn
#define IS_STCLSR1(x) (((x) & 0xF0CF) == 0x4003) //mask stc.l {SR,GBR,VBR,SSR},@-Rn
//todo: other stc.l not on sh2e
#define IS_STSLPR(x) (((x) & 0xF0FF) == 0x4022)
//#define IS_STSLFPUL(x) (((x) & 0xF0FF) == 0x4052)
//#define IS_STSLFPSCR(x) (((x) & 0xF0FF) == 0x4062)
#define IS_TASB(x) (((x) & 0xF0FF) == 0x401B)
#define IS_DT(x) (((x) & 0xF0FF) == 0x4010)
#define IS_MOVB_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6000)
#define IS_MOVW_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6001)
#define IS_MOVL_REGREF_TO_REG(x) (((x) & 0xF00F) == 0x6002)
#define IS_MOV_REGS(x) (((x) & 0xf00f) == 0x6003)
#define IS_MOVB_POP(x) (((x) & 0xF00F) == 0x6004)
#define IS_MOVW_POP(x) (((x) & 0xF00F) == 0x6005)
#define IS_MOVL_POP(x) (((x) & 0xF00F) == 0x6006)
#define IS_NOT(x) (((x) & 0xF00F) == 0x6007)
#define IS_SWAP(x) (((x) & 0xF00E) == 0x6008) //match swap.{b,w}
#define IS_NEG(x) (((x) & 0xF00E) == 0x600A) //match neg{,c}
#define IS_EXT(x) (((x) & 0xF00C) == 0x600C) //match ext{s,u}.{b,w}
#define IS_MOVB_R0_REGDISP(x) (((x) & 0xFF00) == 0x8000)
#define IS_MOVW_R0_REGDISP(x) (((x) & 0xFF00) == 0x8100)
//#define illegal?(x) (((x) & 0xF900) == 0x8000) //match 8{2,3,6,7}00
#define IS_MOVB_REGDISP_R0(x) (((x) & 0xFF00) == 0x8400)
#define IS_MOVW_REGDISP_R0(x) (((x) & 0xFF00) == 0x8500)
#define IS_CMPIMM(x) (((x) & 0xFF00) == 0x8800)
//#define illegal?(x) (((x) & 0xFB00) == 0x8A00) //match 8{A,E}00
#define IS_BT(x) (((x) & 0xff00) == 0x8900)
#define IS_BF(x) (((x) & 0xff00) == 0x8B00)
#define IS_BTS(x) (((x) & 0xff00) == 0x8D00)
#define IS_BFS(x) (((x) & 0xff00) == 0x8F00)
#define IS_BT_OR_BF(x) IS_BT(x)||IS_BTS(x)||IS_BF(x)||IS_BFS(x)
#define IS_MOVB_R0_GBRREF(x) (((x) & 0xFF00) == 0xC000)
#define IS_MOVW_R0_GBRREF(x) (((x) & 0xFF00) == 0xC100)
#define IS_MOVL_R0_GBRREF(x) (((x) & 0xFF00) == 0xC200)
#define IS_TRAP(x) (((x) & 0xFF00) == 0xC300)
#define IS_MOVB_GBRREF_R0(x) (((x) & 0xFF00) == 0xC400)
#define IS_MOVW_GBRREF_R0(x) (((x) & 0xFF00) == 0xC500)
#define IS_MOVL_GBRREF_R0(x) (((x) & 0xFF00) == 0xC600)
#define IS_MOVA_PCREL_R0(x) (((x) & 0xFF00) == 0xC700)
#define IS_BINLOGIC_IMM_R0(x) (((x) & 0xFC00) == 0xC800) //match C{8,9,A,B}00
#define IS_BINLOGIC_IMM_GBR(x) (((x) & 0xFC00) == 0xCC00) //match C{C,D,E,F}00 : *.b #imm, @(R0,GBR)
/* Compute PC-relative displacement for branch instructions */
#define GET_BRA_OFFSET(x) ((x) & 0x0fff)
#define GET_BTF_OFFSET(x) ((x) & 0x00ff)
/* Compute reg nr for BRAF,BSR,BSRF,JMP,JSR */
#define GET_TARGET_REG(x) ((x >> 8) & 0x0f)
#define GET_SOURCE_REG(x) ((x >> 4) & 0x0f)
/* index of PC reg in regs[] array*/
#define PC_IDX 16
/* for {bra,bsr} only: (sign-extend 12bit offset)<<1 + PC +4 */
static ut64 disarm_12bit_offset (RAnalOp *op, unsigned int insoff) {
ut64 off = insoff;
/* sign extend if higher bit is 1 (0x0800) */
if ((off & 0x0800) == 0x0800)
{
off |= ~0xFFF;
}
return (op->addr) + (off<<1) + 4;
}
/* for bt,bf sign-extended offsets : return PC+4+ (exts.b offset)<<1 */
static ut64 disarm_8bit_offset (ut64 pc, ut32 offs) {
/* pc (really, op->addr) is 64 bits, so we need to sign-extend
* to 64 bits instead of the 32 the actual CPU does */
ut64 off = offs;
/* sign extend if higher bit is 1 (0x08) */
if ((off & 0x80) == 0x80)
{
off |= ~0xFF;
}
return (off<<1) + pc + 4;
}
static char *regs[]={"r0","r1","r2","r3","r4","r5","r6","r7","r8","r9","r10","r11","r12","r13","r14","r15","pc"};
static RAnalValue *anal_fill_ai_rg(RAnal *anal, int idx) {
RAnalValue *ret = r_anal_value_new ();
ret->reg = r_reg_get (anal->reg, regs[idx], R_REG_TYPE_GPR);
return ret;
}
static RAnalValue *anal_fill_im(RAnal *anal, st32 v) {
RAnalValue *ret = r_anal_value_new ();
ret->imm = v;
return ret;
}
/* Implements @(disp,Rn) , size=1 for .b, 2 for .w, 4 for .l */
static RAnalValue *anal_fill_reg_disp_mem(RAnal *anal, int reg, st64 delta, st64 size) {
RAnalValue *ret = anal_fill_ai_rg (anal, reg);
ret->memref = size;
ret->delta = delta*size;
return ret;
}
/* Rn */
static RAnalValue *anal_fill_reg_ref(RAnal *anal, int reg, st64 size){
RAnalValue *ret = anal_fill_ai_rg (anal, reg);
ret->memref = size;
return ret;
}
/* @(R0,Rx) references for all sizes */
static RAnalValue *anal_fill_r0_reg_ref(RAnal *anal, int reg, st64 size){
RAnalValue *ret = anal_fill_ai_rg (anal, 0);
ret->regdelta = r_reg_get (anal->reg, regs[reg], R_REG_TYPE_GPR);
ret->memref = size;
return ret;
}
// @(disp,PC) for size=2(.w), size=4(.l). disp is 0-extended
static RAnalValue *anal_pcrel_disp_mov(RAnal* anal, RAnalOp* op, ut8 disp, int size){
RAnalValue *ret = r_anal_value_new ();
if (size==2) {
ret->base = op->addr+4;
ret->delta = disp<<1;
} else {
ret->base = (op->addr+4) & ~0x03;
ret->delta = disp<<2;
}
return ret;
}
//= PC+4+R<reg>
static RAnalValue *anal_regrel_jump(RAnal* anal, RAnalOp* op, ut8 reg){
RAnalValue *ret = r_anal_value_new ();
ret->reg = r_reg_get (anal->reg, regs[reg], R_REG_TYPE_GPR);
ret->base = op->addr+4;
return ret;
}
/* 16 decoder routines, based on 1st nibble value */
static int first_nibble_is_0(RAnal* anal, RAnalOp* op, ut16 code){
if(IS_BSRF(code)) {
/* Call 'far' subroutine Rn+PC+4 */
op->type = R_ANAL_OP_TYPE_UCALL;
op->delay = 1;
op->dst = anal_regrel_jump (anal, op, GET_TARGET_REG(code));
} else if (IS_BRAF(code)) {
/* Unconditional branch to Rn+PC+4, no delay slot */
op->type = R_ANAL_OP_TYPE_UJMP;
op->dst = anal_regrel_jump (anal, op, GET_TARGET_REG(code));
op->eob = true;
} else if( IS_RTS(code) ) {
/* Ret from subroutine. Returns to pr */
//TODO Convert into jump pr?
op->type = R_ANAL_OP_TYPE_RET;
op->delay = 1;
op->eob = true;
} else if (IS_RTE(code)) {
//TODO Convert into jmp spc? Indicate ssr->sr as well?
op->type = R_ANAL_OP_TYPE_RET;
op->delay = 1;
op->eob = true;
} else if (IS_MOVB_REG_TO_R0REL(code)) { //0000nnnnmmmm0100 mov.b <REG_M>,@(R0,<REG_N>)
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_r0_reg_ref (anal, GET_TARGET_REG(code), BYTE_SIZE);
} else if (IS_MOVW_REG_TO_R0REL(code)) {
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_r0_reg_ref (anal, GET_TARGET_REG(code), WORD_SIZE);
} else if (IS_MOVL_REG_TO_R0REL(code)) {
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_r0_reg_ref(anal, GET_TARGET_REG(code), LONG_SIZE);
} else if (IS_MOVB_R0REL_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), BYTE_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVW_R0REL_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), WORD_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVL_R0REL_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_r0_reg_ref (anal, GET_SOURCE_REG(code), LONG_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_NOP(code)) {
op->type = R_ANAL_OP_TYPE_NOP;
} else if (IS_CLRT(code)) {
op->type = R_ANAL_OP_TYPE_UNK; //TODO : implement flag
} else if (IS_SETT(code)) {
op->type = R_ANAL_OP_TYPE_UNK;
} else if (IS_CLRMAC(code)) {
op->type = R_ANAL_OP_TYPE_UNK; //TODO : type_mov ?
} else if (IS_DIV0U(code)) {
op->type = R_ANAL_OP_TYPE_DIV;
} else if (IS_MOVT(code)) {
op->type = R_ANAL_OP_TYPE_MOV;
//op->src[0] = //TODO: figure out how to get T flag from sr reg
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MULL(code)) {
op->type = R_ANAL_OP_TYPE_MUL;
op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
//op->dst = //TODO: figure out how to set MACL + MACH
} else if (IS_SLEEP(code)) {
op->type = R_ANAL_OP_TYPE_UNK;
} else if (IS_STSMAC(code)) { //0000nnnn0000101_ sts MAC*,<REG_N>
op->type = R_ANAL_OP_TYPE_MOV;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_STCSR1(code)) { //0000nnnn00010010 stc {sr,gbr,vbr,ssr},<REG_N>
op->type = R_ANAL_OP_TYPE_MOV;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo: plug in src
} else if (IS_STSPR(code)) { //0000nnnn00101010 sts PR,<REG_N>
op->type = R_ANAL_OP_TYPE_MOV;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo: plug in src
}
//TODO Check missing insns, especially STC might be interesting
return op->size;
}
//nibble=1; 0001nnnnmmmmi4*4 mov.l <REG_M>,@(<disp>,<REG_N>)
static int movl_reg_rdisp(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_reg_disp_mem (anal, GET_TARGET_REG(code), code&0x0F, LONG_SIZE);
return op->size;
}
static int first_nibble_is_2(RAnal* anal, RAnalOp* op, ut16 code){
if (IS_MOVB_REG_TO_REGREF(code)) { // 0010nnnnmmmm0000 mov.b <REG_M>,@<REG_N>
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), BYTE_SIZE);
} else if (IS_MOVW_REG_TO_REGREF(code)) {
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), WORD_SIZE);
} else if (IS_MOVL_REG_TO_REGREF(code)) {
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_reg_ref (anal, GET_TARGET_REG(code), LONG_SIZE);
} else if (IS_AND_REGS(code)) {
op->type = R_ANAL_OP_TYPE_AND;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_XOR_REGS(code)) {
op->type = R_ANAL_OP_TYPE_XOR;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_OR_REGS(code)) {
op->type = R_ANAL_OP_TYPE_OR;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_PUSHB(code) || IS_PUSHW(code) || IS_PUSHL(code)) {
op->type = R_ANAL_OP_TYPE_PUSH;
//TODO Handle 'pushes' (mov Rm,@-Rn)
} else if (IS_TSTRR(code)) {
op->type = R_ANAL_OP_TYPE_ACMP;
//TODO: handle tst reg,reg
} else if (IS_CMPSTR(code)) { //0010nnnnmmmm1100 cmp/str <REG_M>,<REG_N>
op->type = R_ANAL_OP_TYPE_ACMP; //maybe not?
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo: handle cmp/str byte-per-byte cmp?
} else if (IS_XTRCT(code)) { //0010nnnnmmmm1101 xtrct <REG_M>,<REG_N>
op->type = R_ANAL_OP_TYPE_MOV;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo: add details ?
} else if (IS_DIV0S(code)) {
op->type = R_ANAL_OP_TYPE_DIV;
//todo: add details?
} else if (IS_MULUW(code) || IS_MULSW(code)) { //0010nnnnmmmm111_ mul{s,u}.w <REG_M>,<REG_N>
op->type = R_ANAL_OP_TYPE_MUL;
op->src[0] = anal_fill_ai_rg(anal,GET_SOURCE_REG(code));
op->src[1] = anal_fill_ai_rg(anal,GET_TARGET_REG(code));
//todo: dest=MACL
}
return op->size;
}
static int first_nibble_is_3(RAnal* anal, RAnalOp* op, ut16 code){
//TODO Handle carry/overflow , CMP/xx?
if( IS_ADD(code) || IS_ADDC(code) || IS_ADDV(code) ) {
op->type = R_ANAL_OP_TYPE_ADD;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if ( IS_SUB(code) || IS_SUBC(code) || IS_SUBV(code)) {
op->type = R_ANAL_OP_TYPE_SUB;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_CMPEQ(code) || IS_CMPGE(code) || IS_CMPGT(code) ||
IS_CMPHI(code) || IS_CMPHS(code)) {
//TODO : finish implementing
op->type = R_ANAL_OP_TYPE_CMP;
op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
} else if (IS_DIV1(code)) {
op->type = R_ANAL_OP_TYPE_DIV;
op->src[0] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
//todo: dest ?
} else if (IS_DMULU(code) || IS_DMULS(code)) {
op->type = R_ANAL_OP_TYPE_MUL;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->src[1] = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo: dest=MACL,MACH
}
return op->size;
}
static int first_nibble_is_4(RAnal* anal, RAnalOp* op, ut16 code){
switch (code & 0xF0FF) {
//todo: implement
case 0x4020: //shal
op->type = R_ANAL_OP_TYPE_SAL;
break;
case 0x4021: //shar
op->type = R_ANAL_OP_TYPE_SAR;
break;
case 0x4000: //shll
case 0x4008: //shll2
case 0x4018: //shll8
case 0x4028: //shll16
op->type = R_ANAL_OP_TYPE_SHL;
break;
case 0x4001: //shlr
case 0x4009: //shlr2
case 0x4019: //shlr8
case 0x4029: //shlr16
op->type = R_ANAL_OP_TYPE_SHR;
break;
default:
break;
}
if (IS_JSR(code)) {
op->type = R_ANAL_OP_TYPE_UCALL; //call to reg
op->delay = 1;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if ( IS_JMP(code) ) {
op->type = R_ANAL_OP_TYPE_UJMP; //jmp to reg
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->delay = 1;
op->eob = true;
} else if (IS_CMPPL(code) || IS_CMPPZ(code)) {
op->type = R_ANAL_OP_TYPE_CMP;
//todo: implement
} else if (IS_LDCLSR1(code) || IS_LDSLMAC(code) || IS_LDSLPR(code)) {
op->type = R_ANAL_OP_TYPE_POP;
//todo: implement
} else if (IS_LDCSR1(code) || IS_LDSMAC(code) || IS_LDSPR(code)) {
op->type = R_ANAL_OP_TYPE_MOV;
//todo: implement
} else if (IS_ROT(code)) {
op->type = (code&1)? R_ANAL_OP_TYPE_ROR:R_ANAL_OP_TYPE_ROL;
//todo: implement rot* vs rotc*
} else if (IS_STCLSR1(code) || IS_STSLMAC(code) || IS_STSLPR(code)) {
op->type = R_ANAL_OP_TYPE_PUSH;
//todo: implement st*.l *,@-Rn
} else if (IS_TASB(code)) {
op->type = R_ANAL_OP_TYPE_UNK;
//todo: implement
} else if (IS_DT(code)) {
op->type = R_ANAL_OP_TYPE_UNK;
//todo: implement
}
return op->size;
}
//nibble=5; 0101nnnnmmmmi4*4 mov.l @(<disp>,<REG_M>),<REG_N>
static int movl_rdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, LONG_SIZE);
return op->size;
}
static int first_nibble_is_6(RAnal* anal, RAnalOp* op, ut16 code){
if (IS_MOV_REGS(code)) {
op->type = R_ANAL_OP_TYPE_MOV;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVB_REGREF_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), BYTE_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVW_REGREF_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), WORD_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVL_REGREF_TO_REG(code)) {
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_fill_reg_ref (anal, GET_SOURCE_REG(code), LONG_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_EXT(code)) {
//ext{s,u}.{b,w} instructs. todo : more detail ?
op->type = R_ANAL_OP_TYPE_MOV;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_MOVB_POP(code) || IS_MOVW_POP(code) || IS_MOVL_POP(code)) {
/* 0110nnnnmmmm0100 mov.b @<REG_M>+,<REG_N>*/
/* 0110nnnnmmmm0101 mov.w @<REG_M>+,<REG_N>*/
/* 0110nnnnmmmm0110 mov.l @<REG_M>+,<REG_N>*/
op->type = R_ANAL_OP_TYPE_POP;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//todo : op->src for pop = ?
} else if (IS_NEG(code)) {
//todo: neg and negc details
op->type = R_ANAL_OP_TYPE_UNK;
/* 0110nnnnmmmm1010 negc*/
/* 0110nnnnmmmm1010 neg */
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_NOT(code)) {
//todo : details?
op->type = R_ANAL_OP_TYPE_NOT;
op->src[0] = anal_fill_ai_rg (anal, GET_SOURCE_REG(code));
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
} else if (IS_SWAP(code)) {
/* 0110nnnnmmmm1000 swap.b <REG_M>,<REG_N>*/
/* 0110nnnnmmmm1001 swap.w <REG_M>,<REG_N>*/
op->type = R_ANAL_OP_TYPE_MOV;
//todo : details
}
return op->size;
}
//nibble=7; 0111nnnni8*1.... add #<imm>,<REG_N>
static int add_imm(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_ADD;
op->src[0] = anal_fill_im (anal, (st8)(code&0xFF)); //Casting to (st8) forces sign-extension.
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
return op->size;
}
static int first_nibble_is_8(RAnal* anal, RAnalOp* op, ut16 code){
if (IS_BT_OR_BF(code)) {
op->type = R_ANAL_OP_TYPE_CJMP; //Jump if true or jump if false insns
op->jump = disarm_8bit_offset (op->addr, GET_BTF_OFFSET(code));
op->fail = op->addr + 2 ;
op->eob = true;
if (IS_BTS(code) || IS_BFS(code))
op->delay = 1; //Only /S versions have a delay slot
} else if (IS_MOVB_REGDISP_R0(code)) {
// 10000100mmmmi4*1 mov.b @(<disp>,<REG_M>),R0
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, 0);
op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, BYTE_SIZE);
} else if (IS_MOVW_REGDISP_R0(code)) {
// 10000101mmmmi4*2 mov.w @(<disp>,<REG_M>),R0
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, 0);
op->src[0] = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, WORD_SIZE);
} else if (IS_CMPIMM(code)) {
op->type = R_ANAL_OP_TYPE_CMP;
//todo : finish implementing
} else if (IS_MOVB_R0_REGDISP(code)) {
/* 10000000mmmmi4*1 mov.b R0,@(<disp>,<REG_M>)*/
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, 0);
op->dst = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, BYTE_SIZE);
} else if (IS_MOVW_R0_REGDISP(code)) {
// 10000001mmmmi4*2 mov.w R0,@(<disp>,<REG_M>))
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, 0);
op->dst = anal_fill_reg_disp_mem (anal, GET_SOURCE_REG(code), code&0x0F, WORD_SIZE);
}
return op->size;
}
//nibble=9; 1001nnnni8p2.... mov.w @(<disp>,PC),<REG_N>
static int movw_pcdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
//op->src[0] = anal_fill_reg_disp_mem(anal,PC_IDX,code&0xFF,WORD_SIZE); //XXX trash in 2 commits
op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, WORD_SIZE);
return op->size;
}
//nibble=A; 1010i12......... bra <bdisp12>
static int bra(RAnal* anal, RAnalOp* op, ut16 code){
/* Unconditional branch, relative to PC */
op->type = R_ANAL_OP_TYPE_JMP;
op->delay = 1;
op->jump = disarm_12bit_offset (op, GET_BRA_OFFSET(code));
op->eob = true;
return op->size;
}
//nibble=B; 1011i12......... bsr <bdisp12>
static int bsr(RAnal* anal, RAnalOp* op, ut16 code){
/* Subroutine call, relative to PC */
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = disarm_12bit_offset (op, GET_BRA_OFFSET(code));
op->delay = 1;
return op->size;
}
static int first_nibble_is_c(RAnal* anal, RAnalOp* op, ut16 code){
if (IS_TRAP(code)) {
op->type = R_ANAL_OP_TYPE_SWI;
op->val = (ut8)(code&0xFF);
} else if (IS_MOVA_PCREL_R0(code)) {
// 11000111i8p4.... mova @(<disp>,PC),R0
op->type = R_ANAL_OP_TYPE_LEA;
op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, LONG_SIZE); //this is wrong !
op->dst = anal_fill_ai_rg (anal, 0); //Always R0
} else if (IS_BINLOGIC_IMM_R0(code)) { // 110010__i8 (binop) #imm, R0
op->src[0] = anal_fill_im (anal, code&0xFF);
op->src[1] = anal_fill_ai_rg (anal, 0); //Always R0
op->dst = anal_fill_ai_rg (anal, 0); //Always R0 except tst #imm, R0
switch (code & 0xFF00) {
case 0xC800: //tst
//TODO : get correct op->dst ! (T flag)
op->type = R_ANAL_OP_TYPE_ACMP;
break;
case 0xC900: //and
op->type = R_ANAL_OP_TYPE_AND;
break;
case 0xCA00: //xor
op->type = R_ANAL_OP_TYPE_XOR;
break;
case 0xCB00: //or
op->type = R_ANAL_OP_TYPE_OR;
break;
}
} else if (IS_BINLOGIC_IMM_GBR(code)) { //110011__i8 (binop).b #imm, @(R0,GBR)
op->src[0] = anal_fill_im (anal, code&0xFF);
switch (code & 0xFF00) {
case 0xCC00: //tst
//TODO : get correct op->dst ! (T flag)
op->type = R_ANAL_OP_TYPE_ACMP;
break;
case 0xCD00: //and
op->type = R_ANAL_OP_TYPE_AND;
break;
case 0xCE00: //xor
op->type = R_ANAL_OP_TYPE_XOR;
break;
case 0xCF00: //or
op->type = R_ANAL_OP_TYPE_OR;
break;
}
//TODO : implement @(R0,GBR) dest and src[1]
} else if (IS_MOVB_R0_GBRREF(code)) { //11000000i8*1.... mov.b R0,@(<disp>,GBR)
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) dest
} else if (IS_MOVW_R0_GBRREF(code)) { //11000001i8*2.... mov.w R0,@(<disp>,GBR)
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) dest
} else if (IS_MOVL_R0_GBRREF(code)) { //11000010i8*4.... mov.l R0,@(<disp>,GBR)
op->type = R_ANAL_OP_TYPE_STORE;
op->src[0] = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) dest
} else if (IS_MOVB_GBRREF_R0(code)) { //11000100i8*1.... mov.b @(<disp>,GBR),R0
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) src
} else if (IS_MOVW_GBRREF_R0(code)) { //11000101i8*2.... mov.w @(<disp>,GBR),R0
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) src
} else if (IS_MOVL_GBRREF_R0(code)) { //11000110i8*4.... mov.l @(<disp>,GBR),R0
op->type = R_ANAL_OP_TYPE_LOAD;
op->dst = anal_fill_ai_rg (anal, 0);
//todo: implement @(disp,GBR) src
}
return op->size;
}
//nibble=d; 1101nnnni8 : mov.l @(<disp>,PC), Rn
static int movl_pcdisp_reg(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_LOAD;
op->src[0] = anal_pcrel_disp_mov (anal, op, code&0xFF, LONG_SIZE);
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
return op->size;
}
//nibble=e; 1110nnnni8*1.... mov #<imm>,<REG_N>
static int mov_imm_reg(RAnal* anal, RAnalOp* op, ut16 code){
op->type = R_ANAL_OP_TYPE_MOV;
op->dst = anal_fill_ai_rg (anal, GET_TARGET_REG(code));
op->src[0] = anal_fill_im (anal, (st8)(code & 0xFF));
return op->size;
}
//nibble=f;
static int fpu_insn(RAnal* anal, RAnalOp* op, ut16 code){
//Not interested on FPU stuff for now
op->family = R_ANAL_OP_FAMILY_FPU;
return op->size;
}
/* Table of routines for further analysis based on 1st nibble */
static int (*first_nibble_decode[])(RAnal*,RAnalOp*,ut16) = {
first_nibble_is_0,
movl_reg_rdisp,
first_nibble_is_2,
first_nibble_is_3,
first_nibble_is_4,
movl_rdisp_reg,
first_nibble_is_6,
add_imm,
first_nibble_is_8,
movw_pcdisp_reg,
bra,
bsr,
first_nibble_is_c,
movl_pcdisp_reg,
mov_imm_reg,
fpu_insn
};
/* This is the basic operation analysis. Just initialize and jump to
* routines defined in first_nibble_decode table
*/
static int sh_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
ut8 op_MSB,op_LSB;
int ret;
if (!data)
return 0;
memset (op, '\0', sizeof (RAnalOp));
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->jump = op->fail = -1;
op->ptr = op->val = -1;
op->size = 2;
op_MSB = anal->big_endian? data[0]: data[1];
op_LSB = anal->big_endian? data[1]: data[0];
ret = first_nibble_decode[(op_MSB>>4) & 0x0F](anal, op, (ut16)(op_MSB<<8 | op_LSB));
return ret;
}
/* Set the profile register */
static int sh_set_reg_profile(RAnal* anal){
//TODO Add system ( ssr, spc ) + fpu regs
const char *p =
"=PC pc\n"
"=SP r15\n"
"=BP r14\n"
"gpr r0 .32 0 0\n"
"gpr r1 .32 4 0\n"
"gpr r2 .32 8 0\n"
"gpr r3 .32 12 0\n"
"gpr r4 .32 16 0\n"
"gpr r5 .32 20 0\n"
"gpr r6 .32 24 0\n"
"gpr r7 .32 28 0\n"
"gpr r8 .32 32 0\n"
"gpr r9 .32 36 0\n"
"gpr r10 .32 40 0\n"
"gpr r11 .32 44 0\n"
"gpr r12 .32 48 0\n"
"gpr r13 .32 52 0\n"
"gpr r14 .32 56 0\n"
"gpr r15 .32 60 0\n"
"gpr pc .32 64 0\n"
"gpr pr .32 68 0\n"
"gpr sr .32 72 0\n"
"gpr gbr .32 76 0\n"
"gpr mach .32 80 0\n"
"gpr macl .32 84 0\n";
return r_reg_set_profile_string(anal->reg, p);
}
static int archinfo(RAnal *anal, int q) {
return 2; /* :) */
}
RAnalPlugin r_anal_plugin_sh = {
.name = "sh",
.desc = "SH-4 code analysis plugin",
.license = "LGPL3",
.arch = "sh",
.archinfo = archinfo,
.bits = 32,
.op = &sh_op,
.set_reg_profile = &sh_set_reg_profile,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_sh,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_149_0 |
crossvul-cpp_data_good_2709_0 | /*
* Copyright (c) 1998-2007 The TCPDUMP project
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Reference documentation:
* http://www.cisco.com/c/en/us/support/docs/lan-switching/vtp/10558-21.html
* http://docstore.mik.ua/univercd/cc/td/doc/product/lan/trsrb/frames.htm
*
* Original code ode by Carles Kishimoto <carles.kishimoto@gmail.com>
*/
/* \summary: Cisco VLAN Trunking Protocol (VTP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#define VTP_HEADER_LEN 36
#define VTP_DOMAIN_NAME_LEN 32
#define VTP_MD5_DIGEST_LEN 16
#define VTP_UPDATE_TIMESTAMP_LEN 12
#define VTP_VLAN_INFO_FIXED_PART_LEN 12 /* length of VLAN info before VLAN name */
#define VTP_SUMMARY_ADV 0x01
#define VTP_SUBSET_ADV 0x02
#define VTP_ADV_REQUEST 0x03
#define VTP_JOIN_MESSAGE 0x04
struct vtp_vlan_ {
uint8_t len;
uint8_t status;
uint8_t type;
uint8_t name_len;
uint16_t vlanid;
uint16_t mtu;
uint32_t index;
};
static const struct tok vtp_message_type_values[] = {
{ VTP_SUMMARY_ADV, "Summary advertisement"},
{ VTP_SUBSET_ADV, "Subset advertisement"},
{ VTP_ADV_REQUEST, "Advertisement request"},
{ VTP_JOIN_MESSAGE, "Join message"},
{ 0, NULL }
};
static const struct tok vtp_header_values[] = {
{ 0x01, "Followers"}, /* On Summary advertisement, 3rd byte is Followers */
{ 0x02, "Seq number"}, /* On Subset advertisement, 3rd byte is Sequence number */
{ 0x03, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0x04, "Rsvd"}, /* On Adver. requests 3rd byte is Rsvd */
{ 0, NULL }
};
static const struct tok vtp_vlan_type_values[] = {
{ 0x01, "Ethernet"},
{ 0x02, "FDDI"},
{ 0x03, "TrCRF"},
{ 0x04, "FDDI-net"},
{ 0x05, "TrBRF"},
{ 0, NULL }
};
static const struct tok vtp_vlan_status[] = {
{ 0x00, "Operational"},
{ 0x01, "Suspended"},
{ 0, NULL }
};
#define VTP_VLAN_SOURCE_ROUTING_RING_NUMBER 0x01
#define VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER 0x02
#define VTP_VLAN_STP_TYPE 0x03
#define VTP_VLAN_PARENT_VLAN 0x04
#define VTP_VLAN_TRANS_BRIDGED_VLAN 0x05
#define VTP_VLAN_PRUNING 0x06
#define VTP_VLAN_BRIDGE_TYPE 0x07
#define VTP_VLAN_ARP_HOP_COUNT 0x08
#define VTP_VLAN_STE_HOP_COUNT 0x09
#define VTP_VLAN_BACKUP_CRF_MODE 0x0A
static const struct tok vtp_vlan_tlv_values[] = {
{ VTP_VLAN_SOURCE_ROUTING_RING_NUMBER, "Source-Routing Ring Number TLV"},
{ VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER, "Source-Routing Bridge Number TLV"},
{ VTP_VLAN_STP_TYPE, "STP type TLV"},
{ VTP_VLAN_PARENT_VLAN, "Parent VLAN TLV"},
{ VTP_VLAN_TRANS_BRIDGED_VLAN, "Translationally bridged VLANs TLV"},
{ VTP_VLAN_PRUNING, "Pruning TLV"},
{ VTP_VLAN_BRIDGE_TYPE, "Bridge Type TLV"},
{ VTP_VLAN_ARP_HOP_COUNT, "Max ARP Hop Count TLV"},
{ VTP_VLAN_STE_HOP_COUNT, "Max STE Hop Count TLV"},
{ VTP_VLAN_BACKUP_CRF_MODE, "Backup CRF Mode TLV"},
{ 0, NULL }
};
static const struct tok vtp_stp_type_values[] = {
{ 1, "SRT"},
{ 2, "SRB"},
{ 3, "Auto"},
{ 0, NULL }
};
void
vtp_print (netdissect_options *ndo,
const u_char *pptr, u_int length)
{
int type, len, tlv_len, tlv_value, mgmtd_len;
const u_char *tptr;
const struct vtp_vlan_ *vtp_vlan;
if (length < VTP_HEADER_LEN)
goto trunc;
tptr = pptr;
ND_TCHECK2(*tptr, VTP_HEADER_LEN);
type = *(tptr+1);
ND_PRINT((ndo, "VTPv%u, Message %s (0x%02x), length %u",
*tptr,
tok2str(vtp_message_type_values,"Unknown message type", type),
type,
length));
/* In non-verbose mode, just print version and message type */
if (ndo->ndo_vflag < 1) {
return;
}
/* verbose mode print all fields */
ND_PRINT((ndo, "\n\tDomain name: "));
mgmtd_len = *(tptr + 3);
if (mgmtd_len < 1 || mgmtd_len > 32) {
ND_PRINT((ndo, " [invalid MgmtD Len %d]", mgmtd_len));
return;
}
fn_printzp(ndo, tptr + 4, mgmtd_len, NULL);
ND_PRINT((ndo, ", %s: %u",
tok2str(vtp_header_values, "Unknown", type),
*(tptr+2)));
tptr += VTP_HEADER_LEN;
switch (type) {
case VTP_SUMMARY_ADV:
/*
* SUMMARY ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Followers | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Updater Identity IP address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Update Timestamp (12 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MD5 digest (16 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 8);
ND_PRINT((ndo, "\n\t Config Rev %x, Updater %s",
EXTRACT_32BITS(tptr),
ipaddr_string(ndo, tptr+4)));
tptr += 8;
ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN);
ND_PRINT((ndo, ", Timestamp 0x%08x 0x%08x 0x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8)));
tptr += VTP_UPDATE_TIMESTAMP_LEN;
ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN);
ND_PRINT((ndo, ", MD5 digest: %08x%08x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
EXTRACT_32BITS(tptr + 12)));
tptr += VTP_MD5_DIGEST_LEN;
break;
case VTP_SUBSET_ADV:
/*
* SUBSET ADVERTISEMENT
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Seq number | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Configuration revision number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field 1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ................ |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN info field N |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK_32BITS(tptr);
ND_PRINT((ndo, ", Config Rev %x", EXTRACT_32BITS(tptr)));
/*
* VLAN INFORMATION
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | V info len | Status | VLAN type | VLAN name len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ISL vlan id | MTU size |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | 802.10 index (SAID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | VLAN name |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
tptr += 4;
while (tptr < (pptr+length)) {
ND_TCHECK_8BITS(tptr);
len = *tptr;
if (len == 0)
break;
ND_TCHECK2(*tptr, len);
vtp_vlan = (const struct vtp_vlan_*)tptr;
if (len < VTP_VLAN_INFO_FIXED_PART_LEN)
goto trunc;
ND_TCHECK(*vtp_vlan);
ND_PRINT((ndo, "\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name ",
tok2str(vtp_vlan_status,"Unknown",vtp_vlan->status),
tok2str(vtp_vlan_type_values,"Unknown",vtp_vlan->type),
EXTRACT_16BITS(&vtp_vlan->vlanid),
EXTRACT_16BITS(&vtp_vlan->mtu),
EXTRACT_32BITS(&vtp_vlan->index)));
len -= VTP_VLAN_INFO_FIXED_PART_LEN;
tptr += VTP_VLAN_INFO_FIXED_PART_LEN;
if (len < 4*((vtp_vlan->name_len + 3)/4))
goto trunc;
ND_TCHECK2(*tptr, vtp_vlan->name_len);
fn_printzp(ndo, tptr, vtp_vlan->name_len, NULL);
/*
* Vlan names are aligned to 32-bit boundaries.
*/
len -= 4*((vtp_vlan->name_len + 3)/4);
tptr += 4*((vtp_vlan->name_len + 3)/4);
/* TLV information follows */
while (len > 0) {
/*
* Cisco specs say 2 bytes for type + 2 bytes for length;
* see http://docstore.mik.ua/univercd/cc/td/doc/product/lan/trsrb/frames.htm
* However, actual packets on the wire appear to use 1
* byte for the type and 1 byte for the length, so that's
* what we do.
*/
if (len < 2)
goto trunc;
ND_TCHECK2(*tptr, 2);
type = *tptr;
tlv_len = *(tptr+1);
ND_PRINT((ndo, "\n\t\t%s (0x%04x) TLV",
tok2str(vtp_vlan_tlv_values, "Unknown", type),
type));
if (len < tlv_len * 2 + 2) {
ND_PRINT((ndo, " (TLV goes past the end of the packet)"));
return;
}
ND_TCHECK2(*tptr, tlv_len * 2 +2);
/*
* We assume the value is a 2-byte integer; the length is
* in units of 16-bit words.
*/
if (tlv_len != 1) {
ND_PRINT((ndo, " (invalid TLV length %u != 1)", tlv_len));
return;
} else {
tlv_value = EXTRACT_16BITS(tptr+2);
switch (type) {
case VTP_VLAN_STE_HOP_COUNT:
ND_PRINT((ndo, ", %u", tlv_value));
break;
case VTP_VLAN_PRUNING:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Enabled" : "Disabled",
tlv_value));
break;
case VTP_VLAN_STP_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tok2str(vtp_stp_type_values, "Unknown", tlv_value),
tlv_value));
break;
case VTP_VLAN_BRIDGE_TYPE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "SRB" : "SRT",
tlv_value));
break;
case VTP_VLAN_BACKUP_CRF_MODE:
ND_PRINT((ndo, ", %s (%u)",
tlv_value == 1 ? "Backup" : "Not backup",
tlv_value));
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER:
case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER:
case VTP_VLAN_PARENT_VLAN:
case VTP_VLAN_TRANS_BRIDGED_VLAN:
case VTP_VLAN_ARP_HOP_COUNT:
default:
print_unknown_data(ndo, tptr, "\n\t\t ", 2 + tlv_len*2);
break;
}
}
len -= 2 + tlv_len*2;
tptr += 2 + tlv_len*2;
}
}
break;
case VTP_ADV_REQUEST:
/*
* ADVERTISEMENT REQUEST
*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version | Code | Reserved | MgmtD Len |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Management Domain Name (zero-padded to 32 bytes) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Start value |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*/
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\tStart value: %u", EXTRACT_32BITS(tptr)));
break;
case VTP_JOIN_MESSAGE:
/* FIXME - Could not find message format */
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|vtp]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2709_0 |
crossvul-cpp_data_bad_5299_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-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 "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/channel.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/enhance.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/log.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/module.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/profile.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/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;
} LayerInfo;
/*
Forward declarations.
*/
static MagickBooleanType
WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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";
}
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->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace)
return(MagickTrue);
option=GetImageOption(image_info,"psd:alpha-unblend");
if (IsStringFalse(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 Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
register ssize_t
i;
gamma=QuantumScale*GetPixelAlpha(image, q);
if (gamma != 0.0 && gamma != 1.0)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
if (channel != AlphaPixelChannel)
q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma);
}
}
q+=GetPixelChannels(image);
}
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 CorrectPSDOpacity(LayerInfo *layer_info,
ExceptionInfo *exception)
{
MagickBooleanType
status;
ssize_t
y;
if (layer_info->opacity == OpaqueAlpha)
return(MagickTrue);
layer_info->image->alpha_trait=BlendPixelTrait;
status=MagickTrue;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(layer_info->image,layer_info->image,layer_info->image->rows,1)
#endif
for (y=0; y < (ssize_t) layer_info->image->rows; y++)
{
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetAuthenticPixels(layer_info->image,0,y,layer_info->image->columns,1,
exception);
if (q == (Quantum *)NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) layer_info->image->columns; x++)
{
SetPixelAlpha(layer_info->image,(Quantum) (QuantumScale*(GetPixelAlpha(
layer_info->image,q))*layer_info->opacity),q);
q+=GetPixelChannels(layer_info->image);
}
if (SyncAuthenticPixels(layer_info->image,exception) == MagickFalse)
status=MagickFalse;
}
return(status);
}
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++)
{
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;
}
}
CheckNumberCompactPixels;
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);
}
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);
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 MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception)
{
ChannelType
channel_mask;
MagickBooleanType
status;
channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~
AlphaChannel));
status=NegateImage(image,MagickFalse,exception);
(void) SetImageChannelMask(image,channel_mask);
return(status);
}
static void ParseImageResourceBlocks(Image *image,
const unsigned char *blocks,size_t length,
MagickBooleanType *has_merged_image,ExceptionInfo *exception)
{
const unsigned char
*p;
StringInfo
*profile;
unsigned int
count,
long_sans;
unsigned short
id,
short_sans;
if (length < 16)
return;
profile=BlobToStringInfo((const unsigned char *) NULL,length);
SetStringInfoDatum(profile,blocks);
(void) SetImageProfile(image,"8bim",profile,exception);
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)
return;
switch (id)
{
case 0x03ed:
{
char
value[MagickPathExtent];
unsigned short
resolution;
/*
Resolution info.
*/
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.x=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.x);
(void) SetImageProperty(image,"tiff:XResolution",value,exception);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&short_sans);
p=PushShortPixel(MSBEndian,p,&resolution);
image->resolution.y=(double) resolution;
(void) FormatLocaleString(value,MagickPathExtent,"%g",image->resolution.y);
(void) SetImageProperty(image,"tiff:YResolution",value,exception);
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,Quantum *q,
ExceptionInfo *exception)
{
if (image->storage_class == PseudoClass)
{
if (packet_size == 1)
SetPixelIndex(image,ScaleQuantumToChar(pixel),q);
else
SetPixelIndex(image,ScaleQuantumToShort(pixel),q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t)
ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q);
return;
}
switch (type)
{
case -1:
{
SetPixelAlpha(image, pixel,q);
break;
}
case -2:
case 0:
{
SetPixelRed(image,pixel,q);
if (channels == 1 || type == -2)
SetPixelGray(image,pixel,q);
break;
}
case 1:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelGreen(image,pixel,q);
break;
}
case 2:
{
if (image->storage_class == PseudoClass)
SetPixelAlpha(image,pixel,q);
else
SetPixelBlue(image,pixel,q);
break;
}
case 3:
{
if (image->colorspace == CMYKColorspace)
SetPixelBlack(image,pixel,q);
else
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
break;
}
case 4:
{
if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) &&
(channels > 3))
break;
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,pixel,q);
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 Quantum
*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 == (Quantum *) NULL)
return MagickFalse;
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,exception);
q+=GetPixelChannels(image);
}
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 : 255,q,exception);
q+=GetPixelChannels(image);
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 *ReadPSDRLEOffsets(Image *image,
const PSDInfo *psd_info,const size_t size)
{
MagickOffsetType
*offsets;
ssize_t
y;
offsets=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*offsets));
if(offsets != (MagickOffsetType *) NULL)
{
for (y=0; y < (ssize_t) size; y++)
{
if (psd_info->version == 1)
offsets[y]=(MagickOffsetType) ReadBlobShort(image);
else
offsets[y]=(MagickOffsetType) ReadBlobLong(image);
}
}
return offsets;
}
static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info,
const ssize_t type,MagickOffsetType *offsets,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 < offsets[y])
length=(size_t) offsets[y];
if (length > row_size + 256) // arbitrary number
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowBinaryException(ResourceLimitError,"InvalidLength",
image->filename);
}
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) offsets[y],compact_pixels);
if (count != (ssize_t) offsets[y])
break;
count=DecodePSDPixels((size_t) offsets[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(z_stream));
stream.data_type=Z_BINARY;
(void) ReadBlob(image,compact_size,compact_pixels);
stream.next_in=(Bytef *)compact_pixels;
stream.avail_in=(unsigned int) compact_size;
stream.next_out=(Bytef *)pixels;
stream.avail_out=(unsigned int) 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 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)
{
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
if (layer_info->channel_info[channel].type != -2 ||
(layer_info->mask.flags > 3) || (layer_info->mask.flags & 0x02))
{
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);
SetImageType(mask,GrayscaleType,exception);
channel_image=mask;
}
offset=TellBlob(channel_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
*offsets;
offsets=ReadPSDRLEOffsets(channel_image,psd_info,channel_image->rows);
if (offsets == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,offsets,exception);
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
}
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
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
if (mask != (Image *) NULL)
{
if (status != MagickFalse)
{
PixelInfo
color;
layer_info->mask.image=CloneImage(image,image->columns,image->rows,
MagickTrue,exception);
layer_info->mask.image->alpha_trait=UndefinedPixelTrait;
GetPixelInfo(layer_info->mask.image,&color);
color.red=layer_info->mask.background == 0 ? 0 : QuantumRange;
SetImageColor(layer_info->mask.image,&color,exception);
(void) CompositeImage(layer_info->mask.image,mask,OverCompositeOp,
MagickTrue,layer_info->mask.page.x,layer_info->mask.page.y,
exception);
}
DestroyImage(mask);
}
return(status);
}
static MagickBooleanType ReadPSDLayer(Image *image,const PSDInfo *psd_info,
LayerInfo* layer_info,ExceptionInfo *exception)
{
char
message[MagickPathExtent];
MagickBooleanType
status;
PSDCompressionType
compression;
ssize_t
j;
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" setting up new layer image");
(void) SetImageBackgroundColor(layer_info->image,exception);
layer_info->image->compose=PSDBlendModeToCompositeOperator(
layer_info->blendkey);
if (layer_info->visible == MagickFalse)
layer_info->image->compose=NoCompositeOp;
if (psd_info->mode == CMYKMode)
SetImageColorspace(layer_info->image,CMYKColorspace,exception);
if ((psd_info->mode == BitmapMode) || (psd_info->mode == GrayscaleMode) ||
(psd_info->mode == DuotoneMode))
SetImageColorspace(layer_info->image,GRAYColorspace,exception);
/*
Set up some hidden attributes for folks that need them.
*/
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.x);
(void) SetImageArtifact(layer_info->image,"psd:layer.x",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",
(double) layer_info->page.y);
(void) SetImageArtifact(layer_info->image,"psd:layer.y",message);
(void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double)
layer_info->opacity);
(void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message);
(void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name,
exception);
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->alpha_trait=BlendPixelTrait;
status=ReadPSDChannel(layer_info->image,psd_info,layer_info,j,
compression,exception);
if (status == MagickFalse)
break;
}
if (status != MagickFalse)
status=CorrectPSDOpacity(layer_info,exception);
if ((status != MagickFalse) &&
(layer_info->image->colorspace == CMYKColorspace))
status=NegateCMYK(layer_info->image,exception);
if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL))
{
status=CompositeImage(layer_info->image,layer_info->mask.image,
CopyAlphaCompositeOp,MagickTrue,0,0,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->alpha_trait=BlendPixelTrait;
}
/*
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=(int) ReadBlobLong(image);
layer_info[i].page.x=(int) ReadBlobLong(image);
y=(int) ReadBlobLong(image);
x=(int) ReadBlobLong(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);
}
count=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=(int) ReadBlobLong(image);
layer_info[i].mask.page.x=(int) ReadBlobLong(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=(size_t) 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);
/*
Skip the rest of the variable data until we support it.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unsupported data: length=%.20g",(double)
((MagickOffsetType) (size-combined_length)));
if (DiscardBlobBytes(image,(MagickSizeType) (size-combined_length)) == MagickFalse)
{
layer_info=DestroyLayerInfo(layer_info,number_layers);
ThrowBinaryException(CorruptImageError,
"UnexpectedEndOfFile",image->filename);
}
}
}
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");
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 (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,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
*offsets;
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);
}
offsets=(MagickOffsetType *) NULL;
if (compression == RLE)
{
offsets=ReadPSDRLEOffsets(image,psd_info,image->rows*psd_info->channels);
if (offsets == (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,offsets+(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=NegateCMYK(image,exception);
if (status != MagickFalse)
status=CorrectPSDAlphaBlend(image_info,image,exception);
if (offsets != (MagickOffsetType *) NULL)
offsets=(MagickOffsetType *) RelinquishMagickMemory(offsets);
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 == 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 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,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if (SetImageBackgroundColor(image,exception) == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
if (psd_info.mode == LabMode)
SetImageColorspace(image,LabColorspace,exception);
if (psd_info.mode == CMYKMode)
{
SetImageColorspace(image,CMYKColorspace,exception);
image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) ||
(psd_info.mode == DuotoneMode))
{
status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536,
exception);
if (status == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image colormap allocated");
SetImageColorspace(image,GRAYColorspace,exception);
image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait :
UndefinedPixelTrait;
}
else
image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait :
UndefinedPixelTrait;
/*
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,exception) == 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->alpha_trait=UndefinedPixelTrait;
}
}
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) ||
(LocaleNCompare((char *) blocks,"8BIM",4) != 0))
{
blocks=(unsigned char *) RelinquishMagickMemory(blocks);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image,
exception);
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) && (GetImageListLength(image) > 1))
{
Image
*merged;
SetImageAlphaChannel(image,TransparentAlphaChannel,exception);
image->background_color.alpha=TransparentAlpha;
image->background_color.alpha_trait=BlendPixelTrait;
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=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(void) RegisterMagickInfo(entry);
entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap");
entry->decoder=(DecodeImageHandler *) ReadPSDImage;
entry->encoder=(EncodeImageHandler *) WritePSDImage;
entry->magick=(IsImageFormatHandler *) IsPSD;
entry->flags|=CoderSeekableStreamFlag;
(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,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
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 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 size_t PSDPackbitsEncodeImage(Image *image,const size_t length,
const unsigned char *pixels,unsigned char *compact_pixels,
ExceptionInfo *exception)
{
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 == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(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 void WritePackbitsLength(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
unsigned char *compact_pixels,const QuantumType quantum_type,
ExceptionInfo *exception)
{
QuantumInfo
*quantum_info;
register const Quantum
*p;
size_t
length,
packet_size;
ssize_t
y;
unsigned char
*pixels;
if (next_image->depth > 8)
next_image->depth=16;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) SetPSDOffset(psd_info,image,length);
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static void WriteOneChannel(const PSDInfo *psd_info,const ImageInfo *image_info,
Image *image,Image *next_image,unsigned char *compact_pixels,
const QuantumType quantum_type,const MagickBooleanType compression_flag,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
length,
packet_size;
unsigned char
*pixels;
(void) psd_info;
if ((compression_flag != MagickFalse) &&
(next_image->compression != RLECompression))
(void) WriteBlobMSBShort(image,0);
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
(void) packet_size;
quantum_info=AcquireQuantumInfo(image_info,image);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression != RLECompression)
(void) WriteBlob(image,length,pixels);
else
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
(void) WriteBlob(image,length,compact_pixels);
}
}
quantum_info=DestroyQuantumInfo(quantum_info);
}
static MagickBooleanType WriteImageChannels(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const MagickBooleanType separate,ExceptionInfo *exception)
{
size_t
channels,
packet_size;
unsigned char
*compact_pixels;
/*
Write uncompressed pixels as separate planes.
*/
channels=1;
packet_size=next_image->depth > 8UL ? 2UL : 1UL;
compact_pixels=(unsigned char *) NULL;
if (next_image->compression == RLECompression)
{
compact_pixels=(unsigned char *) AcquireQuantumMemory((2*channels*
next_image->columns)+1,packet_size*sizeof(*compact_pixels));
if (compact_pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
if (IsImageGray(next_image) != MagickFalse)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GrayQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GrayQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
if (next_image->storage_class == PseudoClass)
{
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,IndexQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
IndexQuantum,MagickTrue,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,0,1);
}
else
{
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
if (next_image->compression == RLECompression)
{
/*
Packbits compression.
*/
(void) WriteBlobMSBShort(image,1);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,RedQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,GreenQuantum,exception);
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlueQuantum,exception);
if (next_image->colorspace == CMYKColorspace)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,BlackQuantum,exception);
if (next_image->alpha_trait != UndefinedPixelTrait)
WritePackbitsLength(psd_info,image_info,image,next_image,
compact_pixels,AlphaQuantum,exception);
}
(void) SetImageProgress(image,SaveImagesTag,0,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
RedQuantum,MagickTrue,exception);
(void) SetImageProgress(image,SaveImagesTag,1,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
GreenQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,2,6);
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlueQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,3,6);
if (next_image->colorspace == CMYKColorspace)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
BlackQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,4,6);
if (next_image->alpha_trait != UndefinedPixelTrait)
WriteOneChannel(psd_info,image_info,image,next_image,compact_pixels,
AlphaQuantum,separate,exception);
(void) SetImageProgress(image,SaveImagesTag,5,6);
if (next_image->colorspace == CMYKColorspace)
(void) NegateCMYK(next_image,exception);
}
if (next_image->compression == RLECompression)
compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels);
return(MagickTrue);
}
static void WritePascalString(Image* inImage,const char *inString,int inPad)
{
size_t
length;
register ssize_t
i;
/*
Max length is 255.
*/
length=(strlen(inString) > 255UL ) ? 255UL : strlen(inString);
if (length == 0)
(void) WriteBlobByte(inImage,0);
else
{
(void) WriteBlobByte(inImage,(unsigned char) length);
(void) WriteBlob(inImage, length, (const unsigned char *) inString);
}
length++;
if ((length % inPad) == 0)
return;
for (i=0; i < (ssize_t) (inPad-(length % inPad)); i++)
(void) WriteBlobByte(inImage,0);
}
static void WriteResolutionResourceBlock(Image *image)
{
double
x_resolution,
y_resolution;
unsigned short
units;
if (image->units == PixelsPerCentimeterResolution)
{
x_resolution=2.54*65536.0*image->resolution.x+0.5;
y_resolution=2.54*65536.0*image->resolution.y+0.5;
units=2;
}
else
{
x_resolution=65536.0*image->resolution.x+0.5;
y_resolution=65536.0*image->resolution.y+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 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)
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
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;
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 == 0x000003ed) && (PSDQuantum(count) < (ssize_t) (length-12)))
{
(void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length-
(PSDQuantum(count)+12)-(q-datum));
SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12));
break;
}
p+=count;
if ((count & 0x01) != 0)
p++;
}
}
static MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
const char
*property;
const StringInfo
*icc_profile;
Image
*base_image,
*next_image;
MagickBooleanType
status;
PSDInfo
psd_info;
register ssize_t
i;
size_t
channel_size,
channelLength,
layer_count,
layer_info_size,
length,
num_channels,
packet_size,
rounded_layer_info_size;
StringInfo
*bim_profile;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
packet_size=(size_t) (image->depth > 8 ? 6 : 3);
if (image->alpha_trait != UndefinedPixelTrait)
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,exception) != MagickFalse)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
if ((image_info->type != TrueColorType) && (image_info->type !=
TrueColorAlphaType) && (image->storage_class == PseudoClass))
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL);
else
{
if (image->storage_class == PseudoClass)
(void) SetImageStorageClass(image,DirectClass,exception);
if (image->colorspace != CMYKColorspace)
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL);
else
num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL);
}
(void) WriteBlobMSBShort(image,(unsigned short) num_channels);
(void) WriteBlobMSBLong(image,(unsigned int) image->rows);
(void) WriteBlobMSBLong(image,(unsigned int) image->columns);
if (IsImageGray(image) != MagickFalse)
{
MagickBooleanType
monochrome;
/*
Write depth & mode.
*/
monochrome=IsImageMonochrome(image) && (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,exception);
(void) WriteBlobMSBShort(image,(unsigned short)
(image->storage_class == PseudoClass ? IndexedMode : RGBMode));
}
else
{
if (image->colorspace != CMYKColorspace)
(void) TransformImageColorspace(image,CMYKColorspace,exception);
(void) WriteBlobMSBShort(image,CMYKMode);
}
}
if ((IsImageGray(image) != 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);
}
layer_count=0;
layer_info_size=2;
base_image=GetNextImageInList(image);
if ((image->alpha_trait != UndefinedPixelTrait) && (base_image == (Image *) NULL))
base_image=image;
next_image=base_image;
while ( next_image != NULL )
{
packet_size=next_image->depth > 8 ? 2UL : 1UL;
if (IsImageGray(next_image) != MagickFalse)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->storage_class == PseudoClass)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL;
else
if (next_image->colorspace != CMYKColorspace)
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL;
else
num_channels=next_image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL;
channelLength=(size_t) (next_image->columns*next_image->rows*packet_size+2);
layer_info_size+=(size_t) (4*4+2+num_channels*6+(psd_info.version == 1 ? 8 :
16)+4*1+4+num_channels*channelLength);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
layer_info_size+=16;
else
{
size_t
layer_length;
layer_length=strlen(property);
layer_info_size+=8+layer_length+(4-(layer_length % 4));
}
layer_count++;
next_image=GetNextImageInList(next_image);
}
if (layer_count == 0)
(void) SetPSDSize(&psd_info,image,0);
else
{
CompressionType
compression;
(void) SetPSDSize(&psd_info,image,layer_info_size+
(psd_info.version == 1 ? 8 : 16));
if ((layer_info_size/2) != ((layer_info_size+1)/2))
rounded_layer_info_size=layer_info_size+1;
else
rounded_layer_info_size=layer_info_size;
(void) SetPSDSize(&psd_info,image,rounded_layer_info_size);
if (image->alpha_trait != UndefinedPixelTrait)
(void) WriteBlobMSBShort(image,-(unsigned short) layer_count);
else
(void) WriteBlobMSBShort(image,(unsigned short) layer_count);
layer_count=1;
compression=base_image->compression;
for (next_image=base_image; next_image != NULL; )
{
next_image->compression=NoCompression;
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.y);
(void) WriteBlobMSBLong(image,(unsigned int) next_image->page.x);
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+
next_image->rows));
(void) WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+
next_image->columns));
packet_size=next_image->depth > 8 ? 2UL : 1UL;
channel_size=(unsigned int) ((packet_size*next_image->rows*
next_image->columns)+2);
if ((IsImageGray(next_image) != MagickFalse) ||
(next_image->storage_class == PseudoClass))
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 2 : 1));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
if (next_image->colorspace != CMYKColorspace)
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait != UndefinedPixelTrait ? 4 : 3));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait != UndefinedPixelTrait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
else
{
(void) WriteBlobMSBShort(image,(unsigned short)
(next_image->alpha_trait ? 5 : 4));
(void) WriteBlobMSBShort(image,0);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,1);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,2);
(void) SetPSDSize(&psd_info,image,channel_size);
(void) WriteBlobMSBShort(image,3);
(void) SetPSDSize(&psd_info,image,channel_size);
if (next_image->alpha_trait)
{
(void) WriteBlobMSBShort(image,(unsigned short) -1);
(void) SetPSDSize(&psd_info,image,channel_size);
}
}
(void) WriteBlob(image,4,(const unsigned char *) "8BIM");
(void) WriteBlob(image,4,(const unsigned char *)
CompositeOperatorToPSDBlendMode(next_image->compose));
(void) WriteBlobByte(image,255); /* layer opacity */
(void) WriteBlobByte(image,0);
(void) WriteBlobByte(image,next_image->compose==NoCompositeOp ?
1 << 0x02 : 1); /* layer properties - visible, etc. */
(void) WriteBlobByte(image,0);
property=(const char *) GetImageProperty(next_image,"label",exception);
if (property == (const char *) NULL)
{
char
layer_name[MagickPathExtent];
(void) WriteBlobMSBLong(image,16);
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
(void) FormatLocaleString(layer_name,MagickPathExtent,"L%04ld",(long)
layer_count++);
WritePascalString(image,layer_name,4);
}
else
{
size_t
label_length;
label_length=strlen(property);
(void) WriteBlobMSBLong(image,(unsigned int) (label_length+(4-
(label_length % 4))+8));
(void) WriteBlobMSBLong(image,0);
(void) WriteBlobMSBLong(image,0);
WritePascalString(image,property,4);
}
next_image=GetNextImageInList(next_image);
}
/*
Now the image data!
*/
next_image=base_image;
while (next_image != NULL)
{
status=WriteImageChannels(&psd_info,image_info,image,next_image,
MagickTrue,exception);
next_image=GetNextImageInList(next_image);
}
(void) WriteBlobMSBLong(image,0); /* user mask data */
base_image->compression=compression;
}
/*
Write composite image.
*/
if (status != MagickFalse)
status=WriteImageChannels(&psd_info,image_info,image,image,MagickFalse,
exception);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5299_0 |
crossvul-cpp_data_good_5361_1 | /*-
* Copyright (c) 2003-2007 Tim Kientzle
* Copyright (c) 2008 Joerg Sonnenberger
* 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_read_support_format_mtree.c 201165 2009-12-29 05:52:13Z kientzle $");
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <stddef.h>
/* #include <stdint.h> */ /* See archive_platform.h */
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#ifdef HAVE_STRING_H
#include <string.h>
#endif
#include "archive.h"
#include "archive_entry.h"
#include "archive_private.h"
#include "archive_read_private.h"
#include "archive_string.h"
#include "archive_pack_dev.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_CLOEXEC
#define O_CLOEXEC 0
#endif
#define MTREE_HAS_DEVICE 0x0001
#define MTREE_HAS_FFLAGS 0x0002
#define MTREE_HAS_GID 0x0004
#define MTREE_HAS_GNAME 0x0008
#define MTREE_HAS_MTIME 0x0010
#define MTREE_HAS_NLINK 0x0020
#define MTREE_HAS_PERM 0x0040
#define MTREE_HAS_SIZE 0x0080
#define MTREE_HAS_TYPE 0x0100
#define MTREE_HAS_UID 0x0200
#define MTREE_HAS_UNAME 0x0400
#define MTREE_HAS_OPTIONAL 0x0800
#define MTREE_HAS_NOCHANGE 0x1000 /* FreeBSD specific */
struct mtree_option {
struct mtree_option *next;
char *value;
};
struct mtree_entry {
struct mtree_entry *next;
struct mtree_option *options;
char *name;
char full;
char used;
};
struct mtree {
struct archive_string line;
size_t buffsize;
char *buff;
int64_t offset;
int fd;
int archive_format;
const char *archive_format_name;
struct mtree_entry *entries;
struct mtree_entry *this_entry;
struct archive_string current_dir;
struct archive_string contents_name;
struct archive_entry_linkresolver *resolver;
int64_t cur_size;
char checkfs;
};
static int bid_keycmp(const char *, const char *, ssize_t);
static int cleanup(struct archive_read *);
static int detect_form(struct archive_read *, int *);
static int mtree_bid(struct archive_read *, int);
static int parse_file(struct archive_read *, struct archive_entry *,
struct mtree *, struct mtree_entry *, int *);
static void parse_escapes(char *, struct mtree_entry *);
static int parse_line(struct archive_read *, struct archive_entry *,
struct mtree *, struct mtree_entry *, int *);
static int parse_keyword(struct archive_read *, struct mtree *,
struct archive_entry *, struct mtree_option *, int *);
static int read_data(struct archive_read *a,
const void **buff, size_t *size, int64_t *offset);
static ssize_t readline(struct archive_read *, struct mtree *, char **, ssize_t);
static int skip(struct archive_read *a);
static int read_header(struct archive_read *,
struct archive_entry *);
static int64_t mtree_atol10(char **);
static int64_t mtree_atol8(char **);
static int64_t mtree_atol(char **);
/*
* There's no standard for TIME_T_MAX/TIME_T_MIN. So we compute them
* here. TODO: Move this to configure time, but be careful
* about cross-compile environments.
*/
static int64_t
get_time_t_max(void)
{
#if defined(TIME_T_MAX)
return TIME_T_MAX;
#else
/* ISO C allows time_t to be a floating-point type,
but POSIX requires an integer type. The following
should work on any system that follows the POSIX
conventions. */
if (((time_t)0) < ((time_t)-1)) {
/* Time_t is unsigned */
return (~(time_t)0);
} else {
/* Time_t is signed. */
/* Assume it's the same as int64_t or int32_t */
if (sizeof(time_t) == sizeof(int64_t)) {
return (time_t)INT64_MAX;
} else {
return (time_t)INT32_MAX;
}
}
#endif
}
static int64_t
get_time_t_min(void)
{
#if defined(TIME_T_MIN)
return TIME_T_MIN;
#else
if (((time_t)0) < ((time_t)-1)) {
/* Time_t is unsigned */
return (time_t)0;
} else {
/* Time_t is signed. */
if (sizeof(time_t) == sizeof(int64_t)) {
return (time_t)INT64_MIN;
} else {
return (time_t)INT32_MIN;
}
}
#endif
}
static int
archive_read_format_mtree_options(struct archive_read *a,
const char *key, const char *val)
{
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (strcmp(key, "checkfs") == 0) {
/* Allows to read information missing from the mtree from the file system */
if (val == NULL || val[0] == 0) {
mtree->checkfs = 0;
} else {
mtree->checkfs = 1;
}
return (ARCHIVE_OK);
}
/* Note: The "warn" return is just to inform the options
* supervisor that we didn't handle it. It will generate
* a suitable error if no one used this option. */
return (ARCHIVE_WARN);
}
static void
free_options(struct mtree_option *head)
{
struct mtree_option *next;
for (; head != NULL; head = next) {
next = head->next;
free(head->value);
free(head);
}
}
int
archive_read_support_format_mtree(struct archive *_a)
{
struct archive_read *a = (struct archive_read *)_a;
struct mtree *mtree;
int r;
archive_check_magic(_a, ARCHIVE_READ_MAGIC,
ARCHIVE_STATE_NEW, "archive_read_support_format_mtree");
mtree = (struct mtree *)malloc(sizeof(*mtree));
if (mtree == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate mtree data");
return (ARCHIVE_FATAL);
}
memset(mtree, 0, sizeof(*mtree));
mtree->fd = -1;
r = __archive_read_register_format(a, mtree, "mtree",
mtree_bid, archive_read_format_mtree_options, read_header, read_data, skip, NULL, cleanup, NULL, NULL);
if (r != ARCHIVE_OK)
free(mtree);
return (ARCHIVE_OK);
}
static int
cleanup(struct archive_read *a)
{
struct mtree *mtree;
struct mtree_entry *p, *q;
mtree = (struct mtree *)(a->format->data);
p = mtree->entries;
while (p != NULL) {
q = p->next;
free(p->name);
free_options(p->options);
free(p);
p = q;
}
archive_string_free(&mtree->line);
archive_string_free(&mtree->current_dir);
archive_string_free(&mtree->contents_name);
archive_entry_linkresolver_free(mtree->resolver);
free(mtree->buff);
free(mtree);
(a->format->data) = NULL;
return (ARCHIVE_OK);
}
static ssize_t
get_line_size(const char *b, ssize_t avail, ssize_t *nlsize)
{
ssize_t len;
len = 0;
while (len < avail) {
switch (*b) {
case '\0':/* Non-ascii character or control character. */
if (nlsize != NULL)
*nlsize = 0;
return (-1);
case '\r':
if (avail-len > 1 && b[1] == '\n') {
if (nlsize != NULL)
*nlsize = 2;
return (len+2);
}
/* FALL THROUGH */
case '\n':
if (nlsize != NULL)
*nlsize = 1;
return (len+1);
default:
b++;
len++;
break;
}
}
if (nlsize != NULL)
*nlsize = 0;
return (avail);
}
/*
* <---------------- ravail --------------------->
* <-- diff ------> <--- avail ----------------->
* <---- len ----------->
* | Previous lines | line being parsed nl extra |
* ^
* b
*
*/
static ssize_t
next_line(struct archive_read *a,
const char **b, ssize_t *avail, ssize_t *ravail, ssize_t *nl)
{
ssize_t len;
int quit;
quit = 0;
if (*avail == 0) {
*nl = 0;
len = 0;
} else
len = get_line_size(*b, *avail, nl);
/*
* Read bytes more while it does not reach the end of line.
*/
while (*nl == 0 && len == *avail && !quit) {
ssize_t diff = *ravail - *avail;
size_t nbytes_req = (*ravail+1023) & ~1023U;
ssize_t tested;
/* Increase reading bytes if it is not enough to at least
* new two lines. */
if (nbytes_req < (size_t)*ravail + 160)
nbytes_req <<= 1;
*b = __archive_read_ahead(a, nbytes_req, avail);
if (*b == NULL) {
if (*ravail >= *avail)
return (0);
/* Reading bytes reaches the end of file. */
*b = __archive_read_ahead(a, *avail, avail);
quit = 1;
}
*ravail = *avail;
*b += diff;
*avail -= diff;
tested = len;/* Skip some bytes we already determinated. */
len = get_line_size(*b + len, *avail - len, nl);
if (len >= 0)
len += tested;
}
return (len);
}
/*
* Compare characters with a mtree keyword.
* Returns the length of a mtree keyword if matched.
* Returns 0 if not matched.
*/
static int
bid_keycmp(const char *p, const char *key, ssize_t len)
{
int match_len = 0;
while (len > 0 && *p && *key) {
if (*p == *key) {
--len;
++p;
++key;
++match_len;
continue;
}
return (0);/* Not match */
}
if (*key != '\0')
return (0);/* Not match */
/* A following character should be specified characters */
if (p[0] == '=' || p[0] == ' ' || p[0] == '\t' ||
p[0] == '\n' || p[0] == '\r' ||
(p[0] == '\\' && (p[1] == '\n' || p[1] == '\r')))
return (match_len);
return (0);/* Not match */
}
/*
* Test whether the characters 'p' has is mtree keyword.
* Returns the length of a detected keyword.
* Returns 0 if any keywords were not found.
*/
static int
bid_keyword(const char *p, ssize_t len)
{
static const char *keys_c[] = {
"content", "contents", "cksum", NULL
};
static const char *keys_df[] = {
"device", "flags", NULL
};
static const char *keys_g[] = {
"gid", "gname", NULL
};
static const char *keys_il[] = {
"ignore", "inode", "link", NULL
};
static const char *keys_m[] = {
"md5", "md5digest", "mode", NULL
};
static const char *keys_no[] = {
"nlink", "nochange", "optional", NULL
};
static const char *keys_r[] = {
"resdevice", "rmd160", "rmd160digest", NULL
};
static const char *keys_s[] = {
"sha1", "sha1digest",
"sha256", "sha256digest",
"sha384", "sha384digest",
"sha512", "sha512digest",
"size", NULL
};
static const char *keys_t[] = {
"tags", "time", "type", NULL
};
static const char *keys_u[] = {
"uid", "uname", NULL
};
const char **keys;
int i;
switch (*p) {
case 'c': keys = keys_c; break;
case 'd': case 'f': keys = keys_df; break;
case 'g': keys = keys_g; break;
case 'i': case 'l': keys = keys_il; break;
case 'm': keys = keys_m; break;
case 'n': case 'o': keys = keys_no; break;
case 'r': keys = keys_r; break;
case 's': keys = keys_s; break;
case 't': keys = keys_t; break;
case 'u': keys = keys_u; break;
default: return (0);/* Unknown key */
}
for (i = 0; keys[i] != NULL; i++) {
int l = bid_keycmp(p, keys[i], len);
if (l > 0)
return (l);
}
return (0);/* Unknown key */
}
/*
* Test whether there is a set of mtree keywords.
* Returns the number of keyword.
* Returns -1 if we got incorrect sequence.
* This function expects a set of "<space characters>keyword=value".
* When "unset" is specified, expects a set of "<space characters>keyword".
*/
static int
bid_keyword_list(const char *p, ssize_t len, int unset, int last_is_path)
{
int l;
int keycnt = 0;
while (len > 0 && *p) {
int blank = 0;
/* Test whether there are blank characters in the line. */
while (len >0 && (*p == ' ' || *p == '\t')) {
++p;
--len;
blank = 1;
}
if (*p == '\n' || *p == '\r')
break;
if (p[0] == '\\' && (p[1] == '\n' || p[1] == '\r'))
break;
if (!blank && !last_is_path) /* No blank character. */
return (-1);
if (last_is_path && len == 0)
return (keycnt);
if (unset) {
l = bid_keycmp(p, "all", len);
if (l > 0)
return (1);
}
/* Test whether there is a correct key in the line. */
l = bid_keyword(p, len);
if (l == 0)
return (-1);/* Unknown keyword was found. */
p += l;
len -= l;
keycnt++;
/* Skip value */
if (*p == '=') {
int value = 0;
++p;
--len;
while (len > 0 && *p != ' ' && *p != '\t') {
++p;
--len;
value = 1;
}
/* A keyword should have a its value unless
* "/unset" operation. */
if (!unset && value == 0)
return (-1);
}
}
return (keycnt);
}
static int
bid_entry(const char *p, ssize_t len, ssize_t nl, int *last_is_path)
{
int f = 0;
static const unsigned char safe_char[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 00 - 0F */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 10 - 1F */
/* !"$%&'()*+,-./ EXCLUSION:( )(#) */
0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 20 - 2F */
/* 0123456789:;<>? EXCLUSION:(=) */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, /* 30 - 3F */
/* @ABCDEFGHIJKLMNO */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 40 - 4F */
/* PQRSTUVWXYZ[\]^_ */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 50 - 5F */
/* `abcdefghijklmno */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 60 - 6F */
/* pqrstuvwxyz{|}~ */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, /* 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* C0 - CF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* D0 - DF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* E0 - EF */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* F0 - FF */
};
ssize_t ll;
const char *pp = p;
const char * const pp_end = pp + len;
*last_is_path = 0;
/*
* Skip the path-name which is quoted.
*/
for (;pp < pp_end; ++pp) {
if (!safe_char[*(const unsigned char *)pp]) {
if (*pp != ' ' && *pp != '\t' && *pp != '\r'
&& *pp != '\n')
f = 0;
break;
}
f = 1;
}
ll = pp_end - pp;
/* If a path-name was not found at the first, try to check
* a mtree format(a.k.a form D) ``NetBSD's mtree -D'' creates,
* which places the path-name at the last. */
if (f == 0) {
const char *pb = p + len - nl;
int name_len = 0;
int slash;
/* The form D accepts only a single line for an entry. */
if (pb-2 >= p &&
pb[-1] == '\\' && (pb[-2] == ' ' || pb[-2] == '\t'))
return (-1);
if (pb-1 >= p && pb[-1] == '\\')
return (-1);
slash = 0;
while (p <= --pb && *pb != ' ' && *pb != '\t') {
if (!safe_char[*(const unsigned char *)pb])
return (-1);
name_len++;
/* The pathname should have a slash in this
* format. */
if (*pb == '/')
slash = 1;
}
if (name_len == 0 || slash == 0)
return (-1);
/* If '/' is placed at the first in this field, this is not
* a valid filename. */
if (pb[1] == '/')
return (-1);
ll = len - nl - name_len;
pp = p;
*last_is_path = 1;
}
return (bid_keyword_list(pp, ll, 0, *last_is_path));
}
#define MAX_BID_ENTRY 3
static int
mtree_bid(struct archive_read *a, int best_bid)
{
const char *signature = "#mtree";
const char *p;
(void)best_bid; /* UNUSED */
/* Now let's look at the actual header and see if it matches. */
p = __archive_read_ahead(a, strlen(signature), NULL);
if (p == NULL)
return (-1);
if (memcmp(p, signature, strlen(signature)) == 0)
return (8 * (int)strlen(signature));
/*
* There is not a mtree signature. Let's try to detect mtree format.
*/
return (detect_form(a, NULL));
}
static int
detect_form(struct archive_read *a, int *is_form_d)
{
const char *p;
ssize_t avail, ravail;
ssize_t detected_bytes = 0, len, nl;
int entry_cnt = 0, multiline = 0;
int form_D = 0;/* The archive is generated by `NetBSD mtree -D'
* (In this source we call it `form D') . */
if (is_form_d != NULL)
*is_form_d = 0;
p = __archive_read_ahead(a, 1, &avail);
if (p == NULL)
return (-1);
ravail = avail;
for (;;) {
len = next_line(a, &p, &avail, &ravail, &nl);
/* The terminal character of the line should be
* a new line character, '\r\n' or '\n'. */
if (len <= 0 || nl == 0)
break;
if (!multiline) {
/* Leading whitespace is never significant,
* ignore it. */
while (len > 0 && (*p == ' ' || *p == '\t')) {
++p;
--avail;
--len;
}
/* Skip comment or empty line. */
if (p[0] == '#' || p[0] == '\n' || p[0] == '\r') {
p += len;
avail -= len;
continue;
}
} else {
/* A continuance line; the terminal
* character of previous line was '\' character. */
if (bid_keyword_list(p, len, 0, 0) <= 0)
break;
if (multiline == 1)
detected_bytes += len;
if (p[len-nl-1] != '\\') {
if (multiline == 1 &&
++entry_cnt >= MAX_BID_ENTRY)
break;
multiline = 0;
}
p += len;
avail -= len;
continue;
}
if (p[0] != '/') {
int last_is_path, keywords;
keywords = bid_entry(p, len, nl, &last_is_path);
if (keywords >= 0) {
detected_bytes += len;
if (form_D == 0) {
if (last_is_path)
form_D = 1;
else if (keywords > 0)
/* This line is not `form D'. */
form_D = -1;
} else if (form_D == 1) {
if (!last_is_path && keywords > 0)
/* This this is not `form D'
* and We cannot accept mixed
* format. */
break;
}
if (!last_is_path && p[len-nl-1] == '\\')
/* This line continues. */
multiline = 1;
else {
/* We've got plenty of correct lines
* to assume that this file is a mtree
* format. */
if (++entry_cnt >= MAX_BID_ENTRY)
break;
}
} else
break;
} else if (strncmp(p, "/set", 4) == 0) {
if (bid_keyword_list(p+4, len-4, 0, 0) <= 0)
break;
/* This line continues. */
if (p[len-nl-1] == '\\')
multiline = 2;
} else if (strncmp(p, "/unset", 6) == 0) {
if (bid_keyword_list(p+6, len-6, 1, 0) <= 0)
break;
/* This line continues. */
if (p[len-nl-1] == '\\')
multiline = 2;
} else
break;
/* Test next line. */
p += len;
avail -= len;
}
if (entry_cnt >= MAX_BID_ENTRY || (entry_cnt > 0 && len == 0)) {
if (is_form_d != NULL) {
if (form_D == 1)
*is_form_d = 1;
}
return (32);
}
return (0);
}
/*
* The extended mtree format permits multiple lines specifying
* attributes for each file. For those entries, only the last line
* is actually used. Practically speaking, that means we have
* to read the entire mtree file into memory up front.
*
* The parsing is done in two steps. First, it is decided if a line
* changes the global defaults and if it is, processed accordingly.
* Otherwise, the options of the line are merged with the current
* global options.
*/
static int
add_option(struct archive_read *a, struct mtree_option **global,
const char *value, size_t len)
{
struct mtree_option *opt;
if ((opt = malloc(sizeof(*opt))) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
if ((opt->value = malloc(len + 1)) == NULL) {
free(opt);
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
memcpy(opt->value, value, len);
opt->value[len] = '\0';
opt->next = *global;
*global = opt;
return (ARCHIVE_OK);
}
static void
remove_option(struct mtree_option **global, const char *value, size_t len)
{
struct mtree_option *iter, *last;
last = NULL;
for (iter = *global; iter != NULL; last = iter, iter = iter->next) {
if (strncmp(iter->value, value, len) == 0 &&
(iter->value[len] == '\0' ||
iter->value[len] == '='))
break;
}
if (iter == NULL)
return;
if (last == NULL)
*global = iter->next;
else
last->next = iter->next;
free(iter->value);
free(iter);
}
static int
process_global_set(struct archive_read *a,
struct mtree_option **global, const char *line)
{
const char *next, *eq;
size_t len;
int r;
line += 4;
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
line = next;
next = line + strcspn(line, " \t\r\n");
eq = strchr(line, '=');
if (eq > next)
len = next - line;
else
len = eq - line;
remove_option(global, line, len);
r = add_option(a, global, line, next - line);
if (r != ARCHIVE_OK)
return (r);
line = next;
}
}
static int
process_global_unset(struct archive_read *a,
struct mtree_option **global, const char *line)
{
const char *next;
size_t len;
line += 6;
if (strchr(line, '=') != NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"/unset shall not contain `='");
return ARCHIVE_FATAL;
}
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
line = next;
len = strcspn(line, " \t\r\n");
if (len == 3 && strncmp(line, "all", 3) == 0) {
free_options(*global);
*global = NULL;
} else {
remove_option(global, line, len);
}
line += len;
}
}
static int
process_add_entry(struct archive_read *a, struct mtree *mtree,
struct mtree_option **global, const char *line, ssize_t line_len,
struct mtree_entry **last_entry, int is_form_d)
{
struct mtree_entry *entry;
struct mtree_option *iter;
const char *next, *eq, *name, *end;
size_t name_len, len;
int r, i;
if ((entry = malloc(sizeof(*entry))) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
entry->next = NULL;
entry->options = NULL;
entry->name = NULL;
entry->used = 0;
entry->full = 0;
/* Add this entry to list. */
if (*last_entry == NULL)
mtree->entries = entry;
else
(*last_entry)->next = entry;
*last_entry = entry;
if (is_form_d) {
/* Filename is last item on line. */
/* Adjust line_len to trim trailing whitespace */
while (line_len > 0) {
char last_character = line[line_len - 1];
if (last_character == '\r'
|| last_character == '\n'
|| last_character == '\t'
|| last_character == ' ') {
line_len--;
} else {
break;
}
}
/* Name starts after the last whitespace separator */
name = line;
for (i = 0; i < line_len; i++) {
if (line[i] == '\r'
|| line[i] == '\n'
|| line[i] == '\t'
|| line[i] == ' ') {
name = line + i + 1;
}
}
name_len = line + line_len - name;
end = name;
} else {
/* Filename is first item on line */
name_len = strcspn(line, " \t\r\n");
name = line;
line += name_len;
end = line + line_len;
}
/* name/name_len is the name within the line. */
/* line..end brackets the entire line except the name */
if ((entry->name = malloc(name_len + 1)) == NULL) {
archive_set_error(&a->archive, errno, "Can't allocate memory");
return (ARCHIVE_FATAL);
}
memcpy(entry->name, name, name_len);
entry->name[name_len] = '\0';
parse_escapes(entry->name, entry);
for (iter = *global; iter != NULL; iter = iter->next) {
r = add_option(a, &entry->options, iter->value,
strlen(iter->value));
if (r != ARCHIVE_OK)
return (r);
}
for (;;) {
next = line + strspn(line, " \t\r\n");
if (*next == '\0')
return (ARCHIVE_OK);
if (next >= end)
return (ARCHIVE_OK);
line = next;
next = line + strcspn(line, " \t\r\n");
eq = strchr(line, '=');
if (eq == NULL || eq > next)
len = next - line;
else
len = eq - line;
remove_option(&entry->options, line, len);
r = add_option(a, &entry->options, line, next - line);
if (r != ARCHIVE_OK)
return (r);
line = next;
}
}
static int
read_mtree(struct archive_read *a, struct mtree *mtree)
{
ssize_t len;
uintmax_t counter;
char *p;
struct mtree_option *global;
struct mtree_entry *last_entry;
int r, is_form_d;
mtree->archive_format = ARCHIVE_FORMAT_MTREE;
mtree->archive_format_name = "mtree";
global = NULL;
last_entry = NULL;
(void)detect_form(a, &is_form_d);
for (counter = 1; ; ++counter) {
len = readline(a, mtree, &p, 65536);
if (len == 0) {
mtree->this_entry = mtree->entries;
free_options(global);
return (ARCHIVE_OK);
}
if (len < 0) {
free_options(global);
return ((int)len);
}
/* Leading whitespace is never significant, ignore it. */
while (*p == ' ' || *p == '\t') {
++p;
--len;
}
/* Skip content lines and blank lines. */
if (*p == '#')
continue;
if (*p == '\r' || *p == '\n' || *p == '\0')
continue;
if (*p != '/') {
r = process_add_entry(a, mtree, &global, p, len,
&last_entry, is_form_d);
} else if (strncmp(p, "/set", 4) == 0) {
if (p[4] != ' ' && p[4] != '\t')
break;
r = process_global_set(a, &global, p);
} else if (strncmp(p, "/unset", 6) == 0) {
if (p[6] != ' ' && p[6] != '\t')
break;
r = process_global_unset(a, &global, p);
} else
break;
if (r != ARCHIVE_OK) {
free_options(global);
return r;
}
}
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Can't parse line %ju", counter);
free_options(global);
return (ARCHIVE_FATAL);
}
/*
* Read in the entire mtree file into memory on the first request.
* Then use the next unused file to satisfy each header request.
*/
static int
read_header(struct archive_read *a, struct archive_entry *entry)
{
struct mtree *mtree;
char *p;
int r, use_next;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd >= 0) {
close(mtree->fd);
mtree->fd = -1;
}
if (mtree->entries == NULL) {
mtree->resolver = archive_entry_linkresolver_new();
if (mtree->resolver == NULL)
return ARCHIVE_FATAL;
archive_entry_linkresolver_set_strategy(mtree->resolver,
ARCHIVE_FORMAT_MTREE);
r = read_mtree(a, mtree);
if (r != ARCHIVE_OK)
return (r);
}
a->archive.archive_format = mtree->archive_format;
a->archive.archive_format_name = mtree->archive_format_name;
for (;;) {
if (mtree->this_entry == NULL)
return (ARCHIVE_EOF);
if (strcmp(mtree->this_entry->name, "..") == 0) {
mtree->this_entry->used = 1;
if (archive_strlen(&mtree->current_dir) > 0) {
/* Roll back current path. */
p = mtree->current_dir.s
+ mtree->current_dir.length - 1;
while (p >= mtree->current_dir.s && *p != '/')
--p;
if (p >= mtree->current_dir.s)
--p;
mtree->current_dir.length
= p - mtree->current_dir.s + 1;
}
}
if (!mtree->this_entry->used) {
use_next = 0;
r = parse_file(a, entry, mtree, mtree->this_entry,
&use_next);
if (use_next == 0)
return (r);
}
mtree->this_entry = mtree->this_entry->next;
}
}
/*
* A single file can have multiple lines contribute specifications.
* Parse as many lines as necessary, then pull additional information
* from a backing file on disk as necessary.
*/
static int
parse_file(struct archive_read *a, struct archive_entry *entry,
struct mtree *mtree, struct mtree_entry *mentry, int *use_next)
{
const char *path;
struct stat st_storage, *st;
struct mtree_entry *mp;
struct archive_entry *sparse_entry;
int r = ARCHIVE_OK, r1, parsed_kws;
mentry->used = 1;
/* Initialize reasonable defaults. */
archive_entry_set_filetype(entry, AE_IFREG);
archive_entry_set_size(entry, 0);
archive_string_empty(&mtree->contents_name);
/* Parse options from this line. */
parsed_kws = 0;
r = parse_line(a, entry, mtree, mentry, &parsed_kws);
if (mentry->full) {
archive_entry_copy_pathname(entry, mentry->name);
/*
* "Full" entries are allowed to have multiple lines
* and those lines aren't required to be adjacent. We
* don't support multiple lines for "relative" entries
* nor do we make any attempt to merge data from
* separate "relative" and "full" entries. (Merging
* "relative" and "full" entries would require dealing
* with pathname canonicalization, which is a very
* tricky subject.)
*/
for (mp = mentry->next; mp != NULL; mp = mp->next) {
if (mp->full && !mp->used
&& strcmp(mentry->name, mp->name) == 0) {
/* Later lines override earlier ones. */
mp->used = 1;
r1 = parse_line(a, entry, mtree, mp,
&parsed_kws);
if (r1 < r)
r = r1;
}
}
} else {
/*
* Relative entries require us to construct
* the full path and possibly update the
* current directory.
*/
size_t n = archive_strlen(&mtree->current_dir);
if (n > 0)
archive_strcat(&mtree->current_dir, "/");
archive_strcat(&mtree->current_dir, mentry->name);
archive_entry_copy_pathname(entry, mtree->current_dir.s);
if (archive_entry_filetype(entry) != AE_IFDIR)
mtree->current_dir.length = n;
}
if (mtree->checkfs) {
/*
* Try to open and stat the file to get the real size
* and other file info. It would be nice to avoid
* this here so that getting a listing of an mtree
* wouldn't require opening every referenced contents
* file. But then we wouldn't know the actual
* contents size, so I don't see a really viable way
* around this. (Also, we may want to someday pull
* other unspecified info from the contents file on
* disk.)
*/
mtree->fd = -1;
if (archive_strlen(&mtree->contents_name) > 0)
path = mtree->contents_name.s;
else
path = archive_entry_pathname(entry);
if (archive_entry_filetype(entry) == AE_IFREG ||
archive_entry_filetype(entry) == AE_IFDIR) {
mtree->fd = open(path, O_RDONLY | O_BINARY | O_CLOEXEC);
__archive_ensure_cloexec_flag(mtree->fd);
if (mtree->fd == -1 &&
(errno != ENOENT ||
archive_strlen(&mtree->contents_name) > 0)) {
archive_set_error(&a->archive, errno,
"Can't open %s", path);
r = ARCHIVE_WARN;
}
}
st = &st_storage;
if (mtree->fd >= 0) {
if (fstat(mtree->fd, st) == -1) {
archive_set_error(&a->archive, errno,
"Could not fstat %s", path);
r = ARCHIVE_WARN;
/* If we can't stat it, don't keep it open. */
close(mtree->fd);
mtree->fd = -1;
st = NULL;
}
} else if (lstat(path, st) == -1) {
st = NULL;
}
/*
* Check for a mismatch between the type in the specification
* and the type of the contents object on disk.
*/
if (st != NULL) {
if (((st->st_mode & S_IFMT) == S_IFREG &&
archive_entry_filetype(entry) == AE_IFREG)
#ifdef S_IFLNK
||((st->st_mode & S_IFMT) == S_IFLNK &&
archive_entry_filetype(entry) == AE_IFLNK)
#endif
#ifdef S_IFSOCK
||((st->st_mode & S_IFSOCK) == S_IFSOCK &&
archive_entry_filetype(entry) == AE_IFSOCK)
#endif
#ifdef S_IFCHR
||((st->st_mode & S_IFMT) == S_IFCHR &&
archive_entry_filetype(entry) == AE_IFCHR)
#endif
#ifdef S_IFBLK
||((st->st_mode & S_IFMT) == S_IFBLK &&
archive_entry_filetype(entry) == AE_IFBLK)
#endif
||((st->st_mode & S_IFMT) == S_IFDIR &&
archive_entry_filetype(entry) == AE_IFDIR)
#ifdef S_IFIFO
||((st->st_mode & S_IFMT) == S_IFIFO &&
archive_entry_filetype(entry) == AE_IFIFO)
#endif
) {
/* Types match. */
} else {
/* Types don't match; bail out gracefully. */
if (mtree->fd >= 0)
close(mtree->fd);
mtree->fd = -1;
if (parsed_kws & MTREE_HAS_OPTIONAL) {
/* It's not an error for an optional
* entry to not match disk. */
*use_next = 1;
} else if (r == ARCHIVE_OK) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_MISC,
"mtree specification has different"
" type for %s",
archive_entry_pathname(entry));
r = ARCHIVE_WARN;
}
return (r);
}
}
/*
* If there is a contents file on disk, pick some of the
* metadata from that file. For most of these, we only
* set it from the contents if it wasn't already parsed
* from the specification.
*/
if (st != NULL) {
if (((parsed_kws & MTREE_HAS_DEVICE) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0) &&
(archive_entry_filetype(entry) == AE_IFCHR ||
archive_entry_filetype(entry) == AE_IFBLK))
archive_entry_set_rdev(entry, st->st_rdev);
if ((parsed_kws & (MTREE_HAS_GID | MTREE_HAS_GNAME))
== 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_gid(entry, st->st_gid);
if ((parsed_kws & (MTREE_HAS_UID | MTREE_HAS_UNAME))
== 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_uid(entry, st->st_uid);
if ((parsed_kws & MTREE_HAS_MTIME) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0) {
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtimespec.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtim.tv_nsec);
#elif HAVE_STRUCT_STAT_ST_MTIME_N
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtime_n);
#elif HAVE_STRUCT_STAT_ST_UMTIME
archive_entry_set_mtime(entry, st->st_mtime,
st->st_umtime*1000);
#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
archive_entry_set_mtime(entry, st->st_mtime,
st->st_mtime_usec*1000);
#else
archive_entry_set_mtime(entry, st->st_mtime, 0);
#endif
}
if ((parsed_kws & MTREE_HAS_NLINK) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_nlink(entry, st->st_nlink);
if ((parsed_kws & MTREE_HAS_PERM) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_perm(entry, st->st_mode);
if ((parsed_kws & MTREE_HAS_SIZE) == 0 ||
(parsed_kws & MTREE_HAS_NOCHANGE) != 0)
archive_entry_set_size(entry, st->st_size);
archive_entry_set_ino(entry, st->st_ino);
archive_entry_set_dev(entry, st->st_dev);
archive_entry_linkify(mtree->resolver, &entry,
&sparse_entry);
} else if (parsed_kws & MTREE_HAS_OPTIONAL) {
/*
* Couldn't open the entry, stat it or the on-disk type
* didn't match. If this entry is optional, just
* ignore it and read the next header entry.
*/
*use_next = 1;
return ARCHIVE_OK;
}
}
mtree->cur_size = archive_entry_size(entry);
mtree->offset = 0;
return r;
}
/*
* Each line contains a sequence of keywords.
*/
static int
parse_line(struct archive_read *a, struct archive_entry *entry,
struct mtree *mtree, struct mtree_entry *mp, int *parsed_kws)
{
struct mtree_option *iter;
int r = ARCHIVE_OK, r1;
for (iter = mp->options; iter != NULL; iter = iter->next) {
r1 = parse_keyword(a, mtree, entry, iter, parsed_kws);
if (r1 < r)
r = r1;
}
if (r == ARCHIVE_OK && (*parsed_kws & MTREE_HAS_TYPE) == 0) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing type keyword in mtree specification");
return (ARCHIVE_WARN);
}
return (r);
}
/*
* Device entries have one of the following forms:
* - raw dev_t
* - format,major,minor[,subdevice]
* When parsing succeeded, `pdev' will contain the appropriate dev_t value.
*/
/* strsep() is not in C90, but strcspn() is. */
/* Taken from http://unixpapa.com/incnote/string.html */
static char *
la_strsep(char **sp, const char *sep)
{
char *p, *s;
if (sp == NULL || *sp == NULL || **sp == '\0')
return(NULL);
s = *sp;
p = s + strcspn(s, sep);
if (*p != '\0')
*p++ = '\0';
*sp = p;
return(s);
}
static int
parse_device(dev_t *pdev, struct archive *a, char *val)
{
#define MAX_PACK_ARGS 3
unsigned long numbers[MAX_PACK_ARGS];
char *p, *dev;
int argc;
pack_t *pack;
dev_t result;
const char *error = NULL;
memset(pdev, 0, sizeof(*pdev));
if ((dev = strchr(val, ',')) != NULL) {
/*
* Device's major/minor are given in a specified format.
* Decode and pack it accordingly.
*/
*dev++ = '\0';
if ((pack = pack_find(val)) == NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Unknown format `%s'", val);
return ARCHIVE_WARN;
}
argc = 0;
while ((p = la_strsep(&dev, ",")) != NULL) {
if (*p == '\0') {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Missing number");
return ARCHIVE_WARN;
}
if (argc >= MAX_PACK_ARGS) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Too many arguments");
return ARCHIVE_WARN;
}
numbers[argc++] = (unsigned long)mtree_atol(&p);
}
if (argc < 2) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"Not enough arguments");
return ARCHIVE_WARN;
}
result = (*pack)(argc, numbers, &error);
if (error != NULL) {
archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
"%s", error);
return ARCHIVE_WARN;
}
} else {
/* file system raw value. */
result = (dev_t)mtree_atol(&val);
}
*pdev = result;
return ARCHIVE_OK;
#undef MAX_PACK_ARGS
}
/*
* Parse a single keyword and its value.
*/
static int
parse_keyword(struct archive_read *a, struct mtree *mtree,
struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws)
{
char *val, *key;
key = opt->value;
if (*key == '\0')
return (ARCHIVE_OK);
if (strcmp(key, "nochange") == 0) {
*parsed_kws |= MTREE_HAS_NOCHANGE;
return (ARCHIVE_OK);
}
if (strcmp(key, "optional") == 0) {
*parsed_kws |= MTREE_HAS_OPTIONAL;
return (ARCHIVE_OK);
}
if (strcmp(key, "ignore") == 0) {
/*
* The mtree processing is not recursive, so
* recursion will only happen for explicitly listed
* entries.
*/
return (ARCHIVE_OK);
}
val = strchr(key, '=');
if (val == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Malformed attribute \"%s\" (%d)", key, key[0]);
return (ARCHIVE_WARN);
}
*val = '\0';
++val;
switch (key[0]) {
case 'c':
if (strcmp(key, "content") == 0
|| strcmp(key, "contents") == 0) {
parse_escapes(val, NULL);
archive_strcpy(&mtree->contents_name, val);
break;
}
if (strcmp(key, "cksum") == 0)
break;
case 'd':
if (strcmp(key, "device") == 0) {
/* stat(2) st_rdev field, e.g. the major/minor IDs
* of a char/block special file */
int r;
dev_t dev;
*parsed_kws |= MTREE_HAS_DEVICE;
r = parse_device(&dev, &a->archive, val);
if (r == ARCHIVE_OK)
archive_entry_set_rdev(entry, dev);
return r;
}
case 'f':
if (strcmp(key, "flags") == 0) {
*parsed_kws |= MTREE_HAS_FFLAGS;
archive_entry_copy_fflags_text(entry, val);
break;
}
case 'g':
if (strcmp(key, "gid") == 0) {
*parsed_kws |= MTREE_HAS_GID;
archive_entry_set_gid(entry, mtree_atol10(&val));
break;
}
if (strcmp(key, "gname") == 0) {
*parsed_kws |= MTREE_HAS_GNAME;
archive_entry_copy_gname(entry, val);
break;
}
case 'i':
if (strcmp(key, "inode") == 0) {
archive_entry_set_ino(entry, mtree_atol10(&val));
break;
}
case 'l':
if (strcmp(key, "link") == 0) {
archive_entry_copy_symlink(entry, val);
break;
}
case 'm':
if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
break;
if (strcmp(key, "mode") == 0) {
if (val[0] >= '0' && val[0] <= '9') {
*parsed_kws |= MTREE_HAS_PERM;
archive_entry_set_perm(entry,
(mode_t)mtree_atol8(&val));
} else {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Symbolic mode \"%s\" unsupported", val);
return ARCHIVE_WARN;
}
break;
}
case 'n':
if (strcmp(key, "nlink") == 0) {
*parsed_kws |= MTREE_HAS_NLINK;
archive_entry_set_nlink(entry,
(unsigned int)mtree_atol10(&val));
break;
}
case 'r':
if (strcmp(key, "resdevice") == 0) {
/* stat(2) st_dev field, e.g. the device ID where the
* inode resides */
int r;
dev_t dev;
r = parse_device(&dev, &a->archive, val);
if (r == ARCHIVE_OK)
archive_entry_set_dev(entry, dev);
return r;
}
if (strcmp(key, "rmd160") == 0 ||
strcmp(key, "rmd160digest") == 0)
break;
case 's':
if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
break;
if (strcmp(key, "sha256") == 0 ||
strcmp(key, "sha256digest") == 0)
break;
if (strcmp(key, "sha384") == 0 ||
strcmp(key, "sha384digest") == 0)
break;
if (strcmp(key, "sha512") == 0 ||
strcmp(key, "sha512digest") == 0)
break;
if (strcmp(key, "size") == 0) {
archive_entry_set_size(entry, mtree_atol10(&val));
break;
}
case 't':
if (strcmp(key, "tags") == 0) {
/*
* Comma delimited list of tags.
* Ignore the tags for now, but the interface
* should be extended to allow inclusion/exclusion.
*/
break;
}
if (strcmp(key, "time") == 0) {
int64_t m;
int64_t my_time_t_max = get_time_t_max();
int64_t my_time_t_min = get_time_t_min();
long ns = 0;
*parsed_kws |= MTREE_HAS_MTIME;
m = mtree_atol10(&val);
/* Replicate an old mtree bug:
* 123456789.1 represents 123456789
* seconds and 1 nanosecond. */
if (*val == '.') {
++val;
ns = (long)mtree_atol10(&val);
} else
ns = 0;
if (m > my_time_t_max)
m = my_time_t_max;
else if (m < my_time_t_min)
m = my_time_t_min;
archive_entry_set_mtime(entry, (time_t)m, ns);
break;
}
if (strcmp(key, "type") == 0) {
switch (val[0]) {
case 'b':
if (strcmp(val, "block") == 0) {
archive_entry_set_filetype(entry, AE_IFBLK);
break;
}
case 'c':
if (strcmp(val, "char") == 0) {
archive_entry_set_filetype(entry,
AE_IFCHR);
break;
}
case 'd':
if (strcmp(val, "dir") == 0) {
archive_entry_set_filetype(entry,
AE_IFDIR);
break;
}
case 'f':
if (strcmp(val, "fifo") == 0) {
archive_entry_set_filetype(entry,
AE_IFIFO);
break;
}
if (strcmp(val, "file") == 0) {
archive_entry_set_filetype(entry,
AE_IFREG);
break;
}
case 'l':
if (strcmp(val, "link") == 0) {
archive_entry_set_filetype(entry,
AE_IFLNK);
break;
}
default:
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Unrecognized file type \"%s\"; "
"assuming \"file\"", val);
archive_entry_set_filetype(entry, AE_IFREG);
return (ARCHIVE_WARN);
}
*parsed_kws |= MTREE_HAS_TYPE;
break;
}
case 'u':
if (strcmp(key, "uid") == 0) {
*parsed_kws |= MTREE_HAS_UID;
archive_entry_set_uid(entry, mtree_atol10(&val));
break;
}
if (strcmp(key, "uname") == 0) {
*parsed_kws |= MTREE_HAS_UNAME;
archive_entry_copy_uname(entry, val);
break;
}
default:
archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
"Unrecognized key %s=%s", key, val);
return (ARCHIVE_WARN);
}
return (ARCHIVE_OK);
}
static int
read_data(struct archive_read *a, const void **buff, size_t *size,
int64_t *offset)
{
size_t bytes_to_read;
ssize_t bytes_read;
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd < 0) {
*buff = NULL;
*offset = 0;
*size = 0;
return (ARCHIVE_EOF);
}
if (mtree->buff == NULL) {
mtree->buffsize = 64 * 1024;
mtree->buff = malloc(mtree->buffsize);
if (mtree->buff == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate memory");
return (ARCHIVE_FATAL);
}
}
*buff = mtree->buff;
*offset = mtree->offset;
if ((int64_t)mtree->buffsize > mtree->cur_size - mtree->offset)
bytes_to_read = (size_t)(mtree->cur_size - mtree->offset);
else
bytes_to_read = mtree->buffsize;
bytes_read = read(mtree->fd, mtree->buff, bytes_to_read);
if (bytes_read < 0) {
archive_set_error(&a->archive, errno, "Can't read");
return (ARCHIVE_WARN);
}
if (bytes_read == 0) {
*size = 0;
return (ARCHIVE_EOF);
}
mtree->offset += bytes_read;
*size = bytes_read;
return (ARCHIVE_OK);
}
/* Skip does nothing except possibly close the contents file. */
static int
skip(struct archive_read *a)
{
struct mtree *mtree;
mtree = (struct mtree *)(a->format->data);
if (mtree->fd >= 0) {
close(mtree->fd);
mtree->fd = -1;
}
return (ARCHIVE_OK);
}
/*
* Since parsing backslash sequences always makes strings shorter,
* we can always do this conversion in-place.
*/
static void
parse_escapes(char *src, struct mtree_entry *mentry)
{
char *dest = src;
char c;
if (mentry != NULL && strcmp(src, ".") == 0)
mentry->full = 1;
while (*src != '\0') {
c = *src++;
if (c == '/' && mentry != NULL)
mentry->full = 1;
if (c == '\\') {
switch (src[0]) {
case '0':
if (src[1] < '0' || src[1] > '7') {
c = 0;
++src;
break;
}
/* FALLTHROUGH */
case '1':
case '2':
case '3':
if (src[1] >= '0' && src[1] <= '7' &&
src[2] >= '0' && src[2] <= '7') {
c = (src[0] - '0') << 6;
c |= (src[1] - '0') << 3;
c |= (src[2] - '0');
src += 3;
}
break;
case 'a':
c = '\a';
++src;
break;
case 'b':
c = '\b';
++src;
break;
case 'f':
c = '\f';
++src;
break;
case 'n':
c = '\n';
++src;
break;
case 'r':
c = '\r';
++src;
break;
case 's':
c = ' ';
++src;
break;
case 't':
c = '\t';
++src;
break;
case 'v':
c = '\v';
++src;
break;
case '\\':
c = '\\';
++src;
break;
}
}
*dest++ = c;
}
*dest = '\0';
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol8(char **p)
{
int64_t l, limit, last_digit_limit;
int digit, base;
base = 8;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
l = 0;
digit = **p - '0';
while (digit >= 0 && digit < base) {
if (l>limit || (l == limit && digit > last_digit_limit)) {
l = INT64_MAX; /* Truncate on overflow. */
break;
}
l = (l * base) + digit;
digit = *++(*p) - '0';
}
return (l);
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol10(char **p)
{
int64_t l, limit, last_digit_limit;
int base, digit, sign;
base = 10;
if (**p == '-') {
sign = -1;
limit = ((uint64_t)(INT64_MAX) + 1) / base;
last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
++(*p);
} else {
sign = 1;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
}
l = 0;
digit = **p - '0';
while (digit >= 0 && digit < base) {
if (l > limit || (l == limit && digit > last_digit_limit))
return (sign < 0) ? INT64_MIN : INT64_MAX;
l = (l * base) + digit;
digit = *++(*p) - '0';
}
return (sign < 0) ? -l : l;
}
/* Parse a hex digit. */
static int
parsehex(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'a' && c <= 'f')
return c - 'a';
else if (c >= 'A' && c <= 'F')
return c - 'A';
else
return -1;
}
/*
* Note that this implementation does not (and should not!) obey
* locale settings; you cannot simply substitute strtol here, since
* it does obey locale.
*/
static int64_t
mtree_atol16(char **p)
{
int64_t l, limit, last_digit_limit;
int base, digit, sign;
base = 16;
if (**p == '-') {
sign = -1;
limit = ((uint64_t)(INT64_MAX) + 1) / base;
last_digit_limit = ((uint64_t)(INT64_MAX) + 1) % base;
++(*p);
} else {
sign = 1;
limit = INT64_MAX / base;
last_digit_limit = INT64_MAX % base;
}
l = 0;
digit = parsehex(**p);
while (digit >= 0 && digit < base) {
if (l > limit || (l == limit && digit > last_digit_limit))
return (sign < 0) ? INT64_MIN : INT64_MAX;
l = (l * base) + digit;
digit = parsehex(*++(*p));
}
return (sign < 0) ? -l : l;
}
static int64_t
mtree_atol(char **p)
{
if (**p != '0')
return mtree_atol10(p);
if ((*p)[1] == 'x' || (*p)[1] == 'X') {
*p += 2;
return mtree_atol16(p);
}
return mtree_atol8(p);
}
/*
* Returns length of line (including trailing newline)
* or negative on error. 'start' argument is updated to
* point to first character of line.
*/
static ssize_t
readline(struct archive_read *a, struct mtree *mtree, char **start,
ssize_t limit)
{
ssize_t bytes_read;
ssize_t total_size = 0;
ssize_t find_off = 0;
const void *t;
void *nl;
char *u;
/* Accumulate line in a line buffer. */
for (;;) {
/* Read some more. */
t = __archive_read_ahead(a, 1, &bytes_read);
if (t == NULL)
return (0);
if (bytes_read < 0)
return (ARCHIVE_FATAL);
nl = memchr(t, '\n', bytes_read);
/* If we found '\n', trim the read to end exactly there. */
if (nl != NULL) {
bytes_read = ((const char *)nl) - ((const char *)t) + 1;
}
if (total_size + bytes_read + 1 > limit) {
archive_set_error(&a->archive,
ARCHIVE_ERRNO_FILE_FORMAT,
"Line too long");
return (ARCHIVE_FATAL);
}
if (archive_string_ensure(&mtree->line,
total_size + bytes_read + 1) == NULL) {
archive_set_error(&a->archive, ENOMEM,
"Can't allocate working buffer");
return (ARCHIVE_FATAL);
}
/* Append new bytes to string. */
memcpy(mtree->line.s + total_size, t, bytes_read);
__archive_read_consume(a, bytes_read);
total_size += bytes_read;
mtree->line.s[total_size] = '\0';
for (u = mtree->line.s + find_off; *u; ++u) {
if (u[0] == '\n') {
/* Ends with unescaped newline. */
*start = mtree->line.s;
return total_size;
} else if (u[0] == '#') {
/* Ends with comment sequence #...\n */
if (nl == NULL) {
/* But we've not found the \n yet */
break;
}
} else if (u[0] == '\\') {
if (u[1] == '\n') {
/* Trim escaped newline. */
total_size -= 2;
mtree->line.s[total_size] = '\0';
break;
} else if (u[1] != '\0') {
/* Skip the two-char escape sequence */
++u;
}
}
}
find_off = u - mtree->line.s;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5361_1 |
crossvul-cpp_data_good_2957_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 "config.h"
#include "libavutil/attributes.h"
#include "libavutil/cpu.h"
#include "libavutil/x86/cpu.h"
#include "libavcodec/mpegvideodsp.h"
#include "libavcodec/videodsp.h"
#if HAVE_INLINE_ASM
static void gmc_mmx(uint8_t *dst, uint8_t *src,
int stride, int h, int ox, int oy,
int dxx, int dxy, int dyx, int dyy,
int shift, int r, int width, int height)
{
const int w = 8;
const int ix = ox >> (16 + shift);
const int iy = oy >> (16 + shift);
const int oxs = ox >> 4;
const int oys = oy >> 4;
const int dxxs = dxx >> 4;
const int dxys = dxy >> 4;
const int dyxs = dyx >> 4;
const int dyys = dyy >> 4;
const uint16_t r4[4] = { r, r, r, r };
const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys };
const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys };
const uint64_t shift2 = 2 * shift;
#define MAX_STRIDE 4096U
#define MAX_H 8U
uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE];
int x, y;
const int dxw = (dxx - (1 << (16 + shift))) * (w - 1);
const int dyh = (dyy - (1 << (16 + shift))) * (h - 1);
const int dxh = dxy * (h - 1);
const int dyw = dyx * (w - 1);
int need_emu = (unsigned) ix >= width - w || width < w ||
(unsigned) iy >= height - h || height< h
;
if ( // non-constant fullpel offset (3% of blocks)
((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |
(oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) ||
// uses more than 16 bits of subpel mv (only at huge resolution)
(dxx | dxy | dyx | dyy) & 15 ||
(need_emu && (h > MAX_H || stride > MAX_STRIDE))) {
// FIXME could still use mmx for some of the rows
ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy,
shift, r, width, height);
return;
}
src += ix + iy * stride;
if (need_emu) {
ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height);
src = edge_buf;
}
__asm__ volatile (
"movd %0, %%mm6 \n\t"
"pxor %%mm7, %%mm7 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
"punpcklwd %%mm6, %%mm6 \n\t"
:: "r" (1 << shift));
for (x = 0; x < w; x += 4) {
uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0),
oxs - dxys + dxxs * (x + 1),
oxs - dxys + dxxs * (x + 2),
oxs - dxys + dxxs * (x + 3) };
uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0),
oys - dyys + dyxs * (x + 1),
oys - dyys + dyxs * (x + 2),
oys - dyys + dyxs * (x + 3) };
for (y = 0; y < h; y++) {
__asm__ volatile (
"movq %0, %%mm4 \n\t"
"movq %1, %%mm5 \n\t"
"paddw %2, %%mm4 \n\t"
"paddw %3, %%mm5 \n\t"
"movq %%mm4, %0 \n\t"
"movq %%mm5, %1 \n\t"
"psrlw $12, %%mm4 \n\t"
"psrlw $12, %%mm5 \n\t"
: "+m" (*dx4), "+m" (*dy4)
: "m" (*dxy4), "m" (*dyy4));
__asm__ volatile (
"movq %%mm6, %%mm2 \n\t"
"movq %%mm6, %%mm1 \n\t"
"psubw %%mm4, %%mm2 \n\t"
"psubw %%mm5, %%mm1 \n\t"
"movq %%mm2, %%mm0 \n\t"
"movq %%mm4, %%mm3 \n\t"
"pmullw %%mm1, %%mm0 \n\t" // (s - dx) * (s - dy)
"pmullw %%mm5, %%mm3 \n\t" // dx * dy
"pmullw %%mm5, %%mm2 \n\t" // (s - dx) * dy
"pmullw %%mm4, %%mm1 \n\t" // dx * (s - dy)
"movd %4, %%mm5 \n\t"
"movd %3, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm3 \n\t" // src[1, 1] * dx * dy
"pmullw %%mm4, %%mm2 \n\t" // src[0, 1] * (s - dx) * dy
"movd %2, %%mm5 \n\t"
"movd %1, %%mm4 \n\t"
"punpcklbw %%mm7, %%mm5 \n\t"
"punpcklbw %%mm7, %%mm4 \n\t"
"pmullw %%mm5, %%mm1 \n\t" // src[1, 0] * dx * (s - dy)
"pmullw %%mm4, %%mm0 \n\t" // src[0, 0] * (s - dx) * (s - dy)
"paddw %5, %%mm1 \n\t"
"paddw %%mm3, %%mm2 \n\t"
"paddw %%mm1, %%mm0 \n\t"
"paddw %%mm2, %%mm0 \n\t"
"psrlw %6, %%mm0 \n\t"
"packuswb %%mm0, %%mm0 \n\t"
"movd %%mm0, %0 \n\t"
: "=m" (dst[x + y * stride])
: "m" (src[0]), "m" (src[1]),
"m" (src[stride]), "m" (src[stride + 1]),
"m" (*r4), "m" (shift2));
src += stride;
}
src += 4 - h * stride;
}
}
#endif /* HAVE_INLINE_ASM */
av_cold void ff_mpegvideodsp_init_x86(MpegVideoDSPContext *c)
{
#if HAVE_INLINE_ASM
int cpu_flags = av_get_cpu_flags();
if (INLINE_MMX(cpu_flags))
c->gmc = gmc_mmx;
#endif /* HAVE_INLINE_ASM */
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2957_0 |
crossvul-cpp_data_bad_351_1 | /*
* Copyright (c) 2007 Athena Smartcard Solutions Inc.
*
* 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 2.1 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <ctype.h>
#include <string.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
static const struct sc_card_operations *iso_ops = NULL;
struct sc_card_operations asepcos_ops;
static struct sc_card_driver asepcos_drv = {
"Athena ASEPCOS",
"asepcos",
&asepcos_ops,
NULL, 0, NULL
};
static struct sc_atr_table asepcos_atrs[] = {
{ "3b:d6:18:00:81:b1:80:7d:1f:03:80:51:00:61:10:30:8f", NULL, NULL, SC_CARD_TYPE_ASEPCOS_GENERIC, 0, NULL},
{ "3b:d6:18:00:81:b1:fe:7d:1f:03:41:53:45:37:35:35:01", NULL, NULL, SC_CARD_TYPE_ASEPCOS_JAVA, 0, NULL},
{ NULL, NULL, NULL, 0, 0, NULL }
};
static int asepcos_match_card(sc_card_t *card)
{
int i = _sc_match_atr(card, asepcos_atrs, &card->type);
if (i < 0)
return 0;
return 1;
}
static int asepcos_select_asepcos_applet(sc_card_t *card)
{
static const u8 asepcos_aid[] = {0xA0,0x00,0x00,0x01,0x64,0x41,0x53,0x45,0x50,0x43,0x4F,0x53,0x00};
sc_path_t tpath;
int r;
memset(&tpath, 0, sizeof(sc_path_t));
tpath.type = SC_PATH_TYPE_DF_NAME;
tpath.len = sizeof(asepcos_aid);
memcpy(tpath.value, asepcos_aid, sizeof(asepcos_aid));
r = sc_select_file(card, &tpath, NULL);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to select ASEPCOS applet");
return r;
}
return SC_SUCCESS;
}
static int asepcos_init(sc_card_t *card)
{
unsigned long flags;
card->name = "Athena ASEPCOS";
card->cla = 0x00;
/* in case of a Java card try to select the ASEPCOS applet */
if (card->type == SC_CARD_TYPE_ASEPCOS_JAVA) {
int r = asepcos_select_asepcos_applet(card);
if (r != SC_SUCCESS)
return SC_ERROR_INVALID_CARD;
}
/* Set up algorithm info. */
flags = SC_ALGORITHM_RSA_RAW
| SC_ALGORITHM_RSA_HASH_NONE
| SC_ALGORITHM_ONBOARD_KEY_GEN
;
_sc_card_add_rsa_alg(card, 512, flags, 0);
_sc_card_add_rsa_alg(card, 768, flags, 0);
_sc_card_add_rsa_alg(card, 1024, flags, 0);
_sc_card_add_rsa_alg(card, 1536, flags, 0);
_sc_card_add_rsa_alg(card, 1792, flags, 0);
_sc_card_add_rsa_alg(card, 2048, flags, 0);
card->caps |= SC_CARD_CAP_APDU_EXT | SC_CARD_CAP_USE_FCI_AC;
return SC_SUCCESS;
}
/* tables to map the asepcos access mode bytes to the OpenSC
* access mode flags */
typedef struct {
unsigned int am;
unsigned int sc;
} amode_entry_t;
static const amode_entry_t df_amode_table[] = {
{ 0x40, SC_AC_OP_DELETE_SELF }, /* DELETE self */
{ 0x01, SC_AC_OP_DELETE }, /* DELETE child */
{ 0x10, SC_AC_OP_INVALIDATE }, /* DEACTIVATE FILE */
{ 0x08, SC_AC_OP_REHABILITATE },/* ACTIVATE FILE */
{ 0x04, SC_AC_OP_CREATE }, /* CREATE DF */
{ 0x02, SC_AC_OP_CREATE }, /* CREATE EF */
{ 0, 0 }
};
static const amode_entry_t wef_amode_table[] = {
{ 0x04, SC_AC_OP_WRITE },
{ 0x02, SC_AC_OP_UPDATE },
{ 0x01, SC_AC_OP_READ },
{ 0, 0 },
};
static const amode_entry_t ief_amode_table[] = {
{ 0x90, SC_AC_OP_REHABILITATE },
/* UPDATE is also used when a new key is generated */
{ 0x82, SC_AC_OP_UPDATE },
{ 0, 0 },
};
static int set_sec_attr(sc_file_t *file, unsigned int am, unsigned int ac,
unsigned int meth)
{
const amode_entry_t *table;
/* CHV with reference '0' is the transport PIN
* and is presented as 'AUT' key with reference '0'*/
if (meth == SC_AC_CHV && ac == 0)
meth = SC_AC_AUT;
if (file->type == SC_FILE_TYPE_DF)
table = df_amode_table;
else if (file->type == SC_FILE_TYPE_WORKING_EF)
table = wef_amode_table;
else if (file->type == SC_FILE_TYPE_INTERNAL_EF)
table = ief_amode_table;
else
return SC_ERROR_INVALID_ARGUMENTS;
for (; table->am != 0; table++) {
if (table->am & am)
sc_file_add_acl_entry(file, table->sc, meth, ac);
}
return SC_SUCCESS;
}
/* Convert asepcos security attributes to opensc access conditions.
*/
static int asepcos_parse_sec_attr(sc_card_t *card, sc_file_t *file, const u8 *buf,
size_t len)
{
const u8 *p = buf;
while (len != 0) {
unsigned int amode, tlen = 3;
if (len < 5 && p[0] != 0x80 && p[1] != 0x01) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid access mode encoding");
return SC_ERROR_INTERNAL;
}
amode = p[2];
if (p[3] == 0x90 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NONE);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0x97 && p[4] == 0x00) {
int r = set_sec_attr(file, amode, 0, SC_AC_NEVER);
if (r != SC_SUCCESS)
return r;
tlen += 2;
} else if (p[3] == 0xA0 && len >= 4U + p[4]) {
/* TODO: support OR expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else if (p[3] == 0xAF && len >= 4U + p[4]) {
/* TODO: support AND expressions */
int r = set_sec_attr(file, amode, p[5], SC_AC_CHV);
if (r != SC_SUCCESS)
return r;
tlen += 2 + p[4]; /* FIXME */
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid security condition");
return SC_ERROR_INTERNAL;
}
p += tlen;
len -= tlen;
}
return SC_SUCCESS;
}
/* sets a TLV encoded path as returned from GET DATA in a sc_path_t object
*/
static int asepcos_tlvpath_to_scpath(sc_path_t *out, const u8 *in, size_t in_len)
{
int r;
size_t len = in_len;
memset(out, 0, sizeof(sc_path_t));
while (len != 0) {
if (len < 4)
return SC_ERROR_INTERNAL;
if (in[0] != 0x8b || in[1] != 0x02)
return SC_ERROR_INVALID_ASN1_OBJECT;
/* append file id to the path */
r = sc_append_path_id(out, &in[2], 2);
if (r != SC_SUCCESS)
return r;
len -= 4;
in += 4;
}
out->type = SC_PATH_TYPE_PATH;
return SC_SUCCESS;
}
/* returns the currently selected DF (if a EF is currently selected
* it returns the path from the MF to the DF in which the EF is
* located.
* @param card sc_card_t object to use
* @param path OUT path from the MF to the current DF
* @return SC_SUCCESS on success and an error value otherwise
*/
static int asepcos_get_current_df_path(sc_card_t *card, sc_path_t *path)
{
int r;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x83);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
return asepcos_tlvpath_to_scpath(path, apdu.resp, apdu.resplen);
}
/* SELECT FILE: call the ISO SELECT FILE implementation and parse
* asepcos specific security attributes.
*/
static int asepcos_select_file(sc_card_t *card, const sc_path_t *in_path,
sc_file_t **file)
{
int r;
sc_path_t npath = *in_path;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (in_path->type == SC_PATH_TYPE_PATH) {
/* check the current DF to avoid unnecessary re-selection of
* the MF (as this might invalidate a security status) */
sc_path_t tpath;
r = asepcos_get_current_df_path(card, &tpath);
/* workaround: as opensc can't handle paths with file id
* and application names in it let's ignore the current
* DF if the returned path contains a unsupported tag.
*/
if (r != SC_ERROR_INVALID_ASN1_OBJECT && r != SC_SUCCESS)
return r;
if (r == SC_SUCCESS && sc_compare_path_prefix(&tpath, &npath) != 0) {
/* remove the currently selected DF from the path */
if (tpath.len == npath.len) {
/* we are already in the requested DF */
if (file == NULL)
/* no file information requested =>
* nothing to do */
return SC_SUCCESS;
} else {
/* shorten path */
r = sc_path_set(&npath, 0, &in_path->value[tpath.len],
npath.len - tpath.len, 0, 0);
if (r != SC_SUCCESS)
return r;
if (npath.len == 2)
npath.type = SC_PATH_TYPE_FILE_ID;
else
npath.type = SC_PATH_TYPE_PATH;
}
}
}
r = iso_ops->select_file(card, &npath, file);
/* XXX: this doesn't look right */
if (file != NULL && *file != NULL)
if ((*file)->ef_structure == SC_FILE_EF_UNKNOWN)
(*file)->ef_structure = SC_FILE_EF_TRANSPARENT;
if (r == SC_SUCCESS && file != NULL && *file != NULL) {
r = asepcos_parse_sec_attr(card, *file, (*file)->sec_attr, (*file)->sec_attr_len);
if (r != SC_SUCCESS)
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error parsing security attributes");
}
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
static int asepcos_set_security_env(sc_card_t *card,
const sc_security_env_t *env, int se_num)
{
return SC_SUCCESS;
}
static int asepcos_akn_to_fileid(sc_card_t *card, sc_cardctl_asepcos_akn2fileid_t *p)
{
int r;
u8 sbuf[32], rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
sbuf[0] = p->akn & 0xff;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x28, 0x02, 0x01);
apdu.cla |= 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
apdu.lc = 1;
apdu.datalen = 1;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.resplen != 4)
return SC_ERROR_INTERNAL;
p->fileid = (apdu.resp[1] << 16) | (apdu.resp[2] << 8) | apdu.resp[3];
return SC_SUCCESS;
}
/* sets the security attribute of a EF/DF
*/
static int asepcos_set_sec_attributes(sc_card_t *card, const u8 *data, size_t len,
int is_ef)
{
int r, type = is_ef != 0 ? 0x02 : 0x04;
sc_apdu_t apdu;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x8a, type, 0xab);
apdu.cla |= 0x80;
apdu.lc = len;
apdu.datalen = len;
apdu.data = data;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
/* encodes the opensc file attributes into the card specific format
*/
static int asepcos_set_security_attributes(sc_card_t *card, sc_file_t *file)
{
size_t i;
const amode_entry_t *table;
u8 buf[64], *p;
int r = SC_SUCCESS;
/* first check whether the security attributes in encoded form
* are already set. If present use these */
if (file->sec_attr != NULL && file->sec_attr_len != 0)
return asepcos_set_sec_attributes(card, file->sec_attr,
file->sec_attr_len, file->type == SC_FILE_TYPE_DF ? 0:1);
/* otherwise construct the ACL from the opensc ACLs */
if (file->type == SC_FILE_TYPE_DF)
table = df_amode_table;
else if (file->type == SC_FILE_TYPE_WORKING_EF)
table = wef_amode_table;
else if (file->type == SC_FILE_TYPE_INTERNAL_EF)
table = ief_amode_table;
else
return SC_ERROR_INVALID_ARGUMENTS;
p = buf;
for (i = 0; table[i].am != 0; i++) {
const struct sc_acl_entry *ent = sc_file_get_acl_entry(file, table[i].sc);
if (ent == NULL)
continue;
*p++ = 0x80;
*p++ = 0x01;
*p++ = table[i].am & 0xff;
if (ent->method == SC_AC_NONE) {
*p++ = 0x90;
*p++ = 0x00;
} else if (ent->method == SC_AC_NEVER) {
*p++ = 0x97;
*p++ = 0x00;
} else if (ent->method == SC_AC_CHV) {
sc_cardctl_asepcos_akn2fileid_t st;
st.akn = ent->key_ref;
r = asepcos_akn_to_fileid(card, &st);
if (r != SC_SUCCESS)
return r;
*p++ = 0xa0;
*p++ = 0x05;
*p++ = 0x89;
*p++ = 0x03;
*p++ = (st.fileid >> 16) & 0xff;
*p++ = (st.fileid >> 8 ) & 0xff;
*p++ = st.fileid & 0xff;
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unknown auth method: '%d'", ent->method);
return SC_ERROR_INTERNAL;
}
}
if (p != buf)
r = asepcos_set_sec_attributes(card, buf, p-buf, file->type == SC_FILE_TYPE_DF ? 0:1);
return r;
}
static int asepcos_decipher(sc_card_t *card, const u8 * crgram, size_t crgram_len,
u8 * out, size_t outlen)
{
int r;
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
/* call RSA ENCRYPT DECRYPT for the decipher operation */
sc_format_apdu(card, &apdu, SC_APDU_CASE_4, 0x14, 0x01, 0x00);
apdu.cla |= 0x80;
apdu.resp = out;
apdu.resplen = outlen;
/* if less than 256 bytes are expected than set Le to 0x00
* to tell the card the we want everything available (note: we
* always have Le <= crgram_len) */
apdu.le = (outlen >= 256 && crgram_len < 256) ? 256 : outlen;
apdu.data = crgram;
apdu.lc = crgram_len;
apdu.datalen = crgram_len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, sc_check_sw(card, apdu.sw1, apdu.sw2));
return apdu.resplen;
}
/* compute the signature. Currently the RSA ENCRYPT DECRYPT command
* is used here (TODO: use the key attributes to determine method
* to use for signature generation).
*/
static int asepcos_compute_signature(sc_card_t *card, const u8 *data, size_t datalen,
u8 *out, size_t outlen)
{
int r = SC_SUCCESS, atype;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_apdu_t apdu;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_NORMAL);
if (datalen >= 256)
atype = SC_APDU_CASE_4_EXT;
else
atype = SC_APDU_CASE_4_SHORT;
sc_format_apdu(card, &apdu, atype, 0x14, 0x01, 0x00);
apdu.cla |= 0x80;
apdu.lc = datalen;
apdu.datalen = datalen;
apdu.data = data;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error creating signature");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
if (apdu.resplen > outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
memcpy(out, apdu.resp, apdu.resplen);
return apdu.resplen;
}
/* activates the EF/DF specified in the file id.
*/
static int asepcos_activate_file(sc_card_t *card, int fileid, int is_ef)
{
int r, type = is_ef != 0 ? 2 : 1;
sc_apdu_t apdu;
u8 sbuf[2];
sbuf[0] = (fileid >> 8) & 0xff;
sbuf[1] = fileid & 0xff;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x44, type, 0x00);
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
/* CREATE FILE: creates wEF, iEF and DFs. Note: although the ISO
* command is used for wEF and iEF so format of the data send to
* the card is asepcos specific.
* @param card the sc_card_t object to use
* @param file sc_file_t object describing the file to create
* @return SC_SUCCESS on success and an error code otherwise.
*/
static int asepcos_create_file(sc_card_t *card, sc_file_t *file)
{
if (file->type == SC_FILE_TYPE_DF) {
int r, type;
sc_apdu_t apdu;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p = &sbuf[0];
*p++ = (file->id >> 8) & 0xff;
*p++ = file->id & 0xff;
if (file->size > 0xffff) {
*p++ = (file->size >> 24) & 0xff;
*p++ = (file->size >> 16) & 0xff;
*p++ = (file->size >> 8 ) & 0xff;
*p++ = file->size & 0xff;
type = 1;
} else {
*p++ = (file->size >> 8) & 0xff;
*p++ = file->size & 0xff;
type = 0;
}
if (file->namelen != 0 && file->namelen <= 16) {
memcpy(p, file->name, file->namelen);
p += file->namelen;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe0, 0x38, type);
apdu.cla |= 0x80;
apdu.lc = p - sbuf;
apdu.datalen = p - sbuf;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
r = sc_select_file(card, &file->path, NULL);
if (r != SC_SUCCESS)
return r;
/* set security attributes */
r = asepcos_set_security_attributes(card, file);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes");
return r;
}
return SC_SUCCESS;
} else if (file->type == SC_FILE_TYPE_WORKING_EF) {
int r;
sc_apdu_t apdu;
u8 descr_byte = file->ef_structure & 7;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE], *p = &sbuf[0];
*p++ = 0x85;
p++;
/* file id */
*p++ = (file->id >> 8) & 0xff;
*p++ = file->id & 0xff;
/* record size */
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
*p++ = 0x00;
*p++ = 0x00;
} else {
*p++ = (file->record_length >> 8) & 0xff;
*p++ = file->record_length & 0xff;
}
/* number of records or file size */
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
*p++ = (file->size >> 8) & 0xff;
*p++ = file->size & 0xff;
} else {
*p++ = (file->record_count >> 8) & 0xff;
*p++ = file->record_count & 0xff;
}
/* set the length of the inner TLV object */
sbuf[1] = p - sbuf - 2; /* FIXME */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xe0, descr_byte, 0x00);
apdu.lc = p - sbuf;
apdu.datalen = p - sbuf;
apdu.data = sbuf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
/* set security attributes */
r = asepcos_set_security_attributes(card, file);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes");
return r;
}
return asepcos_activate_file(card, file->id, 1);
} else if (file->type == SC_FILE_TYPE_INTERNAL_EF) {
/* for internal EF we 'misuse' the prop_attr field of the
* sc_file_t object to store the data send to the card in
* the CREATE EF call.
*/
int r, atype = SC_APDU_CASE_3_SHORT;
sc_apdu_t apdu;
if (file->prop_attr_len > 255)
atype = SC_APDU_CASE_3_EXT;
sc_format_apdu(card, &apdu, atype, 0xe0, 0x08, 0x00);
apdu.lc = file->prop_attr_len;
apdu.datalen = file->prop_attr_len;
apdu.data = file->prop_attr;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return sc_check_sw(card, apdu.sw1, apdu.sw2);
/* set security attributes */
r = asepcos_set_security_attributes(card, file);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to set security attributes");
return r;
}
return asepcos_activate_file(card, file->id, 1);
} else
return SC_ERROR_INVALID_ARGUMENTS;
}
/* list files: the function first calls GET DATA to get the current
* working DF. It then re-selects the DF to get proprietary FCI which
* contain the FID of the first child DF EF.
* The FID of the other EFs/DFs within the selected DF are then
* obtained by selecting the know FIDs to get next child EF/DF.
* @param card the sc_card_t object to use
* @param buff the output buffer for the list of FIDs
* @param blen the length of the buffer
* @return the number of FIDs read on success and an error value otherwise.
*/
static int asepcos_list_files(sc_card_t *card, u8 *buf, size_t blen)
{
int r, rv = 0, dfFID, efFID;
sc_path_t bpath, tpath;
sc_file_t *tfile = NULL;
/* 1. get currently selected DF */
r = asepcos_get_current_df_path(card, &bpath);
if (r != SC_SUCCESS)
return r;
/* 2. re-select DF to get the FID of the child EFs/DFs */
r = sc_select_file(card, &bpath, &tfile);
if (r != SC_SUCCESS)
return r;
if (tfile->prop_attr_len != 6 || tfile->prop_attr == NULL) {
sc_file_free(tfile);
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unable to parse proprietary FCI attributes");
return SC_ERROR_INTERNAL;
}
dfFID = (tfile->prop_attr[2] << 8) | tfile->prop_attr[3];
efFID = (tfile->prop_attr[4] << 8) | tfile->prop_attr[5];
sc_file_free(tfile);
/* 3. select every child DF to get the FID of the next child DF */
while (dfFID != 0) {
/* put DF FID on the list */
if (blen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*buf++ = (dfFID >> 8) & 0xff;
*buf++ = dfFID & 0xff;
rv += 2;
blen -= 2;
/* select DF to get next DF FID */
tpath = bpath;
r = sc_append_file_id(&tpath, dfFID);
if (r != SC_SUCCESS)
return r;
r = sc_select_file(card, &tpath, &tfile);
if (r != SC_SUCCESS)
return r;
if (tfile->prop_attr_len != 6 || tfile->prop_attr == NULL)
return SC_ERROR_INTERNAL;
dfFID = (tfile->prop_attr[0] << 8) | tfile->prop_attr[1];
sc_file_free(tfile);
}
/* 4. select every child EF ... */
while (efFID != 0) {
/* put DF FID on the list */
if (blen < 2)
return SC_ERROR_BUFFER_TOO_SMALL;
*buf++ = (efFID >> 8) & 0xff;
*buf++ = efFID & 0xff;
rv += 2;
blen -= 2;
/* select EF to get next EF FID */
tpath = bpath;
r = sc_append_file_id(&tpath, efFID);
if (r != SC_SUCCESS)
return r;
r = sc_select_file(card, &tpath, &tfile);
if (r != SC_SUCCESS)
return r;
if (tfile->prop_attr_len < 2 || tfile->prop_attr == NULL)
return SC_ERROR_INTERNAL;
efFID = (tfile->prop_attr[0] << 8) | tfile->prop_attr[1];
sc_file_free(tfile);
}
return rv;
}
static int asepcos_delete_file(sc_card_t *card, const sc_path_t *path)
{
int r, ftype, atype;
sc_apdu_t apdu;
u8 buf[SC_MAX_APDU_BUFFER_SIZE];
/* use GET DATA to determine whether it is a DF or EF */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x84);
apdu.le = 256;
apdu.resplen = sizeof(buf);
apdu.resp = buf;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00) {
/* looks like a EF */
atype = SC_APDU_CASE_3_SHORT;
ftype = 0x02;
buf[0] = path->value[path->len-2];
buf[1] = path->value[path->len-1];
} else {
/* presumably a DF */
atype = SC_APDU_CASE_1;
ftype = 0x00;
}
sc_format_apdu(card, &apdu, atype, 0xe4, ftype, 0x00);
if (atype == SC_APDU_CASE_3_SHORT) {
apdu.lc = 2;
apdu.datalen = 2;
apdu.data = buf;
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
/* returns the default transport key (note: this should be put in the
* pkcs15 profile file).
*/
static int asepcos_get_default_key(sc_card_t *card,
struct sc_cardctl_default_key *data)
{
static const u8 asepcos_def_key[] = {0x41,0x53,0x45,0x43,0x41,0x52,0x44,0x2b};
if (data->method != SC_AC_CHV && data->method != SC_AC_AUT)
return SC_ERROR_NO_DEFAULT_KEY;
if (data->key_data == NULL || data->len < sizeof(asepcos_def_key))
return SC_ERROR_BUFFER_TOO_SMALL;
memcpy(data->key_data, asepcos_def_key, sizeof(asepcos_def_key));
data->len = sizeof(asepcos_def_key);
return SC_SUCCESS;
}
static int asepcos_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
sc_apdu_t apdu;
u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xca, 0x01, 0x14);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
if (apdu.resplen != 8) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "unexpected response to GET DATA serial number\n");
return SC_ERROR_INTERNAL;
}
/* cache serial number */
memcpy(card->serialnr.value, rbuf, 8);
card->serialnr.len = 8;
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
static int asepcos_change_key(sc_card_t *card, sc_cardctl_asepcos_change_key_t *p)
{
int r, atype;
sc_apdu_t apdu;
if (p->datalen > 255)
atype = SC_APDU_CASE_3_EXT;
else
atype = SC_APDU_CASE_3_SHORT;
sc_format_apdu(card, &apdu, atype, 0x24, 0x01, 0x80);
apdu.lc = p->datalen;
apdu.datalen = p->datalen;
apdu.data = p->data;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
return sc_check_sw(card, apdu.sw1, apdu.sw2);
}
static int asepcos_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_GET_DEFAULT_KEY:
return asepcos_get_default_key(card, (struct sc_cardctl_default_key *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return asepcos_get_serialnr(card, (sc_serial_number_t *)ptr);
case SC_CARDCTL_ASEPCOS_CHANGE_KEY:
return asepcos_change_key(card, (sc_cardctl_asepcos_change_key_t*)ptr);
case SC_CARDCTL_ASEPCOS_AKN2FILEID:
return asepcos_akn_to_fileid(card, (sc_cardctl_asepcos_akn2fileid_t*)ptr);
case SC_CARDCTL_ASEPCOS_SET_SATTR:
return asepcos_set_security_attributes(card, (sc_file_t*)ptr);
case SC_CARDCTL_ASEPCOS_ACTIVATE_FILE:
return asepcos_activate_file(card, ((sc_cardctl_asepcos_activate_file_t*)ptr)->fileid,
((sc_cardctl_asepcos_activate_file_t *)ptr)->is_ef);
}
return SC_ERROR_NOT_SUPPORTED;
}
/* build the different APDUs for the PIN handling commands
*/
static int asepcos_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu,
struct sc_pin_cmd_data *data, u8 *buf, size_t buf_len,
unsigned int cmd, int is_puk)
{
int r, fileid;
u8 *p = buf;
sc_cardctl_asepcos_akn2fileid_t st;
switch (cmd) {
case SC_PIN_CMD_VERIFY:
st.akn = data->pin_reference;
r = asepcos_akn_to_fileid(card, &st);
if (r != SC_SUCCESS)
return r;
fileid = st.fileid;
/* the fileid of the puk is the fileid of the pin + 1 */
if (is_puk != 0)
fileid++;
sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x20, 0x02, 0x80);
*p++ = (fileid >> 24) & 0xff;
*p++ = (fileid >> 16) & 0xff;
*p++ = (fileid >> 8 ) & 0xff;
*p++ = fileid & 0xff;
memcpy(p, data->pin1.data, data->pin1.len);
p += data->pin1.len;
apdu->lc = p - buf;
apdu->datalen = p - buf;
apdu->data = buf;
break;
case SC_PIN_CMD_CHANGE:
/* build the CHANGE KEY apdu. Note: the PIN file is implicitly
* selected by its SFID */
*p++ = 0x81;
*p++ = data->pin2.len & 0xff;
memcpy(p, data->pin2.data, data->pin2.len);
p += data->pin2.len;
st.akn = data->pin_reference;
r = asepcos_akn_to_fileid(card, &st);
if (r != SC_SUCCESS)
return r;
fileid = 0x80 | (st.fileid & 0x1f);
sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, fileid);
apdu->lc = p - buf;
apdu->datalen = p - buf;
apdu->data = buf;
break;
case SC_PIN_CMD_UNBLOCK:
/* build the UNBLOCK KEY apdu. The PIN file is implicitly
* selected by its SFID. The new PIN is provided in the
* data field of the UNBLOCK KEY command. */
*p++ = 0x81;
*p++ = data->pin2.len & 0xff;
memcpy(p, data->pin2.data, data->pin2.len);
p += data->pin2.len;
st.akn = data->pin_reference;
r = asepcos_akn_to_fileid(card, &st);
if (r != SC_SUCCESS)
return r;
fileid = 0x80 | (st.fileid & 0x1f);
sc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, fileid);
apdu->lc = p - buf;
apdu->datalen = p - buf;
apdu->data = buf;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
return SC_SUCCESS;
}
/* generic function to handle the different PIN operations, i.e verify
* change and unblock.
*/
static int asepcos_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *pdata,
int *tries_left)
{
sc_apdu_t apdu;
int r = SC_SUCCESS;
u8 sbuf[SC_MAX_APDU_BUFFER_SIZE];
if (tries_left)
*tries_left = -1;
/* only PIN verification is supported at the moment */
/* check PIN length */
if (pdata->pin1.len < 4 || pdata->pin1.len > 16) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN1 length");
return SC_ERROR_INVALID_PIN_LENGTH;
}
switch (pdata->cmd) {
case SC_PIN_CMD_VERIFY:
if (pdata->pin_type != SC_AC_CHV && pdata->pin_type != SC_AC_AUT)
return SC_ERROR_INVALID_ARGUMENTS;
/* 'AUT' key is the transport PIN and should have reference '0' */
if (pdata->pin_type == SC_AC_AUT && pdata->pin_reference)
return SC_ERROR_INVALID_ARGUMENTS;
/* build verify APDU and send it to the card */
r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 0);
if (r != SC_SUCCESS)
break;
r = sc_transmit_apdu(card, &apdu);
if (r != SC_SUCCESS)
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed");
break;
case SC_PIN_CMD_CHANGE:
if (pdata->pin_type != SC_AC_CHV)
return SC_ERROR_INVALID_ARGUMENTS;
if (pdata->pin2.len < 4 || pdata->pin2.len > 16) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN2 length");
return SC_ERROR_INVALID_PIN_LENGTH;
}
/* 1. step: verify the old pin */
r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 0);
if (r != SC_SUCCESS)
break;
r = sc_transmit_apdu(card, &apdu);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed");
break;
}
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00) {
/* unable to verify the old PIN */
break;
}
/* 2, step: use CHANGE KEY to update the PIN */
r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_CHANGE, 0);
if (r != SC_SUCCESS)
break;
r = sc_transmit_apdu(card, &apdu);
if (r != SC_SUCCESS)
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed");
break;
case SC_PIN_CMD_UNBLOCK:
if (pdata->pin_type != SC_AC_CHV)
return SC_ERROR_INVALID_ARGUMENTS;
if (pdata->pin2.len < 4 || pdata->pin2.len > 16) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "invalid PIN2 length");
return SC_ERROR_INVALID_PIN_LENGTH;
}
/* 1. step: verify the puk */
r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_VERIFY, 1);
if (r != SC_SUCCESS)
break;
r = sc_transmit_apdu(card, &apdu);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed");
break;
}
/* 2, step: unblock and change the pin */
r = asepcos_build_pin_apdu(card, &apdu, pdata, sbuf, sizeof(sbuf), SC_PIN_CMD_UNBLOCK, 0);
if (r != SC_SUCCESS)
break;
r = sc_transmit_apdu(card, &apdu);
if (r != SC_SUCCESS) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed");
break;
}
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "error: unknown cmd type");
return SC_ERROR_INTERNAL;
}
/* Clear the buffer - it may contain pins */
sc_mem_clear(sbuf, sizeof(sbuf));
/* check for remaining tries if verification failed */
if (r == SC_SUCCESS) {
if (apdu.sw1 == 0x63) {
if ((apdu.sw2 & 0xF0) == 0xC0 && tries_left != NULL)
*tries_left = apdu.sw2 & 0x0F;
r = SC_ERROR_PIN_CODE_INCORRECT;
return r;
}
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
}
return r;
}
static int asepcos_card_reader_lock_obtained(sc_card_t *card, int was_reset)
{
int r = SC_SUCCESS;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (was_reset > 0 && card->type == SC_CARD_TYPE_ASEPCOS_JAVA) {
/* in case of a Java card try to select the ASEPCOS applet */
r = asepcos_select_asepcos_applet(card);
}
LOG_FUNC_RETURN(card->ctx, r);
}
static struct sc_card_driver * sc_get_driver(void)
{
if (iso_ops == NULL)
iso_ops = sc_get_iso7816_driver()->ops;
asepcos_ops = *iso_ops;
asepcos_ops.match_card = asepcos_match_card;
asepcos_ops.init = asepcos_init;
asepcos_ops.select_file = asepcos_select_file;
asepcos_ops.set_security_env = asepcos_set_security_env;
asepcos_ops.decipher = asepcos_decipher;
asepcos_ops.compute_signature = asepcos_compute_signature;
asepcos_ops.create_file = asepcos_create_file;
asepcos_ops.delete_file = asepcos_delete_file;
asepcos_ops.list_files = asepcos_list_files;
asepcos_ops.card_ctl = asepcos_card_ctl;
asepcos_ops.pin_cmd = asepcos_pin_cmd;
asepcos_ops.card_reader_lock_obtained = asepcos_card_reader_lock_obtained;
return &asepcos_drv;
}
struct sc_card_driver * sc_get_asepcos_driver(void)
{
return sc_get_driver();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_1 |
crossvul-cpp_data_bad_508_2 | /* $Id$ */
/*
* Copyright (c) 2001-2010 Aaron Turner <aturner at synfin dot net>
* Copyright (c) 2013-2018 Fred Klassen <tcpreplay at appneta dot com> - AppNeta
*
* The Tcpreplay Suite of tools 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 with the authors permission any later version.
*
* The Tcpreplay Suite 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 the Tcpreplay Suite. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "defines.h"
#include "common.h"
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef DEBUG
extern int debug;
#endif
/**
* this is wrapped up in a #define safe_malloc
* This function, detects failures to malloc memory and zeros out the
* memory before returning
*/
void *
_our_safe_malloc(size_t len, const char *funcname, const int line, const char *file)
{
u_char *ptr;
if ((ptr = malloc(len)) == NULL) {
fprintf(stderr, "ERROR in %s:%s() line %d: Unable to malloc() %zu bytes/n",
file, funcname, line, len);
exit(-1);
}
/* zero memory */
memset(ptr, 0, len);
/* wrapped inside an #ifdef for better performance */
dbgx(5, "Malloc'd %zu bytes in %s:%s() line %d", len, file, funcname, line);
return (void *)ptr;
}
/**
* this is wrapped up in a #define safe_realloc
* This function, detects failures to realloc memory and zeros
* out the NEW memory if len > current len. As always, remember
* to use it as:
* ptr = safe_realloc(ptr, size)
*/
void *
_our_safe_realloc(void *ptr, size_t len, const char *funcname, const int line, const char *file)
{
if ((ptr = realloc(ptr, len)) == NULL) {
fprintf(stderr, "ERROR: in %s:%s() line %d: Unable to remalloc() buffer to %zu bytes", file, funcname, line, len);
exit(-1);
}
dbgx(5, "Remalloc'd buffer to %zu bytes in %s:%s() line %d", len, file, funcname, line);
return ptr;
}
/**
* this is wrapped up in a #define safe_strdup
* This function, detects failures to realloc memory
*/
char *
_our_safe_strdup(const char *str, const char *funcname, const int line, const char *file)
{
char *newstr;
if ((newstr = (char *)malloc(strlen(str) + 1)) == NULL) {
fprintf(stderr, "ERROR in %s:%s() line %d: Unable to strdup() %zu bytes\n", file, funcname, line, strlen(str));
exit(-1);
}
memcpy(newstr, str, strlen(str) + 1);
return newstr;
}
/**
* calls free and sets to NULL.
*/
void
_our_safe_free(void *ptr, const char *funcname, const int line, const char *file)
{
assert(funcname);
assert(line);
assert(file);
if (ptr == NULL)
return;
free(ptr);
}
/**
* get next packet in pcap file
*/
u_char *_our_safe_pcap_next(pcap_t *pcap, struct pcap_pkthdr *pkthdr,
const char *funcname, const int line, const char *file)
{
u_char *pktdata = (u_char *)pcap_next(pcap, pkthdr);
if (pktdata) {
if (pkthdr->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, pkthdr->len, MAXPACKET);
exit(-1);
}
if (pkthdr->len < pkthdr->caplen) {
fprintf(stderr, "safe_pcap_next ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, pkthdr->len, pkthdr->caplen);
exit(-1);
}
}
return pktdata;
}
/**
* get next packet in pcap file (extended)
*/
int _our_safe_pcap_next_ex(pcap_t *pcap, struct pcap_pkthdr **pkthdr,
const u_char **pktdata, const char *funcname,
const int line, const char *file)
{
int res = pcap_next_ex(pcap, pkthdr, pktdata);
if (*pktdata && *pkthdr) {
if ((*pkthdr)->len > MAXPACKET) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: %u is greater than maximum %u\n",
file, funcname, line, (*pkthdr)->len, MAXPACKET);
exit(-1);
}
if ((*pkthdr)->len < (*pkthdr)->caplen) {
fprintf(stderr, "safe_pcap_next_ex ERROR: Invalid packet length in %s:%s() line %d: packet length %u is less than capture length %u\n",
file, funcname, line, (*pkthdr)->len, (*pkthdr)->caplen);
exit(-1);
}
}
return res;
}
/**
* Print various packet statistics
*/
void
packet_stats(const tcpreplay_stats_t *stats)
{
struct timeval diff;
COUNTER diff_us;
COUNTER bytes_sec = 0;
u_int32_t bytes_sec_10ths = 0;
COUNTER mb_sec = 0;
u_int32_t mb_sec_100ths = 0;
u_int32_t mb_sec_1000ths = 0;
COUNTER pkts_sec = 0;
u_int32_t pkts_sec_100ths = 0;
timersub(&stats->end_time, &stats->start_time, &diff);
diff_us = TIMEVAL_TO_MICROSEC(&diff);
if (diff_us && stats->pkts_sent && stats->bytes_sent) {
COUNTER bytes_sec_X10;
COUNTER pkts_sec_X100;
COUNTER mb_sec_X1000;
COUNTER mb_sec_X100;
if (stats->bytes_sent > 1000 * 1000 * 1000 && diff_us > 1000 * 1000) {
bytes_sec_X10 = (stats->bytes_sent * 10 * 1000) / (diff_us / 1000);
pkts_sec_X100 = (stats->pkts_sent * 100 * 1000) / (diff_us / 1000);
} else {
bytes_sec_X10 = (stats->bytes_sent * 10 * 1000 * 1000) / diff_us;
pkts_sec_X100 = (stats->pkts_sent * 100 * 1000 * 1000) / diff_us;
}
bytes_sec = bytes_sec_X10 / 10;
bytes_sec_10ths = bytes_sec_X10 % 10;
mb_sec_X1000 = (bytes_sec * 8) / 1000;
mb_sec_X100 = mb_sec_X1000 / 10;
mb_sec = mb_sec_X1000 / 1000;
mb_sec_100ths = mb_sec_X100 % 100;
mb_sec_1000ths = mb_sec_X1000 % 1000;
pkts_sec = pkts_sec_X100 / 100;
pkts_sec_100ths = pkts_sec_X100 % 100;
}
if (diff_us >= 1000 * 1000)
printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%02zd seconds\n",
stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)(diff.tv_usec / (10 * 1000)));
else
printf("Actual: " COUNTER_SPEC " packets (" COUNTER_SPEC " bytes) sent in %zd.%06zd seconds\n",
stats->pkts_sent, stats->bytes_sent, (ssize_t)diff.tv_sec, (ssize_t)diff.tv_usec);
if (mb_sec >= 1)
printf("Rated: %llu.%1u Bps, %llu.%02u Mbps, %llu.%02u pps\n",
bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_100ths, pkts_sec, pkts_sec_100ths);
else
printf("Rated: %llu.%1u Bps, %llu.%03u Mbps, %llu.%02u pps\n",
bytes_sec, bytes_sec_10ths, mb_sec, mb_sec_1000ths, pkts_sec, pkts_sec_100ths);
fflush(NULL);
if (stats->failed)
printf("Failed write attempts: " COUNTER_SPEC "\n",
stats->failed);
}
/**
* fills a buffer with a string representing the given time
*
* @param when: the time that should be formatted
* @param buf: a buffer to write to
* @param len: length of the buffer
* @return: string containing date, or -1 on error
*/
int format_date_time(struct timeval *when, char *buf, size_t len)
{
struct tm *tm;
char tmp[64];
assert(len);
tm = localtime(&when->tv_sec);
if (!tm)
return -1;
strftime(tmp, sizeof tmp, "%Y-%m-%d %H:%M:%S.%%06u", tm);
return snprintf(buf, len, tmp, when->tv_usec);
}
/**
* reads a hexstring in the format of xx,xx,xx,xx spits it back into *hex
* up to hexlen bytes. Returns actual number of bytes returned. On error
* it just calls errx() since all errors are fatal.
*/
int
read_hexstring(const char *l2string, u_char *hex, const int hexlen)
{
int numbytes = 0;
unsigned int value;
char *l2byte;
u_char databyte;
char *token = NULL;
char *string;
string = safe_strdup(l2string);
if (hexlen <= 0)
err(-1, "Hex buffer must be > 0");
memset(hex, '\0', hexlen);
/* data is hex, comma seperated, byte by byte */
/* get the first byte */
l2byte = strtok_r(string, ",", &token);
sscanf(l2byte, "%x", &value);
if (value > 0xff)
errx(-1, "Invalid hex string byte: %s", l2byte);
databyte = (u_char) value;
memcpy(&hex[numbytes], &databyte, 1);
/* get remaining bytes */
while ((l2byte = strtok_r(NULL, ",", &token)) != NULL) {
numbytes++;
if (numbytes + 1 > hexlen) {
warn("Hex buffer too small for data- skipping data");
goto done;
}
sscanf(l2byte, "%x", &value);
if (value > 0xff)
errx(-1, "Invalid hex string byte: %s", l2byte);
databyte = (u_char) value;
memcpy(&hex[numbytes], &databyte, 1);
}
numbytes++;
done:
safe_free(string);
dbgx(1, "Read %d bytes of hex data", numbytes);
return (numbytes);
}
#ifdef USE_CUSTOM_INET_ATON
int
inet_aton(const char *name, struct in_addr *addr)
{
in_addr_t a = inet_addr(name);
addr->s_addr = a;
return a != (in_addr_t)-1;
}
#endif
#if SIZEOF_LONG == 4
uint32_t __div64_32(uint64_t *n, uint32_t base)
{
uint64_t rem = *n;
uint64_t b = base;
uint64_t res, d = 1;
uint32_t high = rem >> 32;
/* Reduce the thing a bit first */
res = 0;
if (high >= base) {
high /= base;
res = (uint64_t) high << 32;
rem -= (uint64_t) (high*base) << 32;
}
while ((int64_t)b > 0 && b < rem) {
b = b+b;
d = d+d;
}
do {
if (rem >= b) {
rem -= b;
res += d;
}
b >>= 1;
d >>= 1;
} while (d);
*n = res;
return rem;
}
#endif /* SIZEOF_LONG == 4 */
/**
* Implementation of rand_r that is consistent across all platforms
* This algorithm is mentioned in the ISO C standard, here extended
* for 32 bits.
* @param: seed
* @return: random number
*/
uint32_t tcpr_random(uint32_t *seed)
{
unsigned int next = *seed;
int result;
next *= 1103515245;
next += 12345;
result = (unsigned int) (next / 65536) % 2048;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
next *= 1103515245;
next += 12345;
result <<= 10;
result ^= (unsigned int) (next / 65536) % 1024;
*seed = next;
return result;
}
/**
* #416 - Ensure STDIN is not left in non-blocking mode after closing
* a program. BSD and Unix derivatives should utilize `FIONBIO` due to known
* issues with reading from tty with a 0 byte read returning -1 opposed to 0.
*/
void restore_stdin(void)
{
#ifdef FIONBIO
int nb = 0;
ioctl(0, FIONBIO, &nb);
#else
fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
#endif /* FIONBIO */
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_508_2 |
crossvul-cpp_data_bad_2804_1 | #ifndef IGNOREALL
/*
dcraw.c -- Dave Coffin's raw photo decoder
Copyright 1997-2015 by Dave Coffin, dcoffin a cybercom o net
This is a command-line ANSI C program to convert raw photos from
any digital camera on any computer running any operating system.
No license is required to download and use dcraw.c. However,
to lawfully redistribute dcraw, you must either (a) offer, at
no extra charge, full source code* for all executable files
containing RESTRICTED functions, (b) distribute this code under
the GPL Version 2 or later, (c) remove all RESTRICTED functions,
re-implement them, or copy them from an earlier, unrestricted
Revision of dcraw.c, or (d) purchase a license from the author.
The functions that process Foveon images have been RESTRICTED
since Revision 1.237. All other code remains free for all uses.
*If you have not modified dcraw.c in any way, a link to my
homepage qualifies as "full source code".
$Revision: 1.476 $
$Date: 2015/05/25 02:29:14 $
*/
/*@out DEFINES
#ifndef USE_JPEG
#define NO_JPEG
#endif
#ifndef USE_JASPER
#define NO_JASPER
#endif
@end DEFINES */
#define NO_LCMS
#define DCRAW_VERBOSE
//@out DEFINES
#define DCRAW_VERSION "9.26"
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#define _USE_MATH_DEFINES
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
//@end DEFINES
#if defined(DJGPP) || defined(__MINGW32__)
#define fseeko fseek
#define ftello ftell
#else
#define fgetc getc_unlocked
#endif
//@out DEFINES
#ifdef __CYGWIN__
#include <io.h>
#endif
#if defined WIN32 || defined (__MINGW32__)
#include <sys/utime.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define snprintf _snprintf
#define strcasecmp stricmp
#define strncasecmp strnicmp
//@end DEFINES
typedef __int64 INT64;
typedef unsigned __int64 UINT64;
//@out DEFINES
#else
#include <unistd.h>
#include <utime.h>
#include <netinet/in.h>
typedef long long INT64;
typedef unsigned long long UINT64;
#endif
#ifdef NODEPS
#define NO_JASPER
#define NO_JPEG
#define NO_LCMS
#endif
#ifndef NO_JASPER
#include <jasper/jasper.h> /* Decode Red camera movies */
#endif
#ifndef NO_JPEG
#include <jpeglib.h> /* Decode compressed Kodak DC120 photos */
#endif /* and Adobe Lossy DNGs */
#ifndef NO_LCMS
#ifdef USE_LCMS
#include <lcms.h> /* Support color profiles */
#else
#include <lcms2.h> /* Support color profiles */
#endif
#endif
#ifdef LOCALEDIR
#include <libintl.h>
#define _(String) gettext(String)
#else
#define _(String) (String)
#endif
#ifdef LJPEG_DECODE
#error Please compile dcraw.c by itself.
#error Do not link it with ljpeg_decode.
#endif
#ifndef LONG_BIT
#define LONG_BIT (8 * sizeof (long))
#endif
//@end DEFINES
#if !defined(uchar)
#define uchar unsigned char
#endif
#if !defined(ushort)
#define ushort unsigned short
#endif
/*
All global variables are defined here, and all functions that
access them are prefixed with "CLASS". Note that a thread-safe
C++ class cannot have non-const static local variables.
*/
FILE *ifp, *ofp;
short order;
const char *ifname;
char *meta_data, xtrans[6][6], xtrans_abs[6][6];
char cdesc[5], desc[512], make[64], model[64], model2[64], artist[64],software[64];
float flash_used, canon_ev, iso_speed, shutter, aperture, focal_len;
time_t timestamp;
off_t strip_offset, data_offset;
off_t thumb_offset, meta_offset, profile_offset;
unsigned shot_order, kodak_cbpp, exif_cfa, unique_id;
unsigned thumb_length, meta_length, profile_length;
unsigned thumb_misc, *oprof, fuji_layout, shot_select=0, multi_out=0;
unsigned tiff_nifds, tiff_samples, tiff_bps, tiff_compress;
unsigned black, maximum, mix_green, raw_color, zero_is_bad;
unsigned zero_after_ff, is_raw, dng_version, is_foveon, data_error;
unsigned tile_width, tile_length, gpsdata[32], load_flags;
unsigned flip, tiff_flip, filters, colors;
ushort raw_height, raw_width, height, width, top_margin, left_margin;
ushort shrink, iheight, iwidth, fuji_width, thumb_width, thumb_height;
ushort *raw_image, (*image)[4], cblack[4102];
ushort white[8][8], curve[0x10000], cr2_slice[3], sraw_mul[4];
double pixel_aspect, aber[4]={1,1,1,1}, gamm[6]={ 0.45,4.5,0,0,0,0 };
float bright=1, user_mul[4]={0,0,0,0}, threshold=0;
int mask[8][4];
int half_size=0, four_color_rgb=0, document_mode=0, highlight=0;
int verbose=0, use_auto_wb=0, use_camera_wb=0, use_camera_matrix=1;
int output_color=1, output_bps=8, output_tiff=0, med_passes=0;
int no_auto_bright=0;
unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX };
float cam_mul[4], pre_mul[4], cmatrix[3][4], rgb_cam[3][4];
const double xyz_rgb[3][3] = { /* XYZ from RGB */
{ 0.412453, 0.357580, 0.180423 },
{ 0.212671, 0.715160, 0.072169 },
{ 0.019334, 0.119193, 0.950227 } };
const float d65_white[3] = { 0.950456, 1, 1.088754 };
int histogram[4][0x2000];
void (*write_thumb)(), (*write_fun)();
void (*load_raw)(), (*thumb_load_raw)();
jmp_buf failure;
struct decode {
struct decode *branch[2];
int leaf;
} first_decode[2048], *second_decode, *free_decode;
struct tiff_ifd {
int t_width, t_height, bps, comp, phint, offset, t_flip, samples, bytes;
int t_tile_width, t_tile_length,sample_format,predictor;
float t_shutter;
} tiff_ifd[10];
struct ph1 {
int format, key_off, tag_21a;
int t_black, split_col, black_col, split_row, black_row;
float tag_210;
} ph1;
#define CLASS
//@out DEFINES
#define FORC(cnt) for (c=0; c < cnt; c++)
#define FORC3 FORC(3)
#define FORC4 FORC(4)
#define FORCC for (c=0; c < colors && c < 4; c++)
#define SQR(x) ((x)*(x))
#define ABS(x) (((int)(x) ^ ((int)(x) >> 31)) - ((int)(x) >> 31))
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define LIM(x,min,max) MAX(min,MIN(x,max))
#define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y))
#define CLIP(x) LIM((int)(x),0,65535)
#define SWAP(a,b) { a=a+b; b=a-b; a=a-b; }
#define my_swap(type, i, j) {type t = i; i = j; j = t;}
static float fMAX(float a, float b)
{
return MAX(a,b);
}
/*
In order to inline this calculation, I make the risky
assumption that all filter patterns can be described
by a repeating pattern of eight rows and two columns
Do not use the FC or BAYER macros with the Leaf CatchLight,
because its pattern is 16x16, not 2x8.
Return values are either 0/1/2/3 = G/M/C/Y or 0/1/2/3 = R/G1/B/G2
PowerShot 600 PowerShot A50 PowerShot Pro70 Pro90 & G1
0xe1e4e1e4: 0x1b4e4b1e: 0x1e4b4e1b: 0xb4b4b4b4:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 G M G M G M 0 C Y C Y C Y 0 Y C Y C Y C 0 G M G M G M
1 C Y C Y C Y 1 M G M G M G 1 M G M G M G 1 Y C Y C Y C
2 M G M G M G 2 Y C Y C Y C 2 C Y C Y C Y
3 C Y C Y C Y 3 G M G M G M 3 G M G M G M
4 C Y C Y C Y 4 Y C Y C Y C
PowerShot A5 5 G M G M G M 5 G M G M G M
0x1e4e1e4e: 6 Y C Y C Y C 6 C Y C Y C Y
7 M G M G M G 7 M G M G M G
0 1 2 3 4 5
0 C Y C Y C Y
1 G M G M G M
2 C Y C Y C Y
3 M G M G M G
All RGB cameras use one of these Bayer grids:
0x16161616: 0x61616161: 0x49494949: 0x94949494:
0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5
0 B G B G B G 0 G R G R G R 0 G B G B G B 0 R G R G R G
1 G R G R G R 1 B G B G B G 1 R G R G R G 1 G B G B G B
2 B G B G B G 2 G R G R G R 2 G B G B G B 2 R G R G R G
3 G R G R G R 3 B G B G B G 3 R G R G R G 3 G B G B G B
*/
#define RAW(row,col) \
raw_image[(row)*raw_width+(col)]
//@end DEFINES
#define FC(row,col) \
(filters >> ((((row) << 1 & 14) + ((col) & 1)) << 1) & 3)
//@out DEFINES
#define BAYER(row,col) \
image[((row) >> shrink)*iwidth + ((col) >> shrink)][FC(row,col)]
#define BAYER2(row,col) \
image[((row) >> shrink)*iwidth + ((col) >> shrink)][fcol(row,col)]
//@end DEFINES
/* @out COMMON
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#define LIBRAW_IO_REDEFINED
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end COMMON */
//@out COMMON
int CLASS fcol (int row, int col)
{
static const char filter[16][16] =
{ { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 },
{ 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 },
{ 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 },
{ 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 },
{ 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 },
{ 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 },
{ 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 },
{ 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 },
{ 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 },
{ 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 },
{ 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 },
{ 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 },
{ 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 },
{ 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 },
{ 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 },
{ 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } };
if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15];
if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6];
return FC(row,col);
}
static size_t local_strnlen(const char *s, size_t n)
{
const char *p = (const char *)memchr(s, 0, n);
return(p ? p-s : n);
}
/* add OS X version check here ?? */
#define strnlen(a,b) local_strnlen(a,b)
#ifdef LIBRAW_LIBRARY_BUILD
static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp)
{
int r = fp->read(buf,len,1);
buf[len-1] = 0;
return r;
}
#define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp)
#endif
#ifndef __GLIBC__
char *my_memmem (char *haystack, size_t haystacklen,
char *needle, size_t needlelen)
{
char *c;
for (c = haystack; c <= haystack + haystacklen - needlelen; c++)
if (!memcmp (c, needle, needlelen))
return c;
return 0;
}
#define memmem my_memmem
char *my_strcasestr (char *haystack, const char *needle)
{
char *c;
for (c = haystack; *c; c++)
if (!strncasecmp(c, needle, strlen(needle)))
return c;
return 0;
}
#define strcasestr my_strcasestr
#endif
#define strbuflen(buf) strnlen(buf,sizeof(buf)-1)
//@end COMMON
void CLASS merror (void *ptr, const char *where)
{
if (ptr) return;
fprintf (stderr,_("%s: Out of memory in %s\n"), ifname, where);
longjmp (failure, 1);
}
void CLASS derror()
{
if (!data_error) {
fprintf (stderr, "%s: ", ifname);
if (feof(ifp))
fprintf (stderr,_("Unexpected end of file\n"));
else
fprintf (stderr,_("Corrupt data near 0x%llx\n"), (INT64) ftello(ifp));
}
data_error++;
}
//@out COMMON
ushort CLASS sget2 (uchar *s)
{
if (order == 0x4949) /* "II" means little-endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian */
return s[0] << 8 | s[1];
}
// DNG was written by:
#define CameraDNG 1
#define AdobeDNG 2
#ifdef LIBRAW_LIBRARY_BUILD
static int getwords(char *line, char *words[], int maxwords,int maxlen)
{
line[maxlen-1] = 0;
char *p = line;
int nwords = 0;
while(1)
{
while(isspace(*p)) p++;
if(*p == '\0') return nwords;
words[nwords++] = p;
while(!isspace(*p) && *p != '\0') p++;
if(*p == '\0') return nwords;
*p++ = '\0';
if(nwords >= maxwords) return nwords;
}
}
static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){
if ((a >> 4) > 9) return 0;
else if ((a & 0x0f) > 9) return 0;
else if ((b >> 4) > 9) return 0;
else if ((b & 0x0f) > 9) return 0;
else if ((c >> 4) > 9) return 0;
else if ((c & 0x0f) > 9) return 0;
else if ((d >> 4) > 9) return 0;
else if ((d & 0x0f) > 9) return 0;
else if ((e >> 4) > 9) return 0;
else if ((e & 0x0f) > 9) return 0;
else if ((f >> 4) > 9) return 0;
else if ((f & 0x0f) > 9) return 0;
return 1;
}
static ushort bcd2dec(uchar data){
if ((data >> 4) > 9) return 0;
else if ((data & 0x0f) > 9) return 0;
else return (data >> 4) * 10 + (data & 0x0f);
}
static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff";
ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse
{
if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */
return s[0] | s[1] << 8;
else /* "MM" means big-endian... */
return s[0] << 8 | s[1];
}
#endif
ushort CLASS get2()
{
uchar str[2] = { 0xff,0xff };
fread (str, 1, 2, ifp);
return sget2(str);
}
unsigned CLASS sget4 (uchar *s)
{
if (order == 0x4949)
return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24;
else
return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3];
}
#define sget4(s) sget4((uchar *)s)
unsigned CLASS get4()
{
uchar str[4] = { 0xff,0xff,0xff,0xff };
fread (str, 1, 4, ifp);
return sget4(str);
}
unsigned CLASS getint (int type)
{
return type == 3 ? get2() : get4();
}
float CLASS int_to_float (int i)
{
union { int i; float f; } u;
u.i = i;
return u.f;
}
double CLASS getreal (int type)
{
union { char c[8]; double d; } u,v;
int i, rev;
switch (type) {
case 3: return (unsigned short) get2();
case 4: return (unsigned int) get4();
case 5:
u.d = (unsigned int) get4();
v.d = (unsigned int)get4();
return u.d / (v.d ? v.d : 1);
case 8: return (signed short) get2();
case 9: return (signed int) get4();
case 10:
u.d = (signed int) get4();
v.d = (signed int)get4();
return u.d / (v.d?v.d:1);
case 11: return int_to_float (get4());
case 12:
rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234));
for (i=0; i < 8; i++)
u.c[i ^ rev] = fgetc(ifp);
return u.d;
default: return fgetc(ifp);
}
}
void CLASS read_shorts (ushort *pixel, int count)
{
if (fread (pixel, 2, count, ifp) < count) derror();
if ((order == 0x4949) == (ntohs(0x1234) == 0x1234))
swab ((char*)pixel, (char*)pixel, count*2);
}
void CLASS cubic_spline (const int *x_, const int *y_, const int len)
{
float **A, *b, *c, *d, *x, *y;
int i, j;
A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len);
if (!A) return;
A[0] = (float *) (A + 2*len);
for (i = 1; i < 2*len; i++)
A[i] = A[0] + 2*len*i;
y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i))));
for (i = 0; i < len; i++) {
x[i] = x_[i] / 65535.0;
y[i] = y_[i] / 65535.0;
}
for (i = len-1; i > 0; i--) {
b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]);
d[i-1] = x[i] - x[i-1];
}
for (i = 1; i < len-1; i++) {
A[i][i] = 2 * (d[i-1] + d[i]);
if (i > 1) {
A[i][i-1] = d[i-1];
A[i-1][i] = d[i-1];
}
A[i][len-1] = 6 * (b[i+1] - b[i]);
}
for(i = 1; i < len-2; i++) {
float v = A[i+1][i] / A[i][i];
for(j = 1; j <= len-1; j++)
A[i+1][j] -= v * A[i][j];
}
for(i = len-2; i > 0; i--) {
float acc = 0;
for(j = i; j <= len-2; j++)
acc += A[i][j]*c[j];
c[i] = (A[i][len-1] - acc) / A[i][i];
}
for (i = 0; i < 0x10000; i++) {
float x_out = (float)(i / 65535.0);
float y_out = 0;
for (j = 0; j < len-1; j++) {
if (x[j] <= x_out && x_out <= x[j+1]) {
float v = x_out - x[j];
y_out = y[j] +
((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v
+ (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v;
}
}
curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 :
(ushort)(y_out * 65535.0 + 0.5));
}
free (A);
}
void CLASS canon_600_fixed_wb (int temp)
{
static const short mul[4][5] = {
{ 667, 358,397,565,452 },
{ 731, 390,367,499,517 },
{ 1119, 396,348,448,537 },
{ 1399, 485,431,508,688 } };
int lo, hi, i;
float frac=0;
for (lo=4; --lo; )
if (*mul[lo] <= temp) break;
for (hi=0; hi < 3; hi++)
if (*mul[hi] >= temp) break;
if (lo != hi)
frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]);
for (i=1; i < 5; i++)
pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]);
}
/* Return values: 0 = white 1 = near white 2 = not white */
int CLASS canon_600_color (int ratio[2], int mar)
{
int clipped=0, target, miss;
if (flash_used) {
if (ratio[1] < -104)
{ ratio[1] = -104; clipped = 1; }
if (ratio[1] > 12)
{ ratio[1] = 12; clipped = 1; }
} else {
if (ratio[1] < -264 || ratio[1] > 461) return 2;
if (ratio[1] < -50)
{ ratio[1] = -50; clipped = 1; }
if (ratio[1] > 307)
{ ratio[1] = 307; clipped = 1; }
}
target = flash_used || ratio[1] < 197
? -38 - (398 * ratio[1] >> 10)
: -123 + (48 * ratio[1] >> 10);
if (target - mar <= ratio[0] &&
target + 20 >= ratio[0] && !clipped) return 0;
miss = target - ratio[0];
if (abs(miss) >= mar*4) return 2;
if (miss < -20) miss = -20;
if (miss > mar) miss = mar;
ratio[0] = target - miss;
return 1;
}
void CLASS canon_600_auto_wb()
{
int mar, row, col, i, j, st, count[] = { 0,0 };
int test[8], total[2][8], ratio[2][2], stat[2];
memset (&total, 0, sizeof total);
i = canon_ev + 0.5;
if (i < 10) mar = 150;
else if (i > 12) mar = 20;
else mar = 280 - 20 * i;
if (flash_used) mar = 80;
for (row=14; row < height-14; row+=4)
for (col=10; col < width; col+=2) {
for (i=0; i < 8; i++)
test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] =
BAYER(row+(i >> 1),col+(i & 1));
for (i=0; i < 8; i++)
if (test[i] < 150 || test[i] > 1500) goto next;
for (i=0; i < 4; i++)
if (abs(test[i] - test[i+4]) > 50) goto next;
for (i=0; i < 2; i++) {
for (j=0; j < 4; j+=2)
ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j];
stat[i] = canon_600_color (ratio[i], mar);
}
if ((st = stat[0] | stat[1]) > 1) goto next;
for (i=0; i < 2; i++)
if (stat[i])
for (j=0; j < 2; j++)
test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10;
for (i=0; i < 8; i++)
total[st][i] += test[i];
count[st]++;
next: ;
}
if (count[0] | count[1]) {
st = count[0]*200 < count[1];
for (i=0; i < 4; i++)
pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]);
}
}
void CLASS canon_600_coeff()
{
static const short table[6][12] = {
{ -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 },
{ -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 },
{ -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 },
{ -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 },
{ -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 },
{ -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } };
int t=0, i, c;
float mc, yc;
mc = pre_mul[1] / pre_mul[2];
yc = pre_mul[3] / pre_mul[2];
if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1;
if (mc > 1.28 && mc <= 2) {
if (yc < 0.8789) t=3;
else if (yc <= 2) t=4;
}
if (flash_used) t=5;
for (raw_color = i=0; i < 3; i++)
FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0;
}
void CLASS canon_600_load_raw()
{
uchar data[1120], *dp;
ushort *pix;
int irow, row;
for (irow=row=0; irow < height; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (data, 1, 1120, ifp) < 1120) derror();
pix = raw_image + row*raw_width;
for (dp=data; dp < data+1120; dp+=10, pix+=8) {
pix[0] = (dp[0] << 2) + (dp[1] >> 6 );
pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3);
pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3);
pix[3] = (dp[4] << 2) + (dp[1] & 3);
pix[4] = (dp[5] << 2) + (dp[9] & 3);
pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3);
pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3);
pix[7] = (dp[8] << 2) + (dp[9] >> 6 );
}
if ((row+=2) > height) row = 1;
}
}
void CLASS canon_600_correct()
{
int row, col, val;
static const short mul[4][2] =
{ { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } };
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
if ((val = BAYER(row,col) - black) < 0) val = 0;
val = val * mul[row & 3][col & 1] >> 9;
BAYER(row,col) = val;
}
}
canon_600_fixed_wb(1311);
canon_600_auto_wb();
canon_600_coeff();
maximum = (0x3ff - black) * 1109 >> 9;
black = 0;
}
int CLASS canon_s2is()
{
unsigned row;
for (row=0; row < 100; row++) {
fseek (ifp, row*3340 + 3284, SEEK_SET);
if (getc(ifp) > 15) return 1;
}
return 0;
}
unsigned CLASS getbithuff (int nbits, ushort *huff)
{
#ifdef LIBRAW_NOTHREADS
static unsigned bitbuf=0;
static int vbits=0, reset=0;
#else
#define bitbuf tls->getbits.bitbuf
#define vbits tls->getbits.vbits
#define reset tls->getbits.reset
#endif
unsigned c;
if (nbits > 25) return 0;
if (nbits < 0)
return bitbuf = vbits = reset = 0;
if (nbits == 0 || vbits < 0) return 0;
while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF &&
!(reset = zero_after_ff && c == 0xff && fgetc(ifp))) {
bitbuf = (bitbuf << 8) + (uchar) c;
vbits += 8;
}
c = bitbuf << (32-vbits) >> (32-nbits);
if (huff) {
vbits -= huff[c] >> 8;
c = (uchar) huff[c];
} else
vbits -= nbits;
if (vbits < 0) derror();
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#undef reset
#endif
}
#define getbits(n) getbithuff(n,0)
#define gethuff(h) getbithuff(*h,h+1)
/*
Construct a decode tree according the specification in *source.
The first 16 bytes specify how many codes should be 1-bit, 2-bit
3-bit, etc. Bytes after that are the leaf values.
For example, if the source is
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
then the code is
00 0x04
010 0x03
011 0x05
100 0x06
101 0x02
1100 0x07
1101 0x01
11100 0x08
11101 0x09
11110 0x00
111110 0x0a
1111110 0x0b
1111111 0xff
*/
ushort * CLASS make_decoder_ref (const uchar **source)
{
int max, len, h, i, j;
const uchar *count;
ushort *huff;
count = (*source += 16) - 17;
for (max=16; max && !count[max]; max--);
huff = (ushort *) calloc (1 + (1 << max), sizeof *huff);
merror (huff, "make_decoder()");
huff[0] = max;
for (h=len=1; len <= max; len++)
for (i=0; i < count[len]; i++, ++*source)
for (j=0; j < 1 << (max-len); j++)
if (h <= 1 << max)
huff[h++] = len << 8 | **source;
return huff;
}
ushort * CLASS make_decoder (const uchar *source)
{
return make_decoder_ref (&source);
}
void CLASS crw_init_tables (unsigned table, ushort *huff[2])
{
static const uchar first_tree[3][29] = {
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0,
0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff },
{ 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0,
0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff },
{ 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0,
0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff },
};
static const uchar second_tree[3][180] = {
{ 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139,
0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08,
0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0,
0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42,
0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57,
0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9,
0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98,
0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6,
0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4,
0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7,
0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1,
0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64,
0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba,
0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4,
0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff },
{ 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140,
0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06,
0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32,
0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51,
0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26,
0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59,
0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9,
0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99,
0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85,
0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8,
0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a,
0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9,
0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8,
0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8,
0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff },
{ 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117,
0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08,
0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22,
0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34,
0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41,
0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48,
0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69,
0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8,
0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94,
0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a,
0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6,
0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62,
0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5,
0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3,
0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff }
};
if (table > 2) table = 2;
huff[0] = make_decoder ( first_tree[table]);
huff[1] = make_decoder (second_tree[table]);
}
/*
Return 0 if the image starts with compressed data,
1 if it starts with uncompressed low-order bits.
In Canon compressed data, 0xff is always followed by 0x00.
*/
int CLASS canon_has_lowbits()
{
uchar test[0x4000];
int ret=1, i;
fseek (ifp, 0, SEEK_SET);
fread (test, 1, sizeof test, ifp);
for (i=540; i < sizeof test - 1; i++)
if (test[i] == 0xff) {
if (test[i+1]) return 1;
ret=0;
}
return ret;
}
void CLASS canon_load_raw()
{
ushort *pixel, *prow, *huff[2];
int nblocks, lowbits, i, c, row, r, save, val;
int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2];
crw_init_tables (tiff_compress, huff);
lowbits = canon_has_lowbits();
if (!lowbits) maximum = 0x3ff;
fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET);
zero_after_ff = 1;
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row+=8) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row*raw_width;
nblocks = MIN (8, raw_height-row) * raw_width >> 6;
for (block=0; block < nblocks; block++) {
memset (diffbuf, 0, sizeof diffbuf);
for (i=0; i < 64; i++ ) {
leaf = gethuff(huff[i > 0]);
if (leaf == 0 && i) break;
if (leaf == 0xff) continue;
i += leaf >> 4;
len = leaf & 15;
if (len == 0) continue;
diff = getbits(len);
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
if (i < 64) diffbuf[i] = diff;
}
diffbuf[0] += carry;
carry = diffbuf[0];
for (i=0; i < 64; i++ ) {
if (pnum++ % raw_width == 0)
base[0] = base[1] = 512;
if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10)
derror();
}
}
if (lowbits) {
save = ftell(ifp);
fseek (ifp, 26 + row*raw_width/4, SEEK_SET);
for (prow=pixel, i=0; i < raw_width*2; i++) {
c = fgetc(ifp);
for (r=0; r < 8; r+=2, prow++) {
val = (*prow << 2) + ((c >> r) & 3);
if (raw_width == 2672 && val < 512) val += 2;
*prow = val;
}
}
fseek (ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
FORC(2) free (huff[c]);
throw;
}
#endif
FORC(2) free (huff[c]);
}
//@end COMMON
struct jhead {
int algo, bits, high, wide, clrs, sraw, psv, restart, vpred[6];
ushort quant[64], idct[64], *huff[20], *free[20], *row;
};
//@out COMMON
int CLASS ljpeg_start (struct jhead *jh, int info_only)
{
ushort c, tag, len;
int cnt = 0;
uchar data[0x10000];
const uchar *dp;
memset (jh, 0, sizeof *jh);
jh->restart = INT_MAX;
if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0;
do {
if(feof(ifp)) return 0;
if(cnt++ > 1024) return 0; // 1024 tags limit
if (!fread (data, 2, 2, ifp)) return 0;
tag = data[0] << 8 | data[1];
len = (data[2] << 8 | data[3]) - 2;
if (tag <= 0xff00) return 0;
fread (data, 1, len, ifp);
switch (tag) {
case 0xffc3: // start of frame; lossless, Huffman
jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3;
case 0xffc1:
case 0xffc0:
jh->algo = tag & 0xff;
jh->bits = data[0];
jh->high = data[1] << 8 | data[2];
jh->wide = data[3] << 8 | data[4];
jh->clrs = data[5] + jh->sraw;
if (len == 9 && !dng_version) getc(ifp);
break;
case 0xffc4: // define Huffman tables
if (info_only) break;
for (dp = data; dp < data+len && !((c = *dp++) & -20); )
jh->free[c] = jh->huff[c] = make_decoder_ref (&dp);
break;
case 0xffda: // start of scan
jh->psv = data[1+data[0]*2];
jh->bits -= data[3+data[0]*2] & 15;
break;
case 0xffdb:
FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2];
break;
case 0xffdd:
jh->restart = data[0] << 8 | data[1];
}
} while (tag != 0xffda);
if (jh->bits > 16 || jh->clrs > 6 ||
!jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0;
if (info_only) return 1;
if (!jh->huff[0]) return 0;
FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c];
if (jh->sraw) {
FORC(4) jh->huff[2+c] = jh->huff[1];
FORC(jh->sraw) jh->huff[1+c] = jh->huff[0];
}
jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4);
merror (jh->row, "ljpeg_start()");
return zero_after_ff = 1;
}
void CLASS ljpeg_end (struct jhead *jh)
{
int c;
FORC4 if (jh->free[c]) free (jh->free[c]);
free (jh->row);
}
int CLASS ljpeg_diff (ushort *huff)
{
int len, diff;
if(!huff)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 2);
#endif
len = gethuff(huff);
if (len == 16 && (!dng_version || dng_version >= 0x1010000))
return -32768;
diff = getbits(len);
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
return diff;
}
ushort * CLASS ljpeg_row (int jrow, struct jhead *jh)
{
int col, c, diff, pred, spred=0;
ushort mark=0, *row[3];
if (jrow * jh->wide % jh->restart == 0) {
FORC(6) jh->vpred[c] = 1 << (jh->bits-1);
if (jrow) {
fseek (ifp, -2, SEEK_CUR);
do mark = (mark << 8) + (c = fgetc(ifp));
while (c != EOF && mark >> 4 != 0xffd);
}
getbits(-1);
}
FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1);
for (col=0; col < jh->wide; col++)
FORC(jh->clrs) {
diff = ljpeg_diff (jh->huff[c]);
if (jh->sraw && c <= jh->sraw && (col | c))
pred = spred;
else if (col) pred = row[0][-jh->clrs];
else pred = (jh->vpred[c] += diff) - diff;
if (jrow && col) switch (jh->psv) {
case 1: break;
case 2: pred = row[1][0]; break;
case 3: pred = row[1][-jh->clrs]; break;
case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break;
case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break;
case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break;
case 7: pred = (pred + row[1][0]) >> 1; break;
default: pred = 0;
}
if ((**row = pred + diff) >> jh->bits) derror();
if (c <= jh->sraw) spred = **row;
row[0]++; row[1]++;
}
return row[2];
}
void CLASS lossless_jpeg_load_raw()
{
int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0;
struct jhead jh;
ushort *rp;
if (!ljpeg_start (&jh, 0)) return;
if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 2);
#endif
jwide = jh.wide * jh.clrs;
jhigh = jh.high;
if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (jrow=0; jrow < jh.high; jrow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row (jrow, &jh);
if (load_flags & 1)
row = jrow & 1 ? height-1-jrow/2 : jrow/2;
for (jcol=0; jcol < jwide; jcol++) {
val = curve[*rp++];
if (cr2_slice[0]) {
jidx = jrow*jwide + jcol;
i = jidx / (cr2_slice[1]*raw_height);
if ((j = i >= cr2_slice[0]))
i = cr2_slice[0];
jidx -= i * (cr2_slice[1]*raw_height);
row = jidx / cr2_slice[1+j];
col = jidx % cr2_slice[1+j] + i*cr2_slice[1];
}
if (raw_width == 3984 && (col -= 2) < 0)
col += (row--,raw_width);
if(row>raw_height)
#ifdef LIBRAW_LIBRARY_BUILD
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#else
longjmp (failure, 3);
#endif
if ((unsigned) row < raw_height) RAW(row,col) = val;
if (++col >= raw_width)
col = (row++,0);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw;
}
#endif
ljpeg_end (&jh);
}
void CLASS canon_sraw_load_raw()
{
struct jhead jh;
short *rp=0, (*ip)[4];
int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c;
int v[3]={0,0,0}, ver, hue;
#ifdef LIBRAW_LIBRARY_BUILD
int saved_w = width, saved_h = height;
#endif
char *cp;
if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return;
jwide = (jh.wide >>= 1) * jh.clrs;
#ifdef LIBRAW_LIBRARY_BUILD
if(load_flags & 256)
{
width = raw_width;
height = raw_height;
}
try {
#endif
for (ecol=slice=0; slice <= cr2_slice[0]; slice++) {
scol = ecol;
ecol += cr2_slice[1] * 2 / jh.clrs;
if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2;
for (row=0; row < height; row += (jh.clrs >> 1) - 1) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
ip = (short (*)[4]) image + row*width;
for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) {
if ((jcol %= jwide) == 0)
rp = (short *) ljpeg_row (jrow++, &jh);
if (col >= width) continue;
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
FORC (jh.clrs-2)
{
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192;
}
ip[col][1] = rp[jcol+jh.clrs-2] - 8192;
ip[col][2] = rp[jcol+jh.clrs-1] - 8192;
}
else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)
{
FORC (jh.clrs-2)
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col][1] = rp[jcol+jh.clrs-2] - 8192;
ip[col][2] = rp[jcol+jh.clrs-1] - 8192;
}
else
#endif
{
FORC (jh.clrs-2)
ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c];
ip[col][1] = rp[jcol+jh.clrs-2] - 16384;
ip[col][2] = rp[jcol+jh.clrs-1] - 16384;
}
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE)
{
ljpeg_end (&jh);
maximum = 0x3fff;
height = saved_h;
width = saved_w;
return;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (cp=model2; *cp && !isdigit(*cp); cp++);
sscanf (cp, "%d.%d.%d", v, v+1, v+2);
ver = (v[0]*1000 + v[1])*1000 + v[2];
hue = (jh.sraw+1) << 2;
if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006))
hue = jh.sraw << 1;
ip = (short (*)[4]) image;
rp = ip[0];
for (row=0; row < height; row++, ip+=width) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (row & (jh.sraw >> 1))
{
for (col=0; col < width; col+=2)
for (c=1; c < 3; c++)
if (row == height-1)
{
ip[col][c] = ip[col-width][c];
}
else
{
ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1;
}
}
for (col=1; col < width; col+=2)
for (c=1; c < 3; c++)
if (col == width-1)
ip[col][c] = ip[col-1][c];
else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1;
}
#ifdef LIBRAW_LIBRARY_BUILD
if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) )
#endif
for ( ; rp < ip[0]; rp+=4) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (unique_id == 0x80000218 ||
unique_id == 0x80000250 ||
unique_id == 0x80000261 ||
unique_id == 0x80000281 ||
unique_id == 0x80000287) {
rp[1] = (rp[1] << 2) + hue;
rp[2] = (rp[2] << 2) + hue;
pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14);
pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14);
pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14);
} else {
if (unique_id < 0x80000218) rp[0] -= 512;
pix[0] = rp[0] + rp[2];
pix[2] = rp[0] + rp[1];
pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12);
}
FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
height = saved_h;
width = saved_w;
#endif
ljpeg_end (&jh);
maximum = 0x3fff;
}
void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp)
{
int c;
if (tiff_samples == 2 && shot_select) (*rp)++;
if (raw_image) {
if (row < raw_height && col < raw_width)
RAW(row,col) = curve[**rp];
*rp += tiff_samples;
} else {
if (row < height && col < width)
FORC(tiff_samples)
image[row*width+col][c] = curve[(*rp)[c]];
*rp += tiff_samples;
}
if (tiff_samples == 2 && shot_select) (*rp)--;
}
void CLASS ljpeg_idct (struct jhead *jh)
{
int c, i, j, len, skip, coef;
float work[3][8][8];
static float cs[106] = { 0 };
static const uchar zigzag[80] =
{ 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33,
40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36,
29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,
47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 };
if (!cs[0])
FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2;
memset (work, 0, sizeof work);
work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0];
for (i=1; i < 64; i++ ) {
len = gethuff (jh->huff[16]);
i += skip = len >> 4;
if (!(len &= 15) && skip < 15) break;
coef = getbits(len);
if ((coef & (1 << (len-1))) == 0)
coef -= (1 << len) - 1;
((float *)work)[zigzag[i]] = coef * jh->quant[i];
}
FORC(8) work[0][0][c] *= M_SQRT1_2;
FORC(8) work[0][c][0] *= M_SQRT1_2;
for (i=0; i < 8; i++)
for (j=0; j < 8; j++)
FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c];
for (i=0; i < 8; i++)
for (j=0; j < 8; j++)
FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c];
FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5);
}
void CLASS lossless_dng_load_raw()
{
unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j;
struct jhead jh;
ushort *rp;
while (trow < raw_height) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
save = ftell(ifp);
if (tile_length < INT_MAX)
fseek (ifp, get4(), SEEK_SET);
if (!ljpeg_start (&jh, 0)) break;
jwide = jh.wide;
if (filters) jwide *= jh.clrs;
jwide /= MIN (is_raw, tiff_samples);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
switch (jh.algo) {
case 0xc1:
jh.vpred[0] = 16384;
getbits(-1);
for (jrow=0; jrow+7 < jh.high; jrow += 8) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (jcol=0; jcol+7 < jh.wide; jcol += 8) {
ljpeg_idct (&jh);
rp = jh.idct;
row = trow + jcol/tile_width + jrow*2;
col = tcol + jcol%tile_width;
for (i=0; i < 16; i+=2)
for (j=0; j < 8; j++)
adobe_copy_pixel (row+i, col+j, &rp);
}
}
break;
case 0xc3:
for (row=col=jrow=0; jrow < jh.high; jrow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
rp = ljpeg_row (jrow, &jh);
for (jcol=0; jcol < jwide; jcol++) {
adobe_copy_pixel (trow+row, tcol+col, &rp);
if (++col >= tile_width || col >= raw_width)
row += 1 + (col = 0);
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
ljpeg_end (&jh);
throw ;
}
#endif
fseek (ifp, save+4, SEEK_SET);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
ljpeg_end (&jh);
}
}
void CLASS packed_dng_load_raw()
{
ushort *pixel, *rp;
int row, col;
pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel);
merror (pixel, "packed_dng_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (tiff_bps == 16)
read_shorts (pixel, raw_width * tiff_samples);
else {
getbits(-1);
for (col=0; col < raw_width * tiff_samples; col++)
pixel[col] = getbits(tiff_bps);
}
for (rp=pixel, col=0; col < raw_width; col++)
adobe_copy_pixel (row, col, &rp);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free (pixel);
throw ;
}
#endif
free (pixel);
}
void CLASS pentax_load_raw()
{
ushort bit[2][15], huff[4097];
int dep, row, col, diff, c, i;
ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
dep = (get2() + 12) & 15;
fseek (ifp, 12, SEEK_CUR);
FORC(dep) bit[0][c] = get2();
FORC(dep) bit[1][c] = fgetc(ifp);
FORC(dep)
for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); )
huff[++i] = bit[1][c] << 8 | c;
huff[0] = 12;
fseek (ifp, data_offset, SEEK_SET);
getbits(-1);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
diff = ljpeg_diff (huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
RAW(row,col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps) derror();
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS nikon_coolscan_load_raw()
{
int bufsize = width*3*tiff_bps/8;
if(tiff_bps <= 8)
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255);
else
gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535);
fseek (ifp, data_offset, SEEK_SET);
unsigned char *buf = (unsigned char*)malloc(bufsize);
unsigned short *ubuf = (unsigned short *)buf;
for(int row = 0; row < raw_height; row++)
{
int red = fread (buf, 1, bufsize, ifp);
unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width;
if(tiff_bps <= 8)
for(int col=0; col<width;col++)
{
ip[col][0] = curve[buf[col*3]];
ip[col][1] = curve[buf[col*3+1]];
ip[col][2] = curve[buf[col*3+2]];
ip[col][3]=0;
}
else
for(int col=0; col<width;col++)
{
ip[col][0] = curve[ubuf[col*3]];
ip[col][1] = curve[ubuf[col*3+1]];
ip[col][2] = curve[ubuf[col*3+2]];
ip[col][3]=0;
}
}
free(buf);
}
#endif
void CLASS nikon_load_raw()
{
static const uchar nikon_tree[][32] = {
{ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */
5,4,3,6,2,7,1,0,8,9,11,10,12 },
{ 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */
0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 },
{ 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */
5,4,6,3,7,2,8,1,9,0,10,11,12 },
{ 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */
5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 },
{ 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */
8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 },
{ 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */
7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } };
ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize;
int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff;
fseek (ifp, meta_offset, SEEK_SET);
ver0 = fgetc(ifp);
ver1 = fgetc(ifp);
if (ver0 == 0x49 || ver1 == 0x58)
fseek (ifp, 2110, SEEK_CUR);
if (ver0 == 0x46) tree = 2;
if (tiff_bps == 14) tree += 3;
read_shorts (vpred[0], 4);
max = 1 << tiff_bps & 0x7fff;
if ((csize = get2()) > 1)
step = max / (csize-1);
if (ver0 == 0x44 && ver1 == 0x20 && step > 0) {
for (i=0; i < csize; i++)
curve[i*step] = get2();
for (i=0; i < max; i++)
curve[i] = ( curve[i-i%step]*(step-i%step) +
curve[i-i%step+step]*(i%step) ) / step;
fseek (ifp, meta_offset+562, SEEK_SET);
split = get2();
} else if (ver0 != 0x46 && csize <= 0x4001)
read_shorts (curve, max=csize);
while (curve[max-2] == curve[max-1]) max--;
huff = make_decoder (nikon_tree[tree]);
fseek (ifp, data_offset, SEEK_SET);
getbits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (min=row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (split && row == split) {
free (huff);
huff = make_decoder (nikon_tree[tree+1]);
max += (min = 16) << 1;
}
for (col=0; col < raw_width; col++) {
i = gethuff(huff);
len = i & 15;
shl = i >> 4;
diff = ((getbits(len-shl) << 1) + 1) << shl >> 1;
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - !shl;
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if ((ushort)(hpred[col & 1] + min) >= max) derror();
RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free (huff);
throw;
}
#endif
free (huff);
}
void CLASS nikon_yuv_load_raw()
{
int row, col, yuv[4], rgb[3], b, c;
UINT64 bitbuf=0;
float cmul[4];
FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; }
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
if (!(b = col & 1)) {
bitbuf = 0;
FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8;
FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11);
}
rgb[0] = yuv[b] + 1.370705*yuv[3];
rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3];
rgb[2] = yuv[b] + 1.732446*yuv[2];
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c];
}
}
}
/*
Returns 1 for a Coolpix 995, 0 for anything else.
*/
int CLASS nikon_e995()
{
int i, histo[256];
const uchar often[] = { 0x00, 0x55, 0xaa, 0xff };
memset (histo, 0, sizeof histo);
fseek (ifp, -2000, SEEK_END);
for (i=0; i < 2000; i++)
histo[fgetc(ifp)]++;
for (i=0; i < 4; i++)
if (histo[often[i]] < 200)
return 0;
return 1;
}
/*
Returns 1 for a Coolpix 2100, 0 for anything else.
*/
int CLASS nikon_e2100()
{
uchar t[12];
int i;
fseek (ifp, 0, SEEK_SET);
for (i=0; i < 1024; i++) {
fread (t, 1, 12, ifp);
if (((t[2] & t[4] & t[7] & t[9]) >> 4
& t[1] & t[6] & t[8] & t[11] & 3) != 3)
return 0;
}
return 1;
}
void CLASS nikon_3700()
{
int bits, i;
uchar dp[24];
static const struct {
int bits;
char t_make[12], t_model[15];
} table[] = {
{ 0x00, "Pentax", "Optio 33WR" },
{ 0x03, "Nikon", "E3200" },
{ 0x32, "Nikon", "E3700" },
{ 0x33, "Olympus", "C740UZ" } };
fseek (ifp, 3072, SEEK_SET);
fread (dp, 1, 24, ifp);
bits = (dp[8] & 3) << 4 | (dp[20] & 3);
for (i=0; i < sizeof table / sizeof *table; i++)
if (bits == table[i].bits) {
strcpy (make, table[i].t_make );
strcpy (model, table[i].t_model);
}
}
/*
Separates a Minolta DiMAGE Z2 from a Nikon E4300.
*/
int CLASS minolta_z2()
{
int i, nz;
char tail[424];
fseek (ifp, -sizeof tail, SEEK_END);
fread (tail, 1, sizeof tail, ifp);
for (nz=i=0; i < sizeof tail; i++)
if (tail[i]) nz++;
return nz > 20;
}
//@end COMMON
void CLASS jpeg_thumb();
//@out COMMON
void CLASS ppm_thumb()
{
char *thumb;
thumb_length = thumb_width*thumb_height*3;
thumb = (char *) malloc (thumb_length);
merror (thumb, "ppm_thumb()");
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fread (thumb, 1, thumb_length, ifp);
fwrite (thumb, 1, thumb_length, ofp);
free (thumb);
}
void CLASS ppm16_thumb()
{
int i;
char *thumb;
thumb_length = thumb_width*thumb_height*3;
thumb = (char *) calloc (thumb_length, 2);
merror (thumb, "ppm16_thumb()");
read_shorts ((ushort *) thumb, thumb_length);
for (i=0; i < thumb_length; i++)
thumb[i] = ((ushort *) thumb)[i] >> 8;
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
fwrite (thumb, 1, thumb_length, ofp);
free (thumb);
}
void CLASS layer_thumb()
{
int i, c;
char *thumb, map[][4] = { "012","102" };
colors = thumb_misc >> 5 & 7;
thumb_length = thumb_width*thumb_height;
thumb = (char *) calloc (colors, thumb_length);
merror (thumb, "layer_thumb()");
fprintf (ofp, "P%d\n%d %d\n255\n",
5 + (colors >> 1), thumb_width, thumb_height);
fread (thumb, thumb_length, colors, ifp);
for (i=0; i < thumb_length; i++)
FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp);
free (thumb);
}
void CLASS rollei_thumb()
{
unsigned i;
ushort *thumb;
thumb_length = thumb_width * thumb_height;
thumb = (ushort *) calloc (thumb_length, 2);
merror (thumb, "rollei_thumb()");
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
read_shorts (thumb, thumb_length);
for (i=0; i < thumb_length; i++) {
putc (thumb[i] << 3, ofp);
putc (thumb[i] >> 5 << 2, ofp);
putc (thumb[i] >> 11 << 3, ofp);
}
free (thumb);
}
void CLASS rollei_load_raw()
{
uchar pixel[10];
unsigned iten=0, isix, i, buffer=0, todo[16];
isix = raw_width * raw_height * 5 / 8;
while (fread (pixel, 1, 10, ifp) == 10) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (i=0; i < 10; i+=2) {
todo[i] = iten++;
todo[i+1] = pixel[i] << 8 | pixel[i+1];
buffer = pixel[i] >> 2 | buffer << 6;
}
for ( ; i < 16; i+=2) {
todo[i] = isix++;
todo[i+1] = buffer >> (14-i)*5;
}
for (i=0; i < 16; i+=2)
raw_image[todo[i]] = (todo[i+1] & 0x3ff);
}
maximum = 0x3ff;
}
int CLASS raw (unsigned row, unsigned col)
{
return (row < raw_height && col < raw_width) ? RAW(row,col) : 0;
}
void CLASS phase_one_flat_field (int is_float, int nc)
{
ushort head[8];
unsigned wide, high, y, x, c, rend, cend, row, col;
float *mrow, num, mult[4];
read_shorts (head, 8);
if (head[2] * head[3] * head[4] * head[5] == 0) return;
wide = head[2] / head[4] + (head[2] % head[4] != 0);
high = head[3] / head[5] + (head[3] % head[5] != 0);
mrow = (float *) calloc (nc*wide, sizeof *mrow);
merror (mrow, "phase_one_flat_field()");
for (y=0; y < high; y++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (x=0; x < wide; x++)
for (c=0; c < nc; c+=2) {
num = is_float ? getreal(11) : get2()/32768.0;
if (y==0) mrow[c*wide+x] = num;
else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5];
}
if (y==0) continue;
rend = head[1] + y*head[5];
for (row = rend-head[5];
row < raw_height && row < rend &&
row < head[1]+head[3]-head[5]; row++) {
for (x=1; x < wide; x++) {
for (c=0; c < nc; c+=2) {
mult[c] = mrow[c*wide+x-1];
mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4];
}
cend = head[0] + x*head[4];
for (col = cend-head[4];
col < raw_width &&
col < cend && col < head[0]+head[2]-head[4]; col++) {
c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0;
if (!(c & 1)) {
c = RAW(row,col) * mult[c];
RAW(row,col) = LIM(c,0,65535);
}
for (c=0; c < nc; c+=2)
mult[c] += mult[c+1];
}
}
for (x=0; x < wide; x++)
for (c=0; c < nc; c+=2)
mrow[c*wide+x] += mrow[(c+1)*wide+x];
}
}
free (mrow);
}
int CLASS phase_one_correct()
{
unsigned entries, tag, data, save, col, row, type;
int len, i, j, k, cip, val[4], dev[4], sum, max;
int head[9], diff, mindiff=INT_MAX, off_412=0;
/* static */ const signed char dir[12][2] =
{ {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0},
{-2,-2}, {-2,2}, {2,-2}, {2,2} };
float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL};
ushort *xval[2];
int qmult_applied = 0, qlin_applied = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if (!meta_length)
#else
if (half_size || !meta_length)
#endif
return 0;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Phase One correction...\n"));
#endif
fseek (ifp, meta_offset, SEEK_SET);
order = get2();
fseek (ifp, 6, SEEK_CUR);
fseek (ifp, meta_offset+get4(), SEEK_SET);
entries = get4(); get4();
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
while (entries--) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, meta_offset+data, SEEK_SET);
if (tag == 0x419) { /* Polynomial curve */
for (get4(), i=0; i < 8; i++)
poly[i] = getreal(11);
poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1;
for (i=0; i < 0x10000; i++) {
num = (poly[5]*i + poly[3])*i + poly[1];
curve[i] = LIM(num,0,65535);
} goto apply; /* apply to right half */
} else if (tag == 0x41a) { /* Polynomial curve */
for (i=0; i < 4; i++)
poly[i] = getreal(11);
for (i=0; i < 0x10000; i++) {
for (num=0, j=4; j--; )
num = num * i + poly[j];
curve[i] = LIM(num+i,0,65535);
} apply: /* apply to whole image */
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (tag & 1)*ph1.split_col; col < raw_width; col++)
RAW(row,col) = curve[RAW(row,col)];
}
} else if (tag == 0x400) { /* Sensor defects */
while ((len -= 8) >= 0) {
col = get2();
row = get2();
type = get2(); get2();
if (col >= raw_width) continue;
if (type == 131 || type == 137) /* Bad column */
for (row=0; row < raw_height; row++)
if (FC(row-top_margin,col-left_margin) == 1) {
for (sum=i=0; i < 4; i++)
sum += val[i] = raw (row+dir[i][0], col+dir[i][1]);
for (max=i=0; i < 4; i++) {
dev[i] = abs((val[i] << 2) - sum);
if (dev[max] < dev[i]) max = i;
}
RAW(row,col) = (sum - val[max])/3.0 + 0.5;
} else {
for (sum=0, i=8; i < 12; i++)
sum += raw (row+dir[i][0], col+dir[i][1]);
RAW(row,col) = 0.5 + sum * 0.0732233 +
(raw(row,col-2) + raw(row,col+2)) * 0.3535534;
}
else if (type == 129) { /* Bad pixel */
if (row >= raw_height) continue;
j = (FC(row-top_margin,col-left_margin) != 1) * 4;
for (sum=0, i=j; i < j+8; i++)
sum += raw (row+dir[i][0], col+dir[i][1]);
RAW(row,col) = (sum + 4) >> 3;
}
}
} else if (tag == 0x401) { /* All-color flat fields */
phase_one_flat_field (1, 2);
} else if (tag == 0x416 || tag == 0x410) {
phase_one_flat_field (0, 2);
} else if (tag == 0x40b) { /* Red+blue flat field */
phase_one_flat_field (0, 4);
} else if (tag == 0x412) {
fseek (ifp, 36, SEEK_CUR);
diff = abs (get2() - ph1.tag_21a);
if (mindiff > diff) {
mindiff = diff;
off_412 = ftell(ifp) - 38;
}
} else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */
ushort lc[2][2][16], ref[16];
int qr, qc;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 16; i++)
lc[qr][qc][i] = get4();
for (i = 0; i < 16; i++) {
int v = 0;
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
v += lc[qr][qc][i];
ref[i] = (v + 2) >> 2;
}
for (qr = 0; qr < 2; qr++) {
for (qc = 0; qc < 2; qc++) {
int cx[19], cf[19];
for (i = 0; i < 16; i++) {
cx[1+i] = lc[qr][qc][i];
cf[1+i] = ref[i];
}
cx[0] = cf[0] = 0;
cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15];
cf[18] = cx[18] = 65535;
cubic_spline(cx, cf, 19);
for (row = (qr ? ph1.split_row : 0);
row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0);
col < (qc ? raw_width : ph1.split_col); col++)
RAW(row,col) = curve[RAW(row,col)];
}
}
}
qlin_applied = 1;
} else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */
float qmult[2][2] = { { 1, 1 }, { 1, 1 } };
get4(); get4(); get4(); get4();
qmult[0][0] = 1.0 + getreal(11);
get4(); get4(); get4(); get4(); get4();
qmult[0][1] = 1.0 + getreal(11);
get4(); get4(); get4();
qmult[1][0] = 1.0 + getreal(11);
get4(); get4(); get4();
qmult[1][1] = 1.0 + getreal(11);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col);
RAW(row,col) = LIM(i,0,65535);
}
}
qmult_applied = 1;
} else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */
ushort lc[2][2][7], ref[7];
int qr, qc;
for (i = 0; i < 7; i++)
ref[i] = get4();
for (qr = 0; qr < 2; qr++)
for (qc = 0; qc < 2; qc++)
for (i = 0; i < 7; i++)
lc[qr][qc][i] = get4();
for (qr = 0; qr < 2; qr++) {
for (qc = 0; qc < 2; qc++) {
int cx[9], cf[9];
for (i = 0; i < 7; i++) {
cx[1+i] = ref[i];
cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000;
}
cx[0] = cf[0] = 0;
cx[8] = cf[8] = 65535;
cubic_spline(cx, cf, 9);
for (row = (qr ? ph1.split_row : 0);
row < (qr ? raw_height : ph1.split_row); row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col = (qc ? ph1.split_col : 0);
col < (qc ? raw_width : ph1.split_col); col++)
RAW(row,col) = curve[RAW(row,col)];
}
}
}
qmult_applied = 1;
qlin_applied = 1;
}
fseek (ifp, save, SEEK_SET);
}
if (off_412) {
fseek (ifp, off_412, SEEK_SET);
for (i=0; i < 9; i++) head[i] = get4() & 0x7fff;
yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6);
merror (yval[0], "phase_one_correct()");
yval[1] = (float *) (yval[0] + head[1]*head[3]);
xval[0] = (ushort *) (yval[1] + head[2]*head[4]);
xval[1] = (ushort *) (xval[0] + head[1]*head[3]);
get2();
for (i=0; i < 2; i++)
for (j=0; j < head[i+1]*head[i+3]; j++)
yval[i][j] = getreal(11);
for (i=0; i < 2; i++)
for (j=0; j < head[i+1]*head[i+3]; j++)
xval[i][j] = get2();
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
cfrac = (float) col * head[3] / raw_width;
cfrac -= cip = cfrac;
num = RAW(row,col) * 0.5;
for (i=cip; i < cip+2; i++) {
for (k=j=0; j < head[1]; j++)
if (num < xval[0][k = head[1]*i+j]) break;
frac = (j == 0 || j == head[1]) ? 0 :
(xval[0][k] - num) / (xval[0][k] - xval[0][k-1]);
mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac);
}
i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2;
RAW(row,col) = LIM(i,0,65535);
}
}
free (yval[0]);
}
#ifdef LIBRAW_LIBRARY_BUILD
}
catch (...)
{
if(yval[0]) free(yval[0]);
return LIBRAW_CANCELLED_BY_CALLBACK;
}
#endif
return 0;
}
void CLASS phase_one_load_raw()
{
int a, b, i;
ushort akey, bkey, t_mask;
fseek (ifp, ph1.key_off, SEEK_SET);
akey = get2();
bkey = get2();
t_mask = ph1.format == 1 ? 0x5555:0x1354;
#ifdef LIBRAW_LIBRARY_BUILD
if (ph1.black_col || ph1.black_row )
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()");
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()");
if (ph1.black_col)
{
fseek (ifp, ph1.black_col, SEEK_SET);
read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2);
}
if (ph1.black_row)
{
fseek (ifp, ph1.black_row, SEEK_SET);
read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2);
}
}
#endif
fseek (ifp, data_offset, SEEK_SET);
read_shorts (raw_image, raw_width*raw_height);
if (ph1.format)
for (i=0; i < raw_width*raw_height; i+=2) {
a = raw_image[i+0] ^ akey;
b = raw_image[i+1] ^ bkey;
raw_image[i+0] = (a & t_mask) | (b & ~t_mask);
raw_image[i+1] = (b & t_mask) | (a & ~t_mask);
}
}
unsigned CLASS ph1_bithuff (int nbits, ushort *huff)
{
#ifndef LIBRAW_NOTHREADS
#define bitbuf tls->ph1_bits.bitbuf
#define vbits tls->ph1_bits.vbits
#else
static UINT64 bitbuf=0;
static int vbits=0;
#endif
unsigned c;
if (nbits == -1)
return bitbuf = vbits = 0;
if (nbits == 0) return 0;
if (vbits < nbits) {
bitbuf = bitbuf << 32 | get4();
vbits += 32;
}
c = bitbuf << (64-vbits) >> (64-nbits);
if (huff) {
vbits -= huff[c] >> 8;
return (uchar) huff[c];
}
vbits -= nbits;
return c;
#ifndef LIBRAW_NOTHREADS
#undef bitbuf
#undef vbits
#endif
}
#define ph1_bits(n) ph1_bithuff(n,0)
#define ph1_huff(h) ph1_bithuff(*h,h+1)
void CLASS phase_one_load_raw_c()
{
static const int length[] = { 8,7,6,9,11,10,5,12,14,13 };
int *offset, len[2], pred[2], row, col, i, j;
ushort *pixel;
short (*c_black)[2], (*r_black)[2];
#ifdef LIBRAW_LIBRARY_BUILD
if(ph1.format == 6)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2);
merror (pixel, "phase_one_load_raw_c()");
offset = (int *) (pixel + raw_width);
fseek (ifp, strip_offset, SEEK_SET);
for (row=0; row < raw_height; row++)
offset[row] = get4();
c_black = (short (*)[2]) (offset + raw_height);
fseek (ifp, ph1.black_col, SEEK_SET);
if (ph1.black_col)
read_shorts ((ushort *) c_black[0], raw_height*2);
r_black = c_black + raw_height;
fseek (ifp, ph1.black_row, SEEK_SET);
if (ph1.black_row)
read_shorts ((ushort *) r_black[0], raw_width*2);
#ifdef LIBRAW_LIBRARY_BUILD
// Copy data to internal copy (ever if not read)
if (ph1.black_col || ph1.black_row )
{
imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort));
imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort));
merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()");
memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort));
}
#endif
for (i=0; i < 256; i++)
curve[i] = i*i / 3.969 + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, data_offset + offset[row], SEEK_SET);
ph1_bits(-1);
pred[0] = pred[1] = 0;
for (col=0; col < raw_width; col++) {
if (col >= (raw_width & -8))
len[0] = len[1] = 14;
else if ((col & 7) == 0)
for (i=0; i < 2; i++) {
for (j=0; j < 5 && !ph1_bits(1); j++);
if (j--) len[i] = length[j*2 + ph1_bits(1)];
}
if ((i = len[col & 1]) == 14)
pixel[col] = pred[col & 1] = ph1_bits(16);
else
pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));
if (pred[col & 1] >> 16) derror();
if (ph1.format == 5 && pixel[col] < 256)
pixel[col] = curve[pixel[col]];
}
#ifndef LIBRAW_LIBRARY_BUILD
for (col=0; col < raw_width; col++) {
int shift = ph1.format == 8? 0: 2;
i = (pixel[col] << shift) - ph1.t_black
+ c_black[row][col >= ph1.split_col]
+ r_black[col][row >= ph1.split_row];
if (i > 0) RAW(row,col) = i;
}
#else
if(ph1.format == 8)
memmove(&RAW(row,0),&pixel[0],raw_width*2);
else
for (col=0; col < raw_width; col++)
RAW(row,col) = pixel[col] << 2;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = 0xfffc - ph1.t_black;
}
void CLASS hasselblad_load_raw()
{
struct jhead jh;
int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c;
unsigned upix, urow, ucol;
ushort *ip;
if (!ljpeg_start (&jh, 0)) return;
order = 0x4949;
ph1_bits(-1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
back[4] = (int *) calloc (raw_width, 3*sizeof **back);
merror (back[4], "hasselblad_load_raw()");
FORC3 back[c] = back[4] + c*raw_width;
cblack[6] >>= sh = tiff_samples > 1;
shot = LIM(shot_select, 1, tiff_samples) - 1;
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC4 back[(c+3) & 3] = back[c];
for (col=0; col < raw_width; col+=2) {
for (s=0; s < tiff_samples*2; s+=2) {
FORC(2) len[c] = ph1_huff(jh.huff[0]);
FORC(2) {
diff[s+c] = ph1_bits(len[c]);
if ((diff[s+c] & (1 << (len[c]-1))) == 0)
diff[s+c] -= (1 << len[c]) - 1;
if (diff[s+c] == 65535) diff[s+c] = -32768;
}
}
for (s=col; s < col+2; s++) {
pred = 0x8000 + load_flags;
if (col) pred = back[2][s-2];
if (col && row > 1) switch (jh.psv) {
case 11: pred += back[0][s]/2 - back[0][s-2]/2; break;
}
f = (row & 1)*3 ^ ((col+s) & 1);
FORC (tiff_samples) {
pred += diff[(s & 1)*tiff_samples+c];
upix = pred >> sh & 0xffff;
if (raw_image && c == shot)
RAW(row,s) = upix;
if (image) {
urow = row-top_margin + (c & 1);
ucol = col-left_margin - ((c >> 1) & 1);
ip = &image[urow*width+ucol][f];
if (urow < height && ucol < width)
*ip = c < 4 ? upix : (*ip + upix) >> 1;
}
}
back[2][s] = pred;
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...){
free (back[4]);
ljpeg_end (&jh);
throw;
}
#endif
free (back[4]);
ljpeg_end (&jh);
if (image) mix_green = 1;
}
void CLASS leaf_hdr_load_raw()
{
ushort *pixel=0;
unsigned tile=0, r, c, row, col;
if (!filters) {
pixel = (ushort *) calloc (raw_width, sizeof *pixel);
merror (pixel, "leaf_hdr_load_raw()");
}
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
FORC(tiff_samples)
for (r=0; r < raw_height; r++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (r % tile_length == 0) {
fseek (ifp, data_offset + 4*tile++, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
}
if (filters && c != shot_select) continue;
if (filters) pixel = raw_image + r*raw_width;
read_shorts (pixel, raw_width);
if (!filters && (row = r - top_margin) < height)
for (col=0; col < width; col++)
image[row*width+col][c] = pixel[col+left_margin];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
if(!filters) free(pixel);
throw;
}
#endif
if (!filters) {
maximum = 0xffff;
raw_color = 1;
free (pixel);
}
}
void CLASS unpacked_load_raw()
{
int row, col, bits=0;
while (1 << ++bits < maximum);
read_shorts (raw_image, raw_width*raw_height);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++)
if ((RAW(row,col) >>= load_flags) >> bits
&& (unsigned) (row-top_margin) < height
&& (unsigned) (col-left_margin) < width) derror();
}
}
void CLASS unpacked_load_raw_reversed()
{
int row, col, bits=0;
while (1 << ++bits < maximum);
for (row=raw_height-1; row >= 0; row--)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
read_shorts (&raw_image[row*raw_width], raw_width);
for (col=0; col < raw_width; col++)
if ((RAW(row,col) >>= load_flags) >> bits
&& (unsigned) (row-top_margin) < height
&& (unsigned) (col-left_margin) < width) derror();
}
}
void CLASS sinar_4shot_load_raw()
{
ushort *pixel;
unsigned shot, row, col, r, c;
if (raw_image) {
shot = LIM (shot_select, 1, 4) - 1;
fseek (ifp, data_offset + shot*4, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
unpacked_load_raw();
return;
}
pixel = (ushort *) calloc (raw_width, sizeof *pixel);
merror (pixel, "sinar_4shot_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (shot=0; shot < 4; shot++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, data_offset + shot*4, SEEK_SET);
fseek (ifp, get4(), SEEK_SET);
for (row=0; row < raw_height; row++) {
read_shorts (pixel, raw_width);
if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue;
for (col=0; col < raw_width; col++) {
if ((c = col-left_margin - (shot & 1)) >= width) continue;
image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col];
}
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
free(pixel);
throw;
}
#endif
free (pixel);
mix_green = 1;
}
void CLASS imacon_full_load_raw()
{
int row, col;
if (!image) return;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short));
merror(buf,"imacon_full_load_raw");
#endif
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
read_shorts(buf,width*3);
unsigned short (*rowp)[4] = &image[row*width];
for (col=0; col < width; col++)
{
rowp[col][0]=buf[col*3];
rowp[col][1]=buf[col*3+1];
rowp[col][2]=buf[col*3+2];
rowp[col][3]=0;
}
#else
for (col=0; col < width; col++)
read_shorts (image[row*width+col], 3);
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(buf);
#endif
}
void CLASS packed_load_raw()
{
int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i;
UINT64 bitbuf=0;
bwide = raw_width * tiff_bps / 8;
bwide += bwide & load_flags >> 7;
rbits = bwide * 8 - raw_width * tiff_bps;
if (load_flags & 1) bwide = bwide * 16 / 15;
bite = 8 + (load_flags & 24);
half = (raw_height+1) >> 1;
for (irow=0; irow < raw_height; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
row = irow;
if (load_flags & 2 &&
(row = irow % half * 2 + irow / half) == 1 &&
load_flags & 4) {
if (vbits=0, tiff_compress)
fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET);
else {
fseek (ifp, 0, SEEK_END);
fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET);
}
}
for (col=0; col < raw_width; col++) {
for (vbits -= tiff_bps; vbits < 0; vbits += bite) {
bitbuf <<= bite;
for (i=0; i < bite; i+=8)
bitbuf |= (unsigned) (fgetc(ifp) << i);
}
val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps);
RAW(row,col ^ (load_flags >> 6 & 1)) = val;
if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) &&
row < height+top_margin && col < width+left_margin) derror();
}
vbits -= rbits;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
ushort raw_stride;
void CLASS parse_broadcom () {
/* This structure is at offset 0xb0 from the 'BRCM' ident. */
struct {
uint8_t umode[32];
uint16_t uwidth;
uint16_t uheight;
uint16_t padding_right;
uint16_t padding_down;
uint32_t unknown_block[6];
uint16_t transform;
uint16_t format;
uint8_t bayer_order;
uint8_t bayer_format;
} header;
header.bayer_order = 0;
fseek (ifp, 0xb0 - 0x20, SEEK_CUR);
fread (&header, 1, sizeof(header), ifp);
raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f));
raw_width = width = header.uwidth;
raw_height = height = header.uheight;
filters = 0x16161616; /* default Bayer order is 2, BGGR */
switch (header.bayer_order) {
case 0: /* RGGB */
filters = 0x94949494;
break;
case 1: /* GBRG */
filters = 0x49494949;
break;
case 3: /* GRBG */
filters = 0x61616161;
break;
}
}
void CLASS broadcom_load_raw() {
uchar *data, *dp;
int rev, row, col, c;
rev = 3 * (order == 0x4949);
data = (uchar *) malloc (raw_stride*2);
merror (data, "broadcom_load_raw()");
for (row=0; row < raw_height; row++) {
if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror();
FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)];
for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free (data);
}
#endif
void CLASS nokia_load_raw()
{
uchar *data, *dp;
int rev, dwide, row, col, c;
double sum[]={0,0};
rev = 3 * (order == 0x4949);
dwide = (raw_width * 5 + 1) / 4;
data = (uchar *) malloc (dwide*2);
merror (data, "nokia_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (data+dwide, 1, dwide, ifp) < dwide) derror();
FORC(dwide) data[c] = data[dwide+(c ^ rev)];
for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...){
free (data);
throw;
}
#endif
free (data);
maximum = 0x3ff;
if (strncmp(make,"OmniVision",10)) return;
row = raw_height/2;
FORC(width-1) {
sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1));
sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1));
}
if (sum[1] > sum[0]) filters = 0x4b4b4b4b;
}
void CLASS android_tight_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
bwide = -(-5*raw_width >> 5) << 3;
data = (uchar *) malloc (bwide);
merror (data, "android_tight_load_raw()");
for (row=0; row < raw_height; row++) {
if (fread (data, 1, bwide, ifp) < bwide) derror();
for (dp=data, col=0; col < raw_width; dp+=5, col+=4)
FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3);
}
free (data);
}
void CLASS android_loose_load_raw()
{
uchar *data, *dp;
int bwide, row, col, c;
UINT64 bitbuf=0;
bwide = (raw_width+5)/6 << 3;
data = (uchar *) malloc (bwide);
merror (data, "android_loose_load_raw()");
for (row=0; row < raw_height; row++) {
if (fread (data, 1, bwide, ifp) < bwide) derror();
for (dp=data, col=0; col < raw_width; dp+=8, col+=6) {
FORC(8) bitbuf = (bitbuf << 8) | dp[c^7];
FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff;
}
}
free (data);
}
void CLASS canon_rmf_load_raw()
{
int row, col, bits, orow, ocol, c;
#ifdef LIBRAW_LIBRARY_BUILD
int *words = (int*)malloc(sizeof(int)*(raw_width/3+1));
merror(words,"canon_rmf_load_raw");
#endif
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
fread(words,sizeof(int),raw_width/3,ifp);
for (col=0; col < raw_width-2; col+=3)
{
bits = words[col/3];
FORC3 {
orow = row;
if ((ocol = col+c-4) < 0)
{
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff];
}
}
#else
for (col=0; col < raw_width-2; col+=3) {
bits = get4();
FORC3 {
orow = row;
if ((ocol = col+c-4) < 0) {
ocol += raw_width;
if ((orow -= 2) < 0)
orow += raw_height;
}
RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff];
}
}
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
free(words);
#endif
maximum = curve[0x3ff];
}
unsigned CLASS pana_bits (int nbits)
{
#ifndef LIBRAW_NOTHREADS
#define buf tls->pana_bits.buf
#define vbits tls->pana_bits.vbits
#else
static uchar buf[0x4000];
static int vbits;
#endif
int byte;
if (!nbits) return vbits=0;
if (!vbits) {
fread (buf+load_flags, 1, 0x4000-load_flags, ifp);
fread (buf, 1, load_flags, ifp);
}
vbits = (vbits - nbits) & 0x1ffff;
byte = vbits >> 3 ^ 0x3ff0;
return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits);
#ifndef LIBRAW_NOTHREADS
#undef buf
#undef vbits
#endif
}
void CLASS panasonic_load_raw()
{
int row, col, i, j, sh=0, pred[2], nonz[2];
pana_bits(0);
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
if ((i = col % 14) == 0)
pred[0] = pred[1] = nonz[0] = nonz[1] = 0;
if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2));
if (nonz[i & 1]) {
if ((j = pana_bits(8))) {
if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4)
pred[i & 1] &= ~((~0u) << sh);
pred[i & 1] += j << sh;
}
} else if ((nonz[i & 1] = pana_bits(8)) || i > 11)
pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4);
if ((RAW(row,col) = pred[col & 1]) > 4098 && col < width) derror();
}
}
}
void CLASS olympus_load_raw()
{
ushort huff[4096];
int row, col, nbits, sign, low, high, i, c, w, n, nw;
int acarry[2][3], *carry, pred, diff;
huff[n=0] = 0xc0c;
for (i=12; i--; )
FORC(2048 >> i) huff[++n] = (i+1) << 8 | i;
fseek (ifp, 7, SEEK_CUR);
getbits(-1);
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset (acarry, 0, sizeof acarry);
for (col=0; col < raw_width; col++) {
carry = acarry[col & 1];
i = 2 * (carry[2] < 3);
for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++);
low = (sign = getbits(3)) & 3;
sign = sign << 29 >> 31;
if ((high = getbithuff(12,huff)) == 12)
high = getbits(16-nbits) >> 1;
carry[0] = (high << nbits) | getbits(nbits);
diff = (carry[0] ^ sign) + carry[1];
carry[1] = (diff*3 + carry[1]) >> 5;
carry[2] = carry[0] > 16 ? 0 : carry[2]+1;
if (col >= width) continue;
if (row < 2 && col < 2) pred = 0;
else if (row < 2) pred = RAW(row,col-2);
else if (col < 2) pred = RAW(row-2,col);
else {
w = RAW(row,col-2);
n = RAW(row-2,col);
nw = RAW(row-2,col-2);
if ((w < nw && nw < n) || (n < nw && nw < w)) {
if (ABS(w-nw) > 32 || ABS(n-nw) > 32)
pred = w + n - nw;
else pred = (w + n) >> 1;
} else pred = ABS(w-nw) > ABS(n-nw) ? w : n;
}
if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror();
}
}
}
void CLASS minolta_rd175_load_raw()
{
uchar pixel[768];
unsigned irow, box, row, col;
for (irow=0; irow < 1481; irow++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, 768, ifp) < 768) derror();
box = irow / 82;
row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2);
switch (irow) {
case 1477: case 1479: continue;
case 1476: row = 984; break;
case 1480: row = 985; break;
case 1478: row = 985; box = 1;
}
if ((box < 12) && (box & 1)) {
for (col=0; col < 1533; col++, row ^= 1)
if (col != 1) RAW(row,col) = (col+1) & 2 ?
pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1;
RAW(row,1) = pixel[1] << 1;
RAW(row,1533) = pixel[765] << 1;
} else
for (col=row & 1; col < 1534; col+=2)
RAW(row,col) = pixel[col/2] << 1;
}
maximum = 0xff << 1;
}
void CLASS quicktake_100_load_raw()
{
uchar pixel[484][644];
static const short gstep[16] =
{ -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 };
static const short rstep[6][4] =
{ { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 },
{ -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } };
static const short t_curve[256] =
{ 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,
54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78,
79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116,
118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155,
158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195,
197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244,
248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322,
326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400,
405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479,
483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643,
654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844,
855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 };
int rb, row, col, sharp, val=0;
getbits(-1);
memset (pixel, 0x80, sizeof pixel);
for (row=2; row < height+2; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=2+(row & 1); col < width+2; col+=2) {
val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] +
pixel[row][col-2]) >> 2) + gstep[getbits(4)];
pixel[row][col] = val = LIM(val,0,255);
if (col < 4)
pixel[row][col-2] = pixel[row+1][~row & 1] = val;
if (row == 2)
pixel[row-1][col+1] = pixel[row-1][col+3] = val;
}
pixel[row][col] = val;
}
for (rb=0; rb < 2; rb++)
for (row=2+rb; row < height+2; row+=2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=3-(row & 1); col < width+2; col+=2) {
if (row < 4 || col < 4) sharp = 2;
else {
val = ABS(pixel[row-2][col] - pixel[row][col-2])
+ ABS(pixel[row-2][col] - pixel[row-2][col-2])
+ ABS(pixel[row][col-2] - pixel[row-2][col-2]);
sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 :
val < 32 ? 3 : val < 48 ? 4 : 5;
}
val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1)
+ rstep[sharp][getbits(2)];
pixel[row][col] = val = LIM(val,0,255);
if (row < 4) pixel[row-2][col+2] = val;
if (col < 4) pixel[row+2][col-2] = val;
}
}
for (row=2; row < height+2; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=3-(row & 1); col < width+2; col+=2) {
val = ((pixel[row][col-1] + (pixel[row][col] << 2) +
pixel[row][col+1]) >> 1) - 0x100;
pixel[row][col] = LIM(val,0,255);
}
}
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++)
RAW(row,col) = t_curve[pixel[row+2][col+2]];
}
maximum = 0x3ff;
}
#define radc_token(tree) ((signed char) getbithuff(8,huff[tree]))
#define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--)
#define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \
: (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4)
#ifdef __GNUC__
# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
# pragma GCC optimize("no-aggressive-loop-optimizations")
# endif
#endif
void CLASS kodak_radc_load_raw()
{
static const signed char src[] = {
1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8,
1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8,
2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8,
2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8,
2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8,
2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8,
2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8,
2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8,
2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4,
2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8,
1,0, 2,2, 2,-2,
1,-3, 1,3,
2,-17, 2,-5, 2,5, 2,17,
2,-7, 2,2, 2,9, 2,18,
2,-18, 2,-9, 2,-2, 2,7,
2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79,
2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76,
2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37
};
ushort huff[19][256];
int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val;
short last[3] = { 16,16,16 }, mul[3], buf[3][3][386];
static const ushort pt[] =
{ 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 };
for (i=2; i < 12; i+=2)
for (c=pt[i-2]; c <= pt[i]; c++)
curve[c] = (float)
(c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5;
for (s=i=0; i < sizeof src; i+=2)
FORC(256 >> src[i])
((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1];
s = kodak_cbpp == 243 ? 2 : 3;
FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1);
getbits(-1);
for (i=0; i < sizeof(buf)/sizeof(short); i++)
((short *)buf)[i] = 2048;
for (row=0; row < height; row+=4) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
FORC3 mul[c] = getbits(6);
#ifdef LIBRAW_LIBRARY_BUILD
if(!mul[0] || !mul[1] || !mul[2])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
FORC3 {
val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c];
s = val > 65564 ? 10:12;
x = ~((~0u) << (s-1));
val <<= 12-s;
for (i=0; i < sizeof(buf[0])/sizeof(short); i++)
((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s;
last[c] = mul[c];
for (r=0; r <= !c; r++) {
buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7;
for (tree=1, col=width/2; col > 0; ) {
if ((tree = radc_token(tree))) {
col -= 2;
if (tree == 8)
FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c];
else
FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR;
} else
do {
nreps = (col > 2) ? radc_token(9) + 1 : 1;
for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) {
col -= 2;
FORYX buf[c][y][x] = PREDICTOR;
if (rep & 1) {
step = radc_token(10) << 4;
FORYX buf[c][y][x] += step;
}
}
} while (nreps == 9);
}
for (y=0; y < 2; y++)
for (x=0; x < width/2; x++) {
val = (buf[c][y+1][x] << 4) / mul[c];
if (val < 0) val = 0;
if (c) RAW(row+y*2+c-1,x*2+2-c) = val;
else RAW(row+r*2+y,x*2+y) = val;
}
memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c);
}
}
for (y=row; y < row+4; y++)
for (x=0; x < width; x++)
if ((x+y) & 1) {
r = x ? x-1 : x+1;
s = x+1 < width ? x+1 : x-1;
val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2;
if (val < 0) val = 0;
RAW(y,x) = val;
}
}
for (i=0; i < height*width; i++)
raw_image[i] = curve[raw_image[i]];
maximum = 0x3fff;
}
#undef FORYX
#undef PREDICTOR
#ifdef NO_JPEG
void CLASS kodak_jpeg_load_raw() {}
void CLASS lossy_dng_load_raw() {}
#else
#ifndef LIBRAW_LIBRARY_BUILD
METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo)
{
static uchar jpeg_buffer[4096];
size_t nbytes;
nbytes = fread (jpeg_buffer, 1, 4096, ifp);
swab (jpeg_buffer, jpeg_buffer, nbytes);
cinfo->src->next_input_byte = jpeg_buffer;
cinfo->src->bytes_in_buffer = nbytes;
return TRUE;
}
void CLASS kodak_jpeg_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE (*pixel)[3];
int row, col;
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_decompress (&cinfo);
jpeg_stdio_src (&cinfo, ifp);
cinfo.src->fill_input_buffer = fill_input_buffer;
jpeg_read_header (&cinfo, TRUE);
jpeg_start_decompress (&cinfo);
if ((cinfo.output_width != width ) ||
(cinfo.output_height*2 != height ) ||
(cinfo.output_components != 3 )) {
fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname);
jpeg_destroy_decompress (&cinfo);
longjmp (failure, 3);
}
buf = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1);
while (cinfo.output_scanline < cinfo.output_height) {
row = cinfo.output_scanline * 2;
jpeg_read_scanlines (&cinfo, buf, 1);
pixel = (JSAMPLE (*)[3]) buf[0];
for (col=0; col < width; col+=2) {
RAW(row+0,col+0) = pixel[col+0][1] << 1;
RAW(row+1,col+1) = pixel[col+1][1] << 1;
RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
}
}
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
maximum = 0xff << 1;
}
#else
struct jpegErrorManager {
struct jpeg_error_mgr pub;
};
static void jpegErrorExit (j_common_ptr cinfo)
{
jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err;
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
// LibRaw's Kodak_jpeg_load_raw
void CLASS kodak_jpeg_load_raw()
{
if(data_size < 1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
int row, col;
jpegErrorManager jerr;
struct jpeg_decompress_struct cinfo;
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = jpegErrorExit;
unsigned char *jpg_buf = (unsigned char *)malloc(data_size);
merror(jpg_buf,"kodak_jpeg_load_raw");
unsigned char *pixel_buf = (unsigned char*) malloc(width*3);
jpeg_create_decompress (&cinfo);
merror(pixel_buf,"kodak_jpeg_load_raw");
fread(jpg_buf,data_size,1,ifp);
swab ((char*)jpg_buf, (char*)jpg_buf, data_size);
try
{
jpeg_mem_src(&cinfo, jpg_buf, data_size);
int rc = jpeg_read_header(&cinfo, TRUE);
if(rc!=1)
throw LIBRAW_EXCEPTION_DECODE_JPEG;
jpeg_start_decompress (&cinfo);
if ((cinfo.output_width != width ) ||
(cinfo.output_height*2 != height ) ||
(cinfo.output_components != 3 ))
{
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
unsigned char *buf[1];
buf[0] = pixel_buf;
while (cinfo.output_scanline < cinfo.output_height)
{
checkCancel();
row = cinfo.output_scanline * 2;
jpeg_read_scanlines (&cinfo, buf, 1);
unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0];
for (col=0; col < width; col+=2) {
RAW(row+0,col+0) = pixel[col+0][1] << 1;
RAW(row+1,col+1) = pixel[col+1][1] << 1;
RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0];
RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2];
}
}
}
catch (...)
{
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
free(jpg_buf);
free(pixel_buf);
throw;
}
jpeg_finish_decompress (&cinfo);
jpeg_destroy_decompress (&cinfo);
free(jpg_buf);
free(pixel_buf);
maximum = 0xff << 1;
}
#endif
#ifndef LIBRAW_LIBRARY_BUILD
void CLASS gamma_curve (double pwr, double ts, int mode, int imax);
#endif
void CLASS lossy_dng_load_raw()
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
JSAMPARRAY buf;
JSAMPLE (*pixel)[3];
unsigned sorder=order, ntags, opcode, deg, i, j, c;
unsigned save=data_offset-4, trow=0, tcol=0, row, col;
ushort cur[3][256];
double coeff[9], tot;
if (meta_offset) {
fseek (ifp, meta_offset, SEEK_SET);
order = 0x4d4d;
ntags = get4();
while (ntags--) {
opcode = get4(); get4(); get4();
if (opcode != 8)
{ fseek (ifp, get4(), SEEK_CUR); continue; }
fseek (ifp, 20, SEEK_CUR);
if ((c = get4()) > 2) break;
fseek (ifp, 12, SEEK_CUR);
if ((deg = get4()) > 8) break;
for (i=0; i <= deg && i < 9; i++)
coeff[i] = getreal(12);
for (i=0; i < 256; i++) {
for (tot=j=0; j <= deg; j++)
tot += coeff[j] * pow(i/255.0, (int)j);
cur[c][i] = tot*0xffff;
}
}
order = sorder;
} else {
gamma_curve (1/2.4, 12.92, 1, 255);
FORC3 memcpy (cur[c], curve, sizeof cur[0]);
}
cinfo.err = jpeg_std_error (&jerr);
jpeg_create_decompress (&cinfo);
while (trow < raw_height) {
fseek (ifp, save+=4, SEEK_SET);
if (tile_length < INT_MAX)
fseek (ifp, get4(), SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1)
{
jpeg_destroy_decompress(&cinfo);
throw LIBRAW_EXCEPTION_DECODE_JPEG;
}
#else
jpeg_stdio_src (&cinfo, ifp);
#endif
jpeg_read_header (&cinfo, TRUE);
jpeg_start_decompress (&cinfo);
buf = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1);
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
while (cinfo.output_scanline < cinfo.output_height &&
(row = trow + cinfo.output_scanline) < height) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jpeg_read_scanlines (&cinfo, buf, 1);
pixel = (JSAMPLE (*)[3]) buf[0];
for (col=0; col < cinfo.output_width && tcol+col < width; col++) {
FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
jpeg_destroy_decompress (&cinfo);
throw;
}
#endif
jpeg_abort_decompress (&cinfo);
if ((tcol += tile_width) >= raw_width)
trow += tile_length + (tcol = 0);
}
jpeg_destroy_decompress (&cinfo);
maximum = 0xffff;
}
#endif
void CLASS kodak_dc120_load_raw()
{
static const int mul[4] = { 162, 192, 187, 92 };
static const int add[4] = { 0, 636, 424, 212 };
uchar pixel[848];
int row, shift, col;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, 848, ifp) < 848) derror();
shift = row * mul[row & 3] + add[row & 3];
for (col=0; col < width; col++)
RAW(row,col) = (ushort) pixel[(col + shift) % 848];
}
maximum = 0xff;
}
void CLASS eight_bit_load_raw()
{
uchar *pixel;
unsigned row, col;
pixel = (uchar *) calloc (raw_width, sizeof *pixel);
merror (pixel, "eight_bit_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, 1, raw_width, ifp) < raw_width) derror();
for (col=0; col < raw_width; col++)
RAW(row,col) = curve[pixel[col]];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_c330_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel);
merror (pixel, "kodak_c330_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (fread (pixel, raw_width, 2, ifp) < 2) derror();
if (load_flags && (row & 31) == 31)
fseek (ifp, raw_width*32, SEEK_CUR);
for (col=0; col < width; col++) {
y = pixel[col*2];
cb = pixel[(col*2 & -4) | 1] - 128;
cr = pixel[(col*2 & -4) | 3] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_c603_load_raw()
{
uchar *pixel;
int row, col, y, cb, cr, rgb[3], c;
pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel);
merror (pixel, "kodak_c603_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if (~row & 1)
if (fread (pixel, raw_width, 3, ifp) < 3) derror();
for (col=0; col < width; col++) {
y = pixel[width*2*(row & 1) + col];
cb = pixel[width + (col & -2)] - 128;
cr = pixel[width + (col & -2)+1] - 128;
rgb[1] = y - ((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)];
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
maximum = curve[0xff];
}
void CLASS kodak_262_load_raw()
{
static const uchar kodak_tree[2][26] =
{ { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 },
{ 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } };
ushort *huff[2];
uchar *pixel;
int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val;
FORC(2) huff[c] = make_decoder (kodak_tree[c]);
ns = (raw_height+63) >> 5;
pixel = (uchar *) malloc (raw_width*32 + ns*4);
merror (pixel, "kodak_262_load_raw()");
strip = (int *) (pixel + raw_width*32);
order = 0x4d4d;
FORC(ns) strip[c] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
if ((row & 31) == 0) {
fseek (ifp, strip[row >> 5], SEEK_SET);
getbits(-1);
pi = 0;
}
for (col=0; col < raw_width; col++) {
chess = (row + col) & 1;
pi1 = chess ? pi-2 : pi-raw_width-1;
pi2 = chess ? pi-2*raw_width : pi-raw_width+1;
if (col <= chess) pi1 = -1;
if (pi1 < 0) pi1 = pi2;
if (pi2 < 0) pi2 = pi1;
if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2;
pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1;
pixel[pi] = val = pred + ljpeg_diff (huff[chess]);
if (val >> 8) derror();
val = curve[pixel[pi++]];
RAW(row,col) = val;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (pixel);
throw;
}
#endif
free (pixel);
FORC(2) free (huff[c]);
}
int CLASS kodak_65000_decode (short *out, int bsize)
{
uchar c, blen[768];
ushort raw[6];
INT64 bitbuf=0;
int save, bits=0, i, j, len, diff;
save = ftell(ifp);
bsize = (bsize + 3) & -4;
for (i=0; i < bsize; i+=2) {
c = fgetc(ifp);
if ((blen[i ] = c & 15) > 12 ||
(blen[i+1] = c >> 4) > 12 ) {
fseek (ifp, save, SEEK_SET);
for (i=0; i < bsize; i+=8) {
read_shorts (raw, 6);
out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12;
out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12;
for (j=0; j < 6; j++)
out[i+2+j] = raw[j] & 0xfff;
}
return 1;
}
}
if ((bsize & 7) == 4) {
bitbuf = fgetc(ifp) << 8;
bitbuf += fgetc(ifp);
bits = 16;
}
for (i=0; i < bsize; i++) {
len = blen[i];
if (bits < len) {
for (j=0; j < 32; j+=8)
bitbuf += (INT64) fgetc(ifp) << (bits+(j^8));
bits += 32;
}
diff = bitbuf & (0xffff >> (16-len));
bitbuf >>= len;
bits -= len;
if ((diff & (1 << (len-1))) == 0)
diff -= (1 << len) - 1;
out[i] = diff;
}
return 0;
}
void CLASS kodak_65000_load_raw()
{
short buf[256];
int row, col, len, pred[2], ret, i;
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=256) {
pred[0] = pred[1] = 0;
len = MIN (256, width-col);
ret = kodak_65000_decode (buf, len);
for (i=0; i < len; i++)
if ((RAW(row,col+i) = curve[ret ? buf[i] :
(pred[i & 1] += buf[i])]) >> 12) derror();
}
}
}
void CLASS kodak_ycbcr_load_raw()
{
short buf[384], *bp;
int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3];
ushort *ip;
if (!image) return;
unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10;
for (row=0; row < height; row+=2)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=128) {
len = MIN (128, width-col);
kodak_65000_decode (buf, len*3);
y[0][1] = y[1][1] = cb = cr = 0;
for (bp=buf, i=0; i < len; i+=2, bp+=2) {
cb += bp[4];
cr += bp[5];
rgb[1] = -((cb + cr + 2) >> 2);
rgb[2] = rgb[1] + cb;
rgb[0] = rgb[1] + cr;
for (j=0; j < 2; j++)
for (k=0; k < 2; k++) {
if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror();
ip = image[(row+j)*width + col+i+k];
FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)];
}
}
}
}
}
void CLASS kodak_rgb_load_raw()
{
short buf[768], *bp;
int row, col, len, c, i, rgb[3],ret;
ushort *ip=image[0];
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col+=256) {
len = MIN (256, width-col);
ret = kodak_65000_decode (buf, len*3);
memset (rgb, 0, sizeof rgb);
for (bp=buf, i=0; i < len; i++, ip+=4)
#ifdef LIBRAW_LIBRARY_BUILD
if(load_flags == 12)
{
FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++);
}
else
#endif
FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror();
}
}
}
void CLASS kodak_thumb_load_raw()
{
int row, col;
colors = thumb_misc >> 5;
for (row=0; row < height; row++)
for (col=0; col < width; col++)
read_shorts (image[row*width+col], colors);
maximum = (1 << (thumb_misc & 31)) - 1;
}
void CLASS sony_decrypt (unsigned *data, int len, int start, int key)
{
#ifndef LIBRAW_NOTHREADS
#define pad tls->sony_decrypt.pad
#define p tls->sony_decrypt.p
#else
static unsigned pad[128], p;
#endif
if (start) {
for (p=0; p < 4; p++)
pad[p] = key = key * 48828125 + 1;
pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31;
for (p=4; p < 127; p++)
pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31;
for (p=0; p < 127; p++)
pad[p] = htonl(pad[p]);
}
while (len--)
{
*data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127];
p++;
}
#ifndef LIBRAW_NOTHREADS
#undef pad
#undef p
#endif
}
void CLASS sony_load_raw()
{
uchar head[40];
ushort *pixel;
unsigned i, key, row, col;
fseek (ifp, 200896, SEEK_SET);
fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR);
order = 0x4d4d;
key = get4();
fseek (ifp, 164600, SEEK_SET);
fread (head, 1, 40, ifp);
sony_decrypt ((unsigned *) head, 10, 1, key);
for (i=26; i-- > 22; )
key = key << 8 | head[i];
fseek (ifp, data_offset, SEEK_SET);
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pixel = raw_image + row*raw_width;
if (fread (pixel, 2, raw_width, ifp) < raw_width) derror();
sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key);
for (col=0; col < raw_width; col++)
if ((pixel[col] = ntohs(pixel[col])) >> 14) derror();
}
maximum = 0x3ff0;
}
void CLASS sony_arw_load_raw()
{
ushort huff[32770];
static const ushort tab[18] =
{ 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809,
0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 };
int i, c, n, col, row, sum=0;
huff[0] = 15;
for (n=i=0; i < 18; i++)
FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (col = raw_width; col--; )
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (row=0; row < raw_height+1; row+=2) {
if (row == raw_height) row = 1;
if ((sum += ljpeg_diff(huff)) >> 12) derror();
if (row < height) RAW(row,col) = sum;
}
}
}
void CLASS sony_arw2_load_raw()
{
uchar *data, *dp;
ushort pix[16];
int row, col, val, max, min, imax, imin, sh, bit, i;
data = (uchar *) malloc (raw_width+1);
merror (data, "sony_arw2_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
try {
#endif
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fread (data, 1, raw_width, ifp);
for (dp=data, col=0; col < raw_width-30; dp+=16) {
max = 0x7ff & (val = sget4(dp));
min = 0x7ff & val >> 11;
imax = 0x0f & val >> 22;
imin = 0x0f & val >> 26;
for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++);
#ifdef LIBRAW_LIBRARY_BUILD
/* flag checks if outside of loop */
if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set
|| (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else pix[i]=0;
}
else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = 0;
else if (i == imin) pix[i] = 0;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE)
{
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = 0;
else if (i == imin) pix[i] = 0;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh);
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
}
#else
/* unaltered dcraw processing */
for (bit=30, i=0; i < 16; i++)
if (i == imax) pix[i] = max;
else if (i == imin) pix[i] = min;
else {
pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min;
if (pix[i] > 0x7ff) pix[i] = 0x7ff;
bit += 7;
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
{
for (i=0; i < 16; i++, col+=2)
{
unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2];
unsigned step = 1 << sh;
RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr?
LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0;
}
}
else
{
for (i=0; i < 16; i++, col+=2)
RAW(row,col) = curve[pix[i] << 1];
}
#else
for (i=0; i < 16; i++, col+=2)
RAW(row,col) = curve[pix[i] << 1] >> 2;
#endif
col -= col & 1 ? 1:31;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch(...) {
free (data);
throw;
}
if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)
maximum=10000;
#endif
free (data);
}
void CLASS samsung_load_raw()
{
int row, col, c, i, dir, op[4], len[4];
order = 0x4949;
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, strip_offset+row*4, SEEK_SET);
fseek (ifp, data_offset+get4(), SEEK_SET);
ph1_bits(-1);
FORC4 len[c] = row < 2 ? 7:4;
for (col=0; col < raw_width; col+=16) {
dir = ph1_bits(1);
FORC4 op[c] = ph1_bits(2);
FORC4 switch (op[c]) {
case 3: len[c] = ph1_bits(4); break;
case 2: len[c]--; break;
case 1: len[c]++;
}
for (c=0; c < 16; c+=2) {
i = len[((c & 1) << 1) | (c >> 3)];
RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) +
(dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128);
if (c == 14) c = -1;
}
}
}
for (row=0; row < raw_height-1; row+=2)
for (col=0; col < raw_width-1; col+=2)
SWAP (RAW(row,col+1), RAW(row+1,col));
}
void CLASS samsung2_load_raw()
{
static const ushort tab[14] =
{ 0x304,0x307,0x206,0x205,0x403,0x600,0x709,
0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 };
ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2];
int i, c, n, row, col, diff;
huff[0] = 10;
for (n=i=0; i < 14; i++)
FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i];
getbits(-1);
for (row=0; row < raw_height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < raw_width; col++) {
diff = ljpeg_diff (huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
RAW(row,col) = hpred[col & 1];
if (hpred[col & 1] >> tiff_bps) derror();
}
}
}
void CLASS samsung3_load_raw()
{
int opt, init, mag, pmode, row, tab, col, pred, diff, i, c;
ushort lent[3][2], len[4], *prow[2];
order = 0x4949;
fseek (ifp, 9, SEEK_CUR);
opt = fgetc(ifp);
init = (get2(),get2());
for (row=0; row < raw_height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR);
ph1_bits(-1);
mag = 0; pmode = 7;
FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4;
prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green
prow[~row & 1] = &RAW(row-2,0); // red and blue
for (tab=0; tab+15 < raw_width; tab+=16) {
if (~opt & 4 && !(tab & 63)) {
i = ph1_bits(2);
mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12);
}
if (opt & 2)
pmode = 7 - 4*ph1_bits(1);
else if (!ph1_bits(1))
pmode = ph1_bits(3);
if (opt & 1 || !ph1_bits(1)) {
FORC4 len[c] = ph1_bits(2);
FORC4 {
i = ((row & 1) << 1 | (c & 1)) % 3;
len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4);
lent[i][0] = lent[i][1];
lent[i][1] = len[c];
}
}
FORC(16) {
col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1));
pred = (pmode == 7 || row < 2)
? (tab ? RAW(row,tab-2+(col & 1)) : init)
: (prow[col & 1][col-'4'+"0224468"[pmode]] +
prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1;
diff = ph1_bits (i = len[c >> 2]);
if (diff >> (i-1)) diff -= 1 << i;
diff = diff * (mag*2+1) + mag;
RAW(row,col) = pred + diff;
}
}
}
}
#define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1)
/* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */
void CLASS smal_decode_segment (unsigned seg[2][2], int holes)
{
uchar hist[3][13] = {
{ 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
{ 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 },
{ 3, 3, 0, 0, 63, 47, 31, 15, 0 } };
int low, high=0xff, carry=0, nbits=8;
int pix, s, count, bin, next, i, sym[3];
uchar diff, pred[]={0,0};
ushort data=0, range=0;
fseek (ifp, seg[0][1]+1, SEEK_SET);
getbits(-1);
if (seg[1][0] > raw_width*raw_height)
seg[1][0] = raw_width*raw_height;
for (pix=seg[0][0]; pix < seg[1][0]; pix++) {
for (s=0; s < 3; s++) {
data = data << nbits | getbits(nbits);
if (carry < 0)
carry = (nbits += carry+1) < 1 ? nbits-1 : 0;
while (--nbits >= 0)
if ((data >> nbits & 0xff) == 0xff) break;
if (nbits > 0)
data = ((data & ((1 << (nbits-1)) - 1)) << 1) |
((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits));
if (nbits >= 0) {
data += getbits(1);
carry = nbits - 8;
}
count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4);
for (bin=0; hist[s][bin+5] > count; bin++);
low = hist[s][bin+5] * (high >> 4) >> 2;
if (bin) high = hist[s][bin+4] * (high >> 4) >> 2;
high -= low;
for (nbits=0; high << nbits < 128; nbits++);
range = (range+low) << nbits;
high <<= nbits;
next = hist[s][1];
if (++hist[s][2] > hist[s][3]) {
next = (next+1) & hist[s][0];
hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2;
hist[s][2] = 1;
}
if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) {
if (bin < hist[s][1])
for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--;
else if (next <= bin)
for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++;
}
hist[s][1] = next;
sym[s] = bin;
}
diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3);
if (sym[0] & 4)
diff = diff ? -diff : 0x80;
if (ftell(ifp) + 12 >= seg[1][1])
diff = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if(pix>=raw_width*raw_height)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
raw_image[pix] = pred[pix & 1] += diff;
if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2;
}
maximum = 0xff;
}
void CLASS smal_v6_load_raw()
{
unsigned seg[2][2];
fseek (ifp, 16, SEEK_SET);
seg[0][0] = 0;
seg[0][1] = get2();
seg[1][0] = raw_width * raw_height;
seg[1][1] = INT_MAX;
smal_decode_segment (seg, 0);
}
int CLASS median4 (int *p)
{
int min, max, sum, i;
min = max = sum = p[0];
for (i=1; i < 4; i++) {
sum += p[i];
if (min > p[i]) min = p[i];
if (max < p[i]) max = p[i];
}
return (sum - min - max) >> 1;
}
void CLASS fill_holes (int holes)
{
int row, col, val[4];
for (row=2; row < height-2; row++) {
if (!HOLE(row)) continue;
for (col=1; col < width-1; col+=4) {
val[0] = RAW(row-1,col-1);
val[1] = RAW(row-1,col+1);
val[2] = RAW(row+1,col-1);
val[3] = RAW(row+1,col+1);
RAW(row,col) = median4(val);
}
for (col=2; col < width-2; col+=4)
if (HOLE(row-2) || HOLE(row+2))
RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1;
else {
val[0] = RAW(row,col-2);
val[1] = RAW(row,col+2);
val[2] = RAW(row-2,col);
val[3] = RAW(row+2,col);
RAW(row,col) = median4(val);
}
}
}
void CLASS smal_v9_load_raw()
{
unsigned seg[256][2], offset, nseg, holes, i;
fseek (ifp, 67, SEEK_SET);
offset = get4();
nseg = (uchar) fgetc(ifp);
fseek (ifp, offset, SEEK_SET);
for (i=0; i < nseg*2; i++)
((unsigned *)seg)[i] = get4() + data_offset*(i & 1);
fseek (ifp, 78, SEEK_SET);
holes = fgetc(ifp);
fseek (ifp, 88, SEEK_SET);
seg[nseg][0] = raw_height * raw_width;
seg[nseg][1] = get4() + data_offset;
for (i=0; i < nseg; i++)
smal_decode_segment (seg+i, holes);
if (holes) fill_holes (holes);
}
void CLASS redcine_load_raw()
{
#ifndef NO_JASPER
int c, row, col;
jas_stream_t *in;
jas_image_t *jimg;
jas_matrix_t *jmat;
jas_seqent_t *data;
ushort *img, *pix;
jas_init();
#ifndef LIBRAW_LIBRARY_BUILD
in = jas_stream_fopen (ifname, "rb");
#else
in = (jas_stream_t*)ifp->make_jas_stream();
if(!in)
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
#endif
jas_stream_seek (in, data_offset+20, SEEK_SET);
jimg = jas_image_decode (in, -1, 0);
#ifndef LIBRAW_LIBRARY_BUILD
if (!jimg) longjmp (failure, 3);
#else
if(!jimg)
{
jas_stream_close (in);
throw LIBRAW_EXCEPTION_DECODE_JPEG2000;
}
#endif
jmat = jas_matrix_create (height/2, width/2);
merror (jmat, "redcine_load_raw()");
img = (ushort *) calloc ((height+2), (width+2)*2);
merror (img, "redcine_load_raw()");
#ifdef LIBRAW_LIBRARY_BUILD
bool fastexitflag = false;
try {
#endif
FORC4 {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat);
data = jas_matrix_getref (jmat, 0, 0);
for (row = c >> 1; row < height; row+=2)
for (col = c & 1; col < width; col+=2)
img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2];
}
for (col=1; col <= width; col++) {
img[col] = img[2*(width+2)+col];
img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col];
}
for (row=0; row < height+2; row++) {
img[row*(width+2)] = img[row*(width+2)+2];
img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3];
}
for (row=1; row <= height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1));
for ( ; col <= width; col+=2, pix+=2) {
c = (((pix[0] - 0x800) << 3) +
pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2;
pix[0] = LIM(c,0,4095);
}
}
for (row=0; row < height; row++)
{
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++)
RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]];
}
#ifdef LIBRAW_LIBRARY_BUILD
} catch (...) {
fastexitflag=true;
}
#endif
free (img);
jas_matrix_destroy (jmat);
jas_image_destroy (jimg);
jas_stream_close (in);
#ifdef LIBRAW_LIBRARY_BUILD
if(fastexitflag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
#endif
}
//@end COMMON
/* RESTRICTED code starts here */
void CLASS foveon_decoder (unsigned size, unsigned code)
{
static unsigned huff[1024];
struct decode *cur;
int i, len;
if (!code) {
for (i=0; i < size; i++)
huff[i] = get4();
memset (first_decode, 0, sizeof first_decode);
free_decode = first_decode;
}
cur = free_decode++;
if (free_decode > first_decode+2048) {
fprintf (stderr,_("%s: decoder table overflow\n"), ifname);
longjmp (failure, 2);
}
if (code)
for (i=0; i < size; i++)
if (huff[i] == code) {
cur->leaf = i;
return;
}
if ((len = code >> 27) > 26) return;
code = (len+1) << 27 | (code & 0x3ffffff) << 1;
cur->branch[0] = free_decode;
foveon_decoder (size, code);
cur->branch[1] = free_decode;
foveon_decoder (size, code+1);
}
void CLASS foveon_thumb()
{
unsigned bwide, row, col, bitbuf=0, bit=1, c, i;
char *buf;
struct decode *dindex;
short pred[3];
bwide = get4();
fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height);
if (bwide > 0) {
if (bwide < thumb_width*3) return;
buf = (char *) malloc (bwide);
merror (buf, "foveon_thumb()");
for (row=0; row < thumb_height; row++) {
fread (buf, 1, bwide, ifp);
fwrite (buf, 3, thumb_width, ofp);
}
free (buf);
return;
}
foveon_decoder (256, 0);
for (row=0; row < thumb_height; row++) {
memset (pred, 0, sizeof pred);
if (!bit) get4();
for (bit=col=0; col < thumb_width; col++)
FORC3 {
for (dindex=first_decode; dindex->branch[0]; ) {
if ((bit = (bit-1) & 31) == 31)
for (i=0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += dindex->leaf;
fputc (pred[c], ofp);
}
}
}
void CLASS foveon_sd_load_raw()
{
struct decode *dindex;
short diff[1024];
unsigned bitbuf=0;
int pred[3], row, col, bit=-1, c, i;
read_shorts ((ushort *) diff, 1024);
if (!load_flags) foveon_decoder (1024, 0);
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
memset (pred, 0, sizeof pred);
if (!bit && !load_flags && atoi(model+2) < 14) get4();
for (col=bit=0; col < width; col++) {
if (load_flags) {
bitbuf = get4();
FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff];
}
else FORC3 {
for (dindex=first_decode; dindex->branch[0]; ) {
if ((bit = (bit-1) & 31) == 31)
for (i=0; i < 4; i++)
bitbuf = (bitbuf << 8) + fgetc(ifp);
dindex = dindex->branch[bitbuf >> bit & 1];
}
pred[c] += diff[dindex->leaf];
if (pred[c] >> 16 && ~pred[c] >> 16) derror();
}
FORC3 image[row*width+col][c] = pred[c];
}
}
}
void CLASS foveon_huff (ushort *huff)
{
int i, j, clen, code;
huff[0] = 8;
for (i=0; i < 13; i++) {
clen = getc(ifp);
code = getc(ifp);
for (j=0; j < 256 >> clen; )
huff[code+ ++j] = clen << 8 | i;
}
get2();
}
void CLASS foveon_dp_load_raw()
{
unsigned c, roff[4], row, col, diff;
ushort huff[512], vpred[2][2], hpred[2];
fseek (ifp, 8, SEEK_CUR);
foveon_huff (huff);
roff[0] = 48;
FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16);
FORC3 {
fseek (ifp, data_offset+roff[c], SEEK_SET);
getbits(-1);
vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512;
for (row=0; row < height; row++) {
#ifdef LIBRAW_LIBRARY_BUILD
checkCancel();
#endif
for (col=0; col < width; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
image[row*width+col][c] = hpred[col & 1];
}
}
}
}
void CLASS foveon_load_camf()
{
unsigned type, wide, high, i, j, row, col, diff;
ushort huff[258], vpred[2][2] = {{512,512},{512,512}}, hpred[2];
fseek (ifp, meta_offset, SEEK_SET);
type = get4(); get4(); get4();
wide = get4();
high = get4();
if (type == 2) {
fread (meta_data, 1, meta_length, ifp);
for (i=0; i < meta_length; i++) {
high = (high * 1597 + 51749) % 244944;
wide = high * (INT64) 301593171 >> 24;
meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17;
}
} else if (type == 4) {
free (meta_data);
meta_data = (char *) malloc (meta_length = wide*high*3/2);
merror (meta_data, "foveon_load_camf()");
foveon_huff (huff);
get4();
getbits(-1);
for (j=row=0; row < high; row++) {
for (col=0; col < wide; col++) {
diff = ljpeg_diff(huff);
if (col < 2) hpred[col] = vpred[row & 1][col] += diff;
else hpred[col & 1] += diff;
if (col & 1) {
meta_data[j++] = hpred[0] >> 4;
meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8;
meta_data[j++] = hpred[1];
}
}
}
}
#ifdef DCRAW_VERBOSE
else
fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type);
#endif
}
const char * CLASS foveon_camf_param (const char *block, const char *param)
{
unsigned idx, num;
char *pos, *cp, *dp;
for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
pos = meta_data + idx;
if (strncmp (pos, "CMb", 3)) break;
if (pos[3] != 'P') continue;
if (strcmp (block, pos+sget4(pos+12))) continue;
cp = pos + sget4(pos+16);
num = sget4(cp);
dp = pos + sget4(cp+4);
while (num--) {
cp += 8;
if (!strcmp (param, dp+sget4(cp)))
return dp+sget4(cp+4);
}
}
return 0;
}
void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name)
{
unsigned i, idx, type, ndim, size, *mat;
char *pos, *cp, *dp;
double dsize;
for (idx=0; idx < meta_length; idx += sget4(pos+8)) {
pos = meta_data + idx;
if (strncmp (pos, "CMb", 3)) break;
if (pos[3] != 'M') continue;
if (strcmp (name, pos+sget4(pos+12))) continue;
dim[0] = dim[1] = dim[2] = 1;
cp = pos + sget4(pos+16);
type = sget4(cp);
if ((ndim = sget4(cp+4)) > 3) break;
dp = pos + sget4(cp+8);
for (i=ndim; i--; ) {
cp += 12;
dim[i] = sget4(cp);
}
if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break;
mat = (unsigned *) malloc ((size = dsize) * 4);
merror (mat, "foveon_camf_matrix()");
for (i=0; i < size; i++)
if (type && type != 6)
mat[i] = sget4(dp + i*4);
else
mat[i] = sget4(dp + i*2) & 0xffff;
return mat;
}
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name);
#endif
return 0;
}
int CLASS foveon_fixed (void *ptr, int size, const char *name)
{
void *dp;
unsigned dim[3];
if (!name) return 0;
dp = foveon_camf_matrix (dim, name);
if (!dp) return 0;
memcpy (ptr, dp, size*4);
free (dp);
return 1;
}
float CLASS foveon_avg (short *pix, int range[2], float cfilt)
{
int i;
float val, min=FLT_MAX, max=-FLT_MAX, sum=0;
for (i=range[0]; i <= range[1]; i++) {
sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt;
if (min > val) min = val;
if (max < val) max = val;
}
if (range[1] - range[0] == 1) return sum/2;
return (sum - min - max) / (range[1] - range[0] - 1);
}
short * CLASS foveon_make_curve (double max, double mul, double filt)
{
short *curve;
unsigned i, size;
double x;
if (!filt) filt = 0.8;
size = 4*M_PI*max / filt;
if (size == UINT_MAX) size--;
curve = (short *) calloc (size+1, sizeof *curve);
merror (curve, "foveon_make_curve()");
curve[0] = size;
for (i=0; i < size; i++) {
x = i*filt/max/4;
curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5;
}
return curve;
}
void CLASS foveon_make_curves
(short **curvep, float dq[3], float div[3], float filt)
{
double mul[3], max=0;
int c;
FORC3 mul[c] = dq[c]/div[c];
FORC3 if (max < mul[c]) max = mul[c];
FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt);
}
int CLASS foveon_apply_curve (short *curve, int i)
{
if (abs(i) >= curve[0]) return 0;
return i < 0 ? -curve[1-i] : curve[1+i];
}
#define image ((short (*)[4]) image)
void CLASS foveon_interpolate()
{
static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 };
short *pix, prev[3], *curve[8], (*shrink)[3];
float cfilt=0, ddft[3][3][2], ppm[3][3][3];
float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3];
float chroma_dq[3], color_dq[3], diag[3][3], div[3];
float (*black)[3], (*sgain)[3], (*sgrow)[3];
float fsum[3], val, frow, num;
int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit;
int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3];
int work[3][3], smlast, smred, smred_p=0, dev[3];
int satlev[3], keep[4], active[4];
unsigned dim[3], *badpix;
double dsum=0, trsum[3];
char str[128];
const char* cp;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Foveon interpolation...\n"));
#endif
foveon_load_camf();
foveon_fixed (dscr, 4, "DarkShieldColRange");
foveon_fixed (ppm[0][0], 27, "PostPolyMatrix");
foveon_fixed (satlev, 3, "SaturationLevel");
foveon_fixed (keep, 4, "KeepImageArea");
foveon_fixed (active, 4, "ActiveImageArea");
foveon_fixed (chroma_dq, 3, "ChromaDQ");
foveon_fixed (color_dq, 3,
foveon_camf_param ("IncludeBlocks", "ColorDQ") ?
"ColorDQ" : "ColorDQCamRGB");
if (foveon_camf_param ("IncludeBlocks", "ColumnFilter"))
foveon_fixed (&cfilt, 1, "ColumnFilter");
memset (ddft, 0, sizeof ddft);
if (!foveon_camf_param ("IncludeBlocks", "DarkDrift")
|| !foveon_fixed (ddft[1][0], 12, "DarkDrift"))
for (i=0; i < 2; i++) {
foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop");
for (row = dstb[1]; row <= dstb[3]; row++)
for (col = dstb[0]; col <= dstb[2]; col++)
FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c];
FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1);
}
if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2)))
{
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2);
#endif
return; }
foveon_fixed (cam_xyz, 9, cp);
foveon_fixed (correct, 9,
foveon_camf_param ("WhiteBalanceCorrections", model2));
memset (last, 0, sizeof last);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j];
#define LAST(x,y) last[(i+x)%3][(c+y)%3]
for (i=0; i < 3; i++)
FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1);
#undef LAST
FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583;
sprintf (str, "%sRGBNeutral", model2);
if (foveon_camf_param ("IncludeBlocks", str))
foveon_fixed (div, 3, str);
num = 0;
FORC3 if (num < div[c]) num = div[c];
FORC3 div[c] /= num;
memset (trans, 0, sizeof trans);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j];
FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2];
dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20;
for (i=0; i < 3; i++)
FORC3 last[i][c] = trans[i][c] * dsum / trsum[i];
memset (trans, 0, sizeof trans);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30;
foveon_make_curves (curve, color_dq, div, cfilt);
FORC3 chroma_dq[c] /= 3;
foveon_make_curves (curve+3, chroma_dq, div, cfilt);
FORC3 dsum += chroma_dq[c] / div[c];
curve[6] = foveon_make_curve (dsum, dsum, cfilt);
curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt);
sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain");
if (!sgain) return;
sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow);
sgx = (width + dim[1]-2) / (dim[1]-1);
black = (float (*)[3]) calloc (height, sizeof *black);
for (row=0; row < height; row++) {
for (i=0; i < 6; i++)
((float *)ddft[0])[i] = ((float *)ddft[1])[i] +
row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
FORC3 black[row][c] =
( foveon_avg (image[row*width]+c, dscr[0], cfilt) +
foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3
- ddft[0][c][0] ) / 4 - ddft[0][c][1];
}
memcpy (black, black+8, sizeof *black*8);
memcpy (black+height-11, black+height-22, 11*sizeof *black);
memcpy (last, black, sizeof last);
for (row=1; row < height-1; row++) {
FORC3 if (last[1][c] > last[0][c]) {
if (last[1][c] > last[2][c])
black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c];
} else
if (last[1][c] < last[2][c])
black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c];
memmove (last, last+1, 2*sizeof last[0]);
memcpy (last[2], black[row+1], sizeof last[2]);
}
FORC3 black[row][c] = (last[0][c] + last[1][c])/2;
FORC3 black[0][c] = (black[1][c] + black[3][c])/2;
val = 1 - exp(-1/24.0);
memcpy (fsum, black, sizeof fsum);
for (row=1; row < height; row++)
FORC3 fsum[c] += black[row][c] =
(black[row][c] - black[row-1][c])*val + black[row-1][c];
memcpy (last[0], black[height-1], sizeof last[0]);
FORC3 fsum[c] /= height;
for (row = height; row--; )
FORC3 last[0][c] = black[row][c] =
(black[row][c] - fsum[c] - last[0][c])*val + last[0][c];
memset (total, 0, sizeof total);
for (row=2; row < height; row+=4)
for (col=2; col < width; col+=4) {
FORC3 total[c] += (short) image[row*width+col][c];
total[3]++;
}
for (row=0; row < height; row++)
FORC3 black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0);
for (row=0; row < height; row++) {
for (i=0; i < 6; i++)
((float *)ddft[0])[i] = ((float *)ddft[1])[i] +
row / (height-1.0) * (((float *)ddft[2])[i] - ((float *)ddft[1])[i]);
pix = image[row*width];
memcpy (prev, pix, sizeof prev);
frow = row / (height-1.0) * (dim[2]-1);
if ((irow = frow) == dim[2]-1) irow--;
frow -= irow;
for (i=0; i < dim[1]; i++)
FORC3 sgrow[i][c] = sgain[ irow *dim[1]+i][c] * (1-frow) +
sgain[(irow+1)*dim[1]+i][c] * frow;
for (col=0; col < width; col++) {
FORC3 {
diff = pix[c] - prev[c];
prev[c] = pix[c];
ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt
- ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5)
- black[row][c] );
}
FORC3 {
work[0][c] = ipix[c] * ipix[c] >> 14;
work[2][c] = ipix[c] * work[0][c] >> 14;
work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14;
}
FORC3 {
for (val=i=0; i < 3; i++)
for ( j=0; j < 3; j++)
val += ppm[c][i][j] * work[i][j];
ipix[c] = floor ((ipix[c] + floor(val)) *
( sgrow[col/sgx ][c] * (sgx - col%sgx) +
sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]);
if (ipix[c] > 32000) ipix[c] = 32000;
pix[c] = ipix[c];
}
pix += 4;
}
}
free (black);
free (sgrow);
free (sgain);
if ((badpix = (unsigned *) foveon_camf_matrix (dim, "BadPixels"))) {
for (i=0; i < dim[0]; i++) {
col = (badpix[i] >> 8 & 0xfff) - keep[0];
row = (badpix[i] >> 20 ) - keep[1];
if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3)
continue;
memset (fsum, 0, sizeof fsum);
for (sum=j=0; j < 8; j++)
if (badpix[i] & (1 << j)) {
FORC3 fsum[c] += (short)
image[(row+hood[j*2])*width+col+hood[j*2+1]][c];
sum++;
}
if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum;
}
free (badpix);
}
/* Array for 5x5 Gaussian averaging of red values */
smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow);
merror (smrow[6], "foveon_interpolate()");
for (i=0; i < 5; i++)
smrow[i] = smrow[6] + i*width;
/* Sharpen the reds against these Gaussian averages */
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
smrow[4][col][0] =
(pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
smred = ( 6 * smrow[2][col][0]
+ 4 * (smrow[1][col][0] + smrow[3][col][0])
+ smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4;
if (col == 2)
smred_p = smred;
i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3);
if (i > 32000) i = 32000;
pix[0] = i;
smred_p = smred;
pix += 4;
}
}
/* Adjust the brighter pixels for better linearity */
min = 0xffff;
FORC3 {
i = satlev[c] / div[c];
if (min > i) min = i;
}
limit = min * 9 >> 4;
for (pix=image[0]; pix < image[height*width]; pix+=4) {
if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit)
continue;
min = max = pix[0];
for (c=1; c < 3; c++) {
if (min > pix[c]) min = pix[c];
if (max < pix[c]) max = pix[c];
}
if (min >= limit*2) {
pix[0] = pix[1] = pix[2] = max;
} else {
i = 0x4000 - ((min - limit) << 14) / limit;
i = 0x4000 - (i*i >> 14);
i = i*i >> 14;
FORC3 pix[c] += (max - pix[c]) * i >> 14;
}
}
/*
Because photons that miss one detector often hit another,
the sum R+G+B is much less noisy than the individual colors.
So smooth the hues without smoothing the total.
*/
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
FORC3 dev[c] = -foveon_apply_curve (curve[7], pix[c] -
((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2));
sum = (dev[0] + dev[1] + dev[2]) >> 3;
FORC3 pix[c] += dev[c] - sum;
pix += 4;
}
}
for (smlast=-1, row=2; row < height-2; row++) {
while (smlast < row+2) {
for (i=0; i < 6; i++)
smrow[(i+5) % 6] = smrow[i];
pix = image[++smlast*width+2];
for (col=2; col < width-2; col++) {
FORC3 smrow[4][col][c] =
(pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2;
pix += 4;
}
}
pix = image[row*width+2];
for (col=2; col < width-2; col++) {
for (total[3]=375, sum=60, c=0; c < 3; c++) {
for (total[c]=i=0; i < 5; i++)
total[c] += smrow[i][col][c];
total[3] += total[c];
sum += pix[c];
}
if (sum < 0) sum = 0;
j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174;
FORC3 pix[c] += foveon_apply_curve (curve[6],
((j*total[c] + 0x8000) >> 16) - pix[c]);
pix += 4;
}
}
/* Transform the image to a different colorspace */
for (pix=image[0]; pix < image[height*width]; pix+=4) {
FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]);
sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2;
FORC3 pix[c] -= foveon_apply_curve (curve[c], pix[c]-sum);
FORC3 {
for (dsum=i=0; i < 3; i++)
dsum += trans[c][i] * pix[i];
if (dsum < 0) dsum = 0;
if (dsum > 24000) dsum = 24000;
ipix[c] = dsum + 0.5;
}
FORC3 pix[c] = ipix[c];
}
/* Smooth the image bottom-to-top and save at 1/4 scale */
shrink = (short (*)[3]) calloc ((height/4), (width/4)*sizeof *shrink);
merror (shrink, "foveon_interpolate()");
for (row = height/4; row--; )
for (col=0; col < width/4; col++) {
ipix[0] = ipix[1] = ipix[2] = 0;
for (i=0; i < 4; i++)
for (j=0; j < 4; j++)
FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c];
FORC3
if (row+2 > height/4)
shrink[row*(width/4)+col][c] = ipix[c] >> 4;
else
shrink[row*(width/4)+col][c] =
(shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12;
}
/* From the 1/4-scale image, smooth right-to-left */
for (row=0; row < (height & ~3); row++) {
ipix[0] = ipix[1] = ipix[2] = 0;
if ((row & 3) == 0)
for (col = width & ~3 ; col--; )
FORC3 smrow[0][col][c] = ipix[c] =
(shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13;
/* Then smooth left-to-right */
ipix[0] = ipix[1] = ipix[2] = 0;
for (col=0; col < (width & ~3); col++)
FORC3 smrow[1][col][c] = ipix[c] =
(smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13;
/* Smooth top-to-bottom */
if (row == 0)
memcpy (smrow[2], smrow[1], sizeof **smrow * width);
else
for (col=0; col < (width & ~3); col++)
FORC3 smrow[2][col][c] =
(smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13;
/* Adjust the chroma toward the smooth values */
for (col=0; col < (width & ~3); col++) {
for (i=j=30, c=0; c < 3; c++) {
i += smrow[2][col][c];
j += image[row*width+col][c];
}
j = (j << 16) / i;
for (sum=c=0; c < 3; c++) {
ipix[c] = foveon_apply_curve (curve[c+3],
((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]);
sum += ipix[c];
}
sum >>= 3;
FORC3 {
i = image[row*width+col][c] + ipix[c] - sum;
if (i < 0) i = 0;
image[row*width+col][c] = i;
}
}
}
free (shrink);
free (smrow[6]);
for (i=0; i < 8; i++)
free (curve[i]);
/* Trim off the black border */
active[1] -= keep[1];
active[3] -= 2;
i = active[2] - active[0];
for (row=0; row < active[3]-active[1]; row++)
memcpy (image[row*i], image[(row+active[1])*width+active[0]],
i * sizeof *image);
width = i;
height = row;
}
#undef image
/* RESTRICTED code ends here */
//@out COMMON
void CLASS crop_masked_pixels()
{
int row, col;
unsigned
#ifndef LIBRAW_LIBRARY_BUILD
r, raw_pitch = raw_width*2,
c, m, mblack[8], zero, val;
#else
c, m, zero, val;
#define mblack imgdata.color.black_stat
#endif
#ifndef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS phase_one_load_raw ||
load_raw == &CLASS phase_one_load_raw_c)
phase_one_correct();
if (fuji_width) {
for (row=0; row < raw_height-top_margin*2; row++) {
for (col=0; col < fuji_width << !fuji_layout; col++) {
if (fuji_layout) {
r = fuji_width - 1 - col + (row >> 1);
c = col + ((row+1) >> 1);
} else {
r = fuji_width - 1 + row - (col >> 1);
c = row + ((col+1) >> 1);
}
if (r < height && c < width)
BAYER(r,c) = RAW(row+top_margin,col+left_margin);
}
}
} else {
for (row=0; row < height; row++)
for (col=0; col < width; col++)
BAYER2(row,col) = RAW(row+top_margin,col+left_margin);
}
#endif
if (mask[0][3] > 0) goto mask_set;
if (load_raw == &CLASS canon_load_raw ||
load_raw == &CLASS lossless_jpeg_load_raw) {
mask[0][1] = mask[1][1] += 2;
mask[0][3] -= 2;
goto sides;
}
if (load_raw == &CLASS canon_600_load_raw ||
load_raw == &CLASS sony_load_raw ||
(load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) ||
load_raw == &CLASS kodak_262_load_raw ||
(load_raw == &CLASS packed_load_raw && (load_flags & 32))) {
sides:
mask[0][0] = mask[1][0] = top_margin;
mask[0][2] = mask[1][2] = top_margin+height;
mask[0][3] += left_margin;
mask[1][1] += left_margin+width;
mask[1][3] += raw_width;
}
if (load_raw == &CLASS nokia_load_raw) {
mask[0][2] = top_margin;
mask[0][3] = width;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (load_raw == &CLASS broadcom_load_raw) {
mask[0][2] = top_margin;
mask[0][3] = width;
}
#endif
mask_set:
memset (mblack, 0, sizeof mblack);
for (zero=m=0; m < 8; m++)
for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++)
for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) {
c = FC(row-top_margin,col-left_margin);
mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)];
mblack[4+c]++;
zero += !val;
}
if (load_raw == &CLASS canon_600_load_raw && width < raw_width) {
black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) /
(mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4;
#ifndef LIBRAW_LIBRARY_BUILD
canon_600_correct();
#endif
} else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) {
FORC4 cblack[c] = mblack[c] / mblack[4+c];
black = cblack[4] = cblack[5] = cblack[6] = 0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
#undef mblack
#endif
void CLASS remove_zeroes()
{
unsigned row, col, tot, n, r, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2);
#endif
for (row=0; row < height; row++)
for (col=0; col < width; col++)
if (BAYER(row,col) == 0) {
tot = n = 0;
for (r = row-2; r <= row+2; r++)
for (c = col-2; c <= col+2; c++)
if (r < height && c < width &&
FC(r,c) == FC(row,col) && BAYER(r,c))
tot += (n++,BAYER(r,c));
if (n) BAYER(row,col) = tot/n;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2);
#endif
}
//@end COMMON
/* @out FILEIO
#include <math.h>
#define CLASS LibRaw::
#include "libraw/libraw_types.h"
#define LIBRAW_LIBRARY_BUILD
#include "libraw/libraw.h"
#include "internal/defines.h"
#include "internal/var_defines.h"
@end FILEIO */
// @out FILEIO
/*
Seach from the current directory up to the root looking for
a ".badpixels" file, and fix those pixels now.
*/
void CLASS bad_pixels (const char *cfname)
{
FILE *fp=NULL;
#ifndef LIBRAW_LIBRARY_BUILD
char *fname, *cp, line[128];
int len, time, row, col, r, c, rad, tot, n, fixed=0;
#else
char *cp, line[128];
int time, row, col, r, c, rad, tot, n;
#ifdef DCRAW_VERBOSE
int fixed = 0;
#endif
#endif
if (!filters) return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,0,2);
#endif
if (cfname)
fp = fopen (cfname, "r");
// @end FILEIO
else {
for (len=32 ; ; len *= 2) {
fname = (char *) malloc (len);
if (!fname) return;
if (getcwd (fname, len-16)) break;
free (fname);
if (errno != ERANGE) return;
}
#if defined(WIN32) || defined(DJGPP)
if (fname[1] == ':')
memmove (fname, fname+2, len-2);
for (cp=fname; *cp; cp++)
if (*cp == '\\') *cp = '/';
#endif
cp = fname + strlen(fname);
if (cp[-1] == '/') cp--;
while (*fname == '/') {
strcpy (cp, "/.badpixels");
if ((fp = fopen (fname, "r"))) break;
if (cp == fname) break;
while (*--cp != '/');
}
free (fname);
}
// @out FILEIO
if (!fp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_BADPIXELMAP;
#endif
return;
}
while (fgets (line, 128, fp)) {
cp = strchr (line, '#');
if (cp) *cp = 0;
if (sscanf (line, "%d %d %d", &col, &row, &time) != 3) continue;
if ((unsigned) col >= width || (unsigned) row >= height) continue;
if (time > timestamp) continue;
for (tot=n=0, rad=1; rad < 3 && n==0; rad++)
for (r = row-rad; r <= row+rad; r++)
for (c = col-rad; c <= col+rad; c++)
if ((unsigned) r < height && (unsigned) c < width &&
(r != row || c != col) && fcol(r,c) == fcol(row,col)) {
tot += BAYER2(r,c);
n++;
}
BAYER2(row,col) = tot/n;
#ifdef DCRAW_VERBOSE
if (verbose) {
if (!fixed++)
fprintf (stderr,_("Fixed dead pixels at:"));
fprintf (stderr, " %d,%d", col, row);
}
#endif
}
#ifdef DCRAW_VERBOSE
if (fixed) fputc ('\n', stderr);
#endif
fclose (fp);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_BAD_PIXELS,1,2);
#endif
}
void CLASS subtract (const char *fname)
{
FILE *fp;
int dim[3]={0,0,0}, comment=0, number=0, error=0, nd=0, c, row, col;
ushort *pixel;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,0,2);
#endif
if (!(fp = fopen (fname, "rb"))) {
#ifdef DCRAW_VERBOSE
perror (fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_FILE;
#endif
return;
}
if (fgetc(fp) != 'P' || fgetc(fp) != '5') error = 1;
while (!error && nd < 3 && (c = fgetc(fp)) != EOF) {
if (c == '#') comment = 1;
if (c == '\n') comment = 0;
if (comment) continue;
if (isdigit(c)) number = 1;
if (number) {
if (isdigit(c)) dim[nd] = dim[nd]*10 + c -'0';
else if (isspace(c)) {
number = 0; nd++;
} else error = 1;
}
}
if (error || nd < 3) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s is not a valid PGM file!\n"), fname);
#endif
fclose (fp); return;
} else if (dim[0] != width || dim[1] != height || dim[2] != 65535) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s has the wrong dimensions!\n"), fname);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_DARKFRAME_DIM;
#endif
fclose (fp); return;
}
pixel = (ushort *) calloc (width, sizeof *pixel);
merror (pixel, "subtract()");
for (row=0; row < height; row++) {
fread (pixel, 2, width, fp);
for (col=0; col < width; col++)
BAYER(row,col) = MAX (BAYER(row,col) - ntohs(pixel[col]), 0);
}
free (pixel);
fclose (fp);
memset (cblack, 0, sizeof cblack);
black = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_DARK_FRAME,1,2);
#endif
}
//@end FILEIO
//@out COMMON
static const uchar xlat[2][256] = {
{ 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d,
0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d,
0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f,
0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f,
0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1,
0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17,
0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89,
0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f,
0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b,
0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb,
0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3,
0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f,
0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35,
0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43,
0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5,
0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 },
{ 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c,
0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34,
0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad,
0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05,
0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee,
0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d,
0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b,
0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b,
0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc,
0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33,
0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8,
0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6,
0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c,
0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49,
0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb,
0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } };
void CLASS gamma_curve (double pwr, double ts, int mode, int imax)
{
int i;
double g[6], bnd[2]={0,0}, r;
g[0] = pwr;
g[1] = ts;
g[2] = g[3] = g[4] = 0;
bnd[g[1] >= 1] = 1;
if (g[1] && (g[1]-1)*(g[0]-1) <= 0) {
for (i=0; i < 48; i++) {
g[2] = (bnd[0] + bnd[1])/2;
if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2];
else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2];
}
g[3] = g[2] / g[1];
if (g[0]) g[4] = g[2] * (1/g[0] - 1);
}
if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) +
(1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1;
else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1
- g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1;
if (!mode--) {
memcpy (gamm, g, sizeof gamm);
return;
}
for (i=0; i < 0x10000; i++) {
curve[i] = 0xffff;
if ((r = (double) i / imax) < 1)
curve[i] = 0x10000 * ( mode
? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1))
: (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2]))));
}
}
void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size)
{
double work[3][6], num;
int i, j, k;
for (i=0; i < 3; i++) {
for (j=0; j < 6; j++)
work[i][j] = j == i+3;
for (j=0; j < 3; j++)
for (k=0; k < size; k++)
work[i][j] += in[k][i] * in[k][j];
}
for (i=0; i < 3; i++) {
num = work[i][i];
for (j=0; j < 6; j++)
work[i][j] /= num;
for (k=0; k < 3; k++) {
if (k==i) continue;
num = work[k][i];
for (j=0; j < 6; j++)
work[k][j] -= work[i][j] * num;
}
}
for (i=0; i < size; i++)
for (j=0; j < 3; j++)
for (out[i][j]=k=0; k < 3; k++)
out[i][j] += work[j][k+3] * in[i][k];
}
void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3])
{
double cam_rgb[4][3], inverse[4][3], num;
int i, j, k;
for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */
for (j=0; j < 3; j++)
for (cam_rgb[i][j] = k=0; k < 3; k++)
cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j];
for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */
for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */
num += cam_rgb[i][j];
if(num > 0.00001)
{
for (j=0; j < 3; j++)
cam_rgb[i][j] /= num;
pre_mul[i] = 1 / num;
}
else
{
for (j=0; j < 3; j++)
cam_rgb[i][j] = 0.0;
pre_mul[i] = 1.0;
}
}
pseudoinverse (cam_rgb, inverse, colors);
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
_rgb_cam[i][j] = inverse[j][i];
}
#ifdef COLORCHECK
void CLASS colorcheck()
{
#define NSQ 24
// Coordinates of the GretagMacbeth ColorChecker squares
// width, height, 1st_column, 1st_row
int cut[NSQ][4]; // you must set these
// ColorChecker Chart under 6500-kelvin illumination
static const double gmb_xyY[NSQ][3] = {
{ 0.400, 0.350, 10.1 }, // Dark Skin
{ 0.377, 0.345, 35.8 }, // Light Skin
{ 0.247, 0.251, 19.3 }, // Blue Sky
{ 0.337, 0.422, 13.3 }, // Foliage
{ 0.265, 0.240, 24.3 }, // Blue Flower
{ 0.261, 0.343, 43.1 }, // Bluish Green
{ 0.506, 0.407, 30.1 }, // Orange
{ 0.211, 0.175, 12.0 }, // Purplish Blue
{ 0.453, 0.306, 19.8 }, // Moderate Red
{ 0.285, 0.202, 6.6 }, // Purple
{ 0.380, 0.489, 44.3 }, // Yellow Green
{ 0.473, 0.438, 43.1 }, // Orange Yellow
{ 0.187, 0.129, 6.1 }, // Blue
{ 0.305, 0.478, 23.4 }, // Green
{ 0.539, 0.313, 12.0 }, // Red
{ 0.448, 0.470, 59.1 }, // Yellow
{ 0.364, 0.233, 19.8 }, // Magenta
{ 0.196, 0.252, 19.8 }, // Cyan
{ 0.310, 0.316, 90.0 }, // White
{ 0.310, 0.316, 59.1 }, // Neutral 8
{ 0.310, 0.316, 36.2 }, // Neutral 6.5
{ 0.310, 0.316, 19.8 }, // Neutral 5
{ 0.310, 0.316, 9.0 }, // Neutral 3.5
{ 0.310, 0.316, 3.1 } }; // Black
double gmb_cam[NSQ][4], gmb_xyz[NSQ][3];
double inverse[NSQ][3], cam_xyz[4][3], balance[4], num;
int c, i, j, k, sq, row, col, pass, count[4];
memset (gmb_cam, 0, sizeof gmb_cam);
for (sq=0; sq < NSQ; sq++) {
FORCC count[c] = 0;
for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++)
for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) {
c = FC(row,col);
if (c >= colors) c -= 2;
gmb_cam[sq][c] += BAYER2(row,col);
BAYER2(row,col) = black + (BAYER2(row,col)-black)/2;
count[c]++;
}
FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black;
gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1];
gmb_xyz[sq][1] = gmb_xyY[sq][2];
gmb_xyz[sq][2] = gmb_xyY[sq][2] *
(1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1];
}
pseudoinverse (gmb_xyz, inverse, NSQ);
for (pass=0; pass < 2; pass++) {
for (raw_color = i=0; i < colors; i++)
for (j=0; j < 3; j++)
for (cam_xyz[i][j] = k=0; k < NSQ; k++)
cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j];
cam_xyz_coeff (rgb_cam, cam_xyz);
FORCC balance[c] = pre_mul[c] * gmb_cam[20][c];
for (sq=0; sq < NSQ; sq++)
FORCC gmb_cam[sq][c] *= balance[c];
}
if (verbose) {
printf (" { \"%s %s\", %d,\n\t{", make, model, black);
num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]);
FORCC for (j=0; j < 3; j++)
printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5));
puts (" } },");
}
#undef NSQ
}
#endif
void CLASS hat_transform (float *temp, float *base, int st, int size, int sc)
{
int i;
for (i=0; i < sc; i++)
temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)];
for (; i+sc < size; i++)
temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)];
for (; i < size; i++)
temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))];
}
#if !defined(LIBRAW_USE_OPENMP)
void CLASS wavelet_denoise()
{
float *fimg=0, *temp, thold, mul[2], avg, diff;
int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] =
{ 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000) scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight*iwidth) < 0x15550000)
fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
merror (fimg, "wavelet_denoise()");
temp = fimg + size*3;
if ((nc = colors) == 3 && filters) nc++;
FORC(nc) { /* denoise R,G1,B,G3 individually */
for (i=0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass=lev=0; lev < 5; lev++) {
lpass = size*((lev & 1)+1);
for (row=0; row < iheight; row++) {
hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
for (col=0; col < iwidth; col++)
fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
}
for (col=0; col < iwidth; col++) {
hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
for (row=0; row < iheight; row++)
fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
for (i=0; i < size; i++) {
fimg[hpass+i] -= fimg[lpass+i];
if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold;
else fimg[hpass+i] = 0;
if (hpass) fimg[i] += fimg[hpass+i];
}
hpass = lpass;
}
for (i=0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
}
if (filters && colors == 3) { /* pull G1 and G3 closer together */
for (row=0; row < 2; row++) {
mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
blk[row] = cblack[FC(row,0) | 1];
}
for (i=0; i < 4; i++)
window[i] = (ushort *) fimg + width*i;
for (wlast=-1, row=1; row < height-1; row++) {
while (wlast < row+1) {
for (wlast++, i=0; i < 4; i++)
window[(i+3) & 3] = window[i];
for (col = FC(wlast,1) & 1; col < width; col+=2)
window[2][col] = BAYER(wlast,col);
}
thold = threshold/512;
for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
avg = ( window[0][col-1] + window[0][col+1] +
window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
* mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row,col)) - avg;
if (diff < -thold) diff += thold;
else if (diff > thold) diff -= thold;
else diff = 0;
BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
}
}
}
free (fimg);
}
#else /* LIBRAW_USE_OPENMP */
void CLASS wavelet_denoise()
{
float *fimg=0, *temp, thold, mul[2], avg, diff;
int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2];
ushort *window[4];
static const float noise[] =
{ 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Wavelet denoising...\n"));
#endif
while (maximum << scale < 0x10000) scale++;
maximum <<= --scale;
black <<= scale;
FORC4 cblack[c] <<= scale;
if ((size = iheight*iwidth) < 0x15550000)
fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg);
merror (fimg, "wavelet_denoise()");
temp = fimg + size*3;
if ((nc = colors) == 3 && filters) nc++;
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size)
#endif
{
temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg);
FORC(nc) { /* denoise R,G1,B,G3 individually */
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++)
fimg[i] = 256 * sqrt((double)(image[i][c] << scale));
for (hpass=lev=0; lev < 5; lev++) {
lpass = size*((lev & 1)+1);
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (row=0; row < iheight; row++) {
hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev);
for (col=0; col < iwidth; col++)
fimg[lpass + row*iwidth + col] = temp[col] * 0.25;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (col=0; col < iwidth; col++) {
hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev);
for (row=0; row < iheight; row++)
fimg[lpass + row*iwidth + col] = temp[row] * 0.25;
}
thold = threshold * noise[lev];
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++) {
fimg[hpass+i] -= fimg[lpass+i];
if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold;
else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold;
else fimg[hpass+i] = 0;
if (hpass) fimg[i] += fimg[hpass+i];
}
hpass = lpass;
}
#ifdef LIBRAW_LIBRARY_BUILD
#pragma omp for
#endif
for (i=0; i < size; i++)
image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000);
}
free(temp);
} /* end omp parallel */
/* the following loops are hard to parallize, no idea yes,
* problem is wlast which is carrying dependency
* second part should be easyer, but did not yet get it right.
*/
if (filters && colors == 3) { /* pull G1 and G3 closer together */
for (row=0; row < 2; row++){
mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1];
blk[row] = cblack[FC(row,0) | 1];
}
for (i=0; i < 4; i++)
window[i] = (ushort *) fimg + width*i;
for (wlast=-1, row=1; row < height-1; row++) {
while (wlast < row+1) {
for (wlast++, i=0; i < 4; i++)
window[(i+3) & 3] = window[i];
for (col = FC(wlast,1) & 1; col < width; col+=2)
window[2][col] = BAYER(wlast,col);
}
thold = threshold/512;
for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) {
avg = ( window[0][col-1] + window[0][col+1] +
window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 )
* mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5;
avg = avg < 0 ? 0 : sqrt(avg);
diff = sqrt((double)BAYER(row,col)) - avg;
if (diff < -thold) diff += thold;
else if (diff > thold) diff -= thold;
else diff = 0;
BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5);
}
}
}
free (fimg);
}
#endif
// green equilibration
void CLASS green_matching()
{
int i,j;
double m1,m2,c1,c2;
int o1_1,o1_2,o1_3,o1_4;
int o2_1,o2_2,o2_3,o2_4;
ushort (*img)[4];
const int margin = 3;
int oj = 2, oi = 2;
float f;
const float thr = 0.01f;
if(half_size || shrink) return;
if(FC(oj, oi) != 3) oj++;
if(FC(oj, oi) != 3) oi++;
if(FC(oj, oi) != 3) oj--;
img = (ushort (*)[4]) calloc (height*width, sizeof *image);
merror (img, "green_matching()");
memcpy(img,image,height*width*sizeof *image);
for(j=oj;j<height-margin;j+=2)
for(i=oi;i<width-margin;i+=2){
o1_1=img[(j-1)*width+i-1][1];
o1_2=img[(j-1)*width+i+1][1];
o1_3=img[(j+1)*width+i-1][1];
o1_4=img[(j+1)*width+i+1][1];
o2_1=img[(j-2)*width+i][3];
o2_2=img[(j+2)*width+i][3];
o2_3=img[j*width+i-2][3];
o2_4=img[j*width+i+2][3];
m1=(o1_1+o1_2+o1_3+o1_4)/4.0;
m2=(o2_1+o2_2+o2_3+o2_4)/4.0;
c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0;
c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0;
if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr))
{
f = image[j*width+i][3]*m1/m2;
image[j*width+i][3]=f>0xffff?0xffff:f;
}
}
free(img);
}
void CLASS scale_colors()
{
unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8];
int val, dark, sat;
double dsum[8], dmin, dmax;
float scale_mul[4], fr, fc;
ushort *img=0, *pix;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2);
#endif
if (user_mul[0])
memcpy (pre_mul, user_mul, sizeof pre_mul);
if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) {
memset (dsum, 0, sizeof dsum);
bottom = MIN (greybox[1]+greybox[3], height);
right = MIN (greybox[0]+greybox[2], width);
for (row=greybox[1]; row < bottom; row += 8)
for (col=greybox[0]; col < right; col += 8) {
memset (sum, 0, sizeof sum);
for (y=row; y < row+8 && y < bottom; y++)
for (x=col; x < col+8 && x < right; x++)
FORC4 {
if (filters) {
c = fcol(y,x);
val = BAYER2(y,x);
} else
val = image[y*width+x][c];
if (val > maximum-25) goto skip_block;
if ((val -= cblack[c]) < 0) val = 0;
sum[c] += val;
sum[c+4]++;
if (filters) break;
}
FORC(8) dsum[c] += sum[c];
skip_block: ;
}
FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c];
}
if (use_camera_wb && cam_mul[0] != -1) {
memset (sum, 0, sizeof sum);
for (row=0; row < 8; row++)
for (col=0; col < 8; col++) {
c = FC(row,col);
if ((val = white[row][col] - cblack[c]) > 0)
sum[c] += val;
sum[c+4]++;
}
#ifdef LIBRAW_LIBRARY_BUILD
if(load_raw == &LibRaw::nikon_load_sraw)
{
// Nikon sRAW: camera WB already applied:
pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0;
}
else
#endif
if (sum[0] && sum[1] && sum[2] && sum[3])
FORC4 pre_mul[c] = (float) sum[c+4] / sum[c];
else if (cam_mul[0] && cam_mul[2])
memcpy (pre_mul, cam_mul, sizeof pre_mul);
else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname);
#endif
}
}
#ifdef LIBRAW_LIBRARY_BUILD
// Nikon sRAW, daylight
if (load_raw == &LibRaw::nikon_load_sraw
&& !use_camera_wb && !use_auto_wb
&& cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f )
{
for(c=0;c<3;c++)
pre_mul[c]/=cam_mul[c];
}
#endif
if (pre_mul[1] == 0) pre_mul[1] = 1;
if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1;
dark = black;
sat = maximum;
if (threshold) wavelet_denoise();
maximum -= black;
for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) {
if (dmin > pre_mul[c])
dmin = pre_mul[c];
if (dmax < pre_mul[c])
dmax = pre_mul[c];
}
if (!highlight) dmax = dmin;
FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum;
#ifdef DCRAW_VERBOSE
if (verbose) {
fprintf (stderr,
_("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat);
FORC4 fprintf (stderr, " %f", pre_mul[c]);
fputc ('\n', stderr);
}
#endif
if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) {
FORC4 cblack[FC(c/2,c%2)] +=
cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]];
cblack[4] = cblack[5] = 0;
}
size = iheight*iwidth;
#ifdef LIBRAW_LIBRARY_BUILD
scale_colors_loop(scale_mul);
#else
for (i=0; i < size*4; i++) {
if (!(val = ((ushort *)image)[i])) continue;
if (cblack[4] && cblack[5])
val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] +
i/4 % iwidth % cblack[5]];
val -= cblack[i & 3];
val *= scale_mul[i & 3];
((ushort *)image)[i] = CLIP(val);
}
#endif
if ((aber[0] != 1 || aber[2] != 1) && colors == 3) {
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Correcting chromatic aberration...\n"));
#endif
for (c=0; c < 4; c+=2) {
if (aber[c] == 1) continue;
img = (ushort *) malloc (size * sizeof *img);
merror (img, "scale_colors()");
for (i=0; i < size; i++)
img[i] = image[i][c];
for (row=0; row < iheight; row++) {
ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5;
if (ur > iheight-2) continue;
fr -= ur;
for (col=0; col < iwidth; col++) {
uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5;
if (uc > iwidth-2) continue;
fc -= uc;
pix = img + ur*iwidth + uc;
image[row*iwidth+col][c] =
(pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) +
(pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr;
}
}
free(img);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2);
#endif
}
void CLASS pre_interpolate()
{
ushort (*img)[4];
int row, col, c;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2);
#endif
if (shrink) {
if (half_size) {
height = iheight;
width = iwidth;
if (filters == 9) {
for (row=0; row < 3; row++)
for (col=1; col < 4; col++)
if (!(image[row*width+col][0] | image[row*width+col][2]))
goto break2; break2:
for ( ; row < height; row+=3)
for (col=(col-1)%3+1; col < width-1; col+=3) {
img = image + row*width+col;
for (c=0; c < 3; c+=2)
img[0][c] = (img[-1][c] + img[1][c]) >> 1;
}
}
} else {
img = (ushort (*)[4]) calloc (height, width*sizeof *img);
merror (img, "pre_interpolate()");
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
c = fcol(row,col);
img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c];
}
free (image);
image = img;
shrink = 0;
}
}
if (filters > 1000 && colors == 3) {
mix_green = four_color_rgb ^ half_size;
if (four_color_rgb | half_size) colors++;
else {
for (row = FC(1,0) >> 1; row < height; row+=2)
for (col = FC(row,1) & 1; col < width; col+=2)
image[row*width+col][1] = image[row*width+col][3];
filters &= ~((filters & 0x55555555) << 1);
}
}
if (half_size) filters = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2);
#endif
}
void CLASS border_interpolate (int border)
{
unsigned row, col, y, x, f, c, sum[8];
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
if (col==border && row >= border && row < height-border)
col = width-border;
memset (sum, 0, sizeof sum);
for (y=row-1; y != row+2; y++)
for (x=col-1; x != col+2; x++)
if (y < height && x < width) {
f = fcol(y,x);
sum[f] += image[y*width+x][f];
sum[f+4]++;
}
f = fcol(row,col);
FORCC if (c != f && sum[c+4])
image[row*width+col][c] = sum[c] / sum[c+4];
}
}
void CLASS lin_interpolate_loop(int code[16][16][32],int size)
{
int row;
for (row=1; row < height-1; row++)
{
int col,*ip;
ushort *pix;
for (col=1; col < width-1; col++) {
int i;
int sum[4];
pix = image[row*width+col];
ip = code[row % size][col % size];
memset (sum, 0, sizeof sum);
for (i=*ip++; i--; ip+=3)
sum[ip[2]] += pix[ip[0]] << ip[1];
for (i=colors; --i; ip+=2)
pix[ip[0]] = sum[ip[0]] * ip[1] >> 8;
}
}
}
void CLASS lin_interpolate()
{
int code[16][16][32], size=16, *ip, sum[4];
int f, c, x, y, row, col, shift, color;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Bilinear interpolation...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3);
#endif
if (filters == 9) size = 6;
border_interpolate(1);
for (row=0; row < size; row++)
for (col=0; col < size; col++) {
ip = code[row][col]+1;
f = fcol(row,col);
memset (sum, 0, sizeof sum);
for (y=-1; y <= 1; y++)
for (x=-1; x <= 1; x++) {
shift = (y==0) + (x==0);
color = fcol(row+y,col+x);
if (color == f) continue;
*ip++ = (width*y + x)*4 + color;
*ip++ = shift;
*ip++ = color;
sum[color] += 1 << shift;
}
code[row][col][0] = (ip - code[row][col]) / 3;
FORCC
if (c != f) {
*ip++ = c;
*ip++ = sum[c]>0?256 / sum[c]:0;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3);
#endif
lin_interpolate_loop(code,size);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3);
#endif
}
/*
This algorithm is officially called:
"Interpolation using a Threshold-based variable number of gradients"
described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html
I've extended the basic idea to work with non-Bayer filter arrays.
Gradients are numbered clockwise from NW=0 to W=7.
*/
void CLASS vng_interpolate()
{
static const signed char *cp, terms[] = {
-2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01,
-2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01,
-2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03,
-2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06,
-2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04,
-1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01,
-1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40,
-1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11,
-1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11,
-1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22,
-1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44,
-1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10,
-1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04,
+0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40,
+0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20,
+0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08,
+0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20,
+0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44,
+0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60,
+0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128,
+1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40,
+1,+0,+2,+1,0,0x10
}, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 };
ushort (*brow[5])[4], *pix;
int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4];
int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag;
int g, diff, thold, num, c;
lin_interpolate();
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("VNG interpolation...\n"));
#endif
if (filters == 1) prow = pcol = 16;
if (filters == 9) prow = pcol = 6;
ip = (int *) calloc (prow*pcol, 1280);
merror (ip, "vng_interpolate()");
for (row=0; row < prow; row++) /* Precalculate for VNG */
for (col=0; col < pcol; col++) {
code[row][col] = ip;
for (cp=terms, t=0; t < 64; t++) {
y1 = *cp++; x1 = *cp++;
y2 = *cp++; x2 = *cp++;
weight = *cp++;
grads = *cp++;
color = fcol(row+y1,col+x1);
if (fcol(row+y2,col+x2) != color) continue;
diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1;
if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue;
*ip++ = (y1*width + x1)*4 + color;
*ip++ = (y2*width + x2)*4 + color;
*ip++ = weight;
for (g=0; g < 8; g++)
if (grads & 1<<g) *ip++ = g;
*ip++ = -1;
}
*ip++ = INT_MAX;
for (cp=chood, g=0; g < 8; g++) {
y = *cp++; x = *cp++;
*ip++ = (y*width + x) * 4;
color = fcol(row,col);
if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color)
*ip++ = (y*width + x) * 8 + color;
else
*ip++ = 0;
}
}
brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow);
merror (brow[4], "vng_interpolate()");
for (row=0; row < 3; row++)
brow[row] = brow[4] + row*width;
for (row=2; row < height-2; row++) { /* Do VNG interpolation */
#ifdef LIBRAW_LIBRARY_BUILD
if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1);
#endif
for (col=2; col < width-2; col++) {
pix = image[row*width+col];
ip = code[row % prow][col % pcol];
memset (gval, 0, sizeof gval);
while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */
diff = ABS(pix[g] - pix[ip[1]]) << ip[2];
gval[ip[3]] += diff;
ip += 5;
if ((g = ip[-1]) == -1) continue;
gval[g] += diff;
while ((g = *ip++) != -1)
gval[g] += diff;
}
ip++;
gmin = gmax = gval[0]; /* Choose a threshold */
for (g=1; g < 8; g++) {
if (gmin > gval[g]) gmin = gval[g];
if (gmax < gval[g]) gmax = gval[g];
}
if (gmax == 0) {
memcpy (brow[2][col], pix, sizeof *image);
continue;
}
thold = gmin + (gmax >> 1);
memset (sum, 0, sizeof sum);
color = fcol(row,col);
for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */
if (gval[g] <= thold) {
FORCC
if (c == color && ip[1])
sum[c] += (pix[c] + pix[ip[1]]) >> 1;
else
sum[c] += pix[ip[0] + c];
num++;
}
}
FORCC { /* Save to buffer */
t = pix[color];
if (c != color)
t += (sum[c] - sum[color]) / num;
brow[2][col][c] = CLIP(t);
}
}
if (row > 3) /* Write buffer to image */
memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
for (g=0; g < 4; g++)
brow[(g-1) & 3] = brow[g];
}
memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image);
memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image);
free (brow[4]);
free (code[0][0]);
}
/*
Patterned Pixel Grouping Interpolation by Alain Desbiolles
*/
void CLASS ppg_interpolate()
{
int dir[5] = { 1, width, -1, -width, 1 };
int row, col, diff[2], guess[2], c, d, i;
ushort (*pix)[4];
border_interpolate(3);
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("PPG interpolation...\n"));
#endif
/* Fill in the green layer with gradients and pattern recognition: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=3; row < height-3; row++)
for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]) > 0; i++) {
guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2
- pix[-2*d][c] - pix[2*d][c];
diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) +
ABS(pix[ 2*d][c] - pix[ 0][c]) +
ABS(pix[ -d][1] - pix[ d][1]) ) * 3 +
( ABS(pix[ 3*d][1] - pix[ d][1]) +
ABS(pix[-3*d][1] - pix[-d][1]) ) * 2;
}
d = dir[i = diff[0] > diff[1]];
pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]);
}
/* Calculate red and blue for each green pixel: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=1; row < height-1; row++)
for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]) > 0; c=2-c, i++)
pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1]
- pix[-d][1] - pix[d][1]) >> 1);
}
/* Calculate blue for red pixels and vice versa: */
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3);
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static)
#endif
#endif
for (row=1; row < height-1; row++)
for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) {
pix = image + row*width+col;
for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) {
diff[i] = ABS(pix[-d][c] - pix[d][c]) +
ABS(pix[-d][1] - pix[0][1]) +
ABS(pix[ d][1] - pix[0][1]);
guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1]
- pix[-d][1] - pix[d][1];
}
if (diff[0] != diff[1])
pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1);
else
pix[0][c] = CLIP((guess[0]+guess[1]) >> 2);
}
}
void CLASS cielab (ushort rgb[3], short lab[3])
{
int c, i, j, k;
float r, xyz[3];
#ifdef LIBRAW_NOTHREADS
static float cbrt[0x10000], xyz_cam[3][4];
#else
#define cbrt tls->ahd_data.cbrt
#define xyz_cam tls->ahd_data.xyz_cam
#endif
if (!rgb) {
#ifndef LIBRAW_NOTHREADS
if(cbrt[0] < -1.0f)
#endif
for (i=0; i < 0x10000; i++) {
r = i / 65535.0;
cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f;
}
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
for (xyz_cam[i][j] = k=0; k < 3; k++)
xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i];
return;
}
xyz[0] = xyz[1] = xyz[2] = 0.5;
FORCC {
xyz[0] += xyz_cam[0][c] * rgb[c];
xyz[1] += xyz_cam[1][c] * rgb[c];
xyz[2] += xyz_cam[2][c] * rgb[c];
}
xyz[0] = cbrt[CLIP((int) xyz[0])];
xyz[1] = cbrt[CLIP((int) xyz[1])];
xyz[2] = cbrt[CLIP((int) xyz[2])];
lab[0] = 64 * (116 * xyz[1] - 16);
lab[1] = 64 * 500 * (xyz[0] - xyz[1]);
lab[2] = 64 * 200 * (xyz[1] - xyz[2]);
#ifndef LIBRAW_NOTHREADS
#undef cbrt
#undef xyz_cam
#endif
}
#define TS 512 /* Tile Size */
#define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6]
/*
Frank Markesteijn's algorithm for Fuji X-Trans sensors
*/
void CLASS xtrans_interpolate (int passes)
{
int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol;
#ifdef LIBRAW_LIBRARY_BUILD
int cstat[4]={0,0,0,0};
#endif
int val, ndir, pass, hm[8], avg[4], color[3][8];
static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 },
patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 },
{ 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } },
dir[4] = { 1,TS,TS+1,TS-1 };
short allhex[3][3][2][8], *hex;
ushort min, max, sgrow, sgcol;
ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short (*lab) [TS][3], (*lix)[3];
float (*drv)[TS][TS], diff[6], tr;
char (*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
/* Check against right pattern */
for (row = 0; row < 6; row++)
for (col = 0; col < 6; col++)
cstat[fcol(row,col)]++;
if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16
|| cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
cielab (0,0);
ndir = 4 << (passes > 1);
buffer = (char *) malloc (TS*TS*(ndir*11+6));
merror (buffer, "xtrans_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6));
drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6));
homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6));
/* Map a green hexagon around each non-green pixel and vice versa: */
for (row=0; row < 3; row++)
for (col=0; col < 3; col++)
for (ng=d=0; d < 10; d+=2) {
g = fcol(row,col) == 1;
if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++;
if (ng == 4) { sgrow = row; sgcol = col; }
if (ng == g+1) FORC(8) {
v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1];
h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1];
allhex[row][col][0][c^(g*2 & d)] = h + v*width;
allhex[row][col][1][c^(g*2 & d)] = h + v*TS;
}
}
/* Set green1 and green3 to the minimum and maximum allowed values: */
for (row=2; row < height-2; row++)
for (min=~(max=0), col=2; col < width-2; col++) {
if (fcol(row,col) == 1 && (min=~(max=0))) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][0];
if (!max) FORC(6) {
val = pix[hex[c]][1];
if (min > val) min = val;
if (max < val) max = val;
}
pix[0][1] = min;
pix[0][3] = max;
switch ((row-sgrow) % 3) {
case 1: if (row < height-3) { row++; col--; } break;
case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--;
}
}
for (top=3; top < height-19; top += TS-16)
for (left=3; left < width-19; left += TS-16) {
mrow = MIN (top+TS, height-3);
mcol = MIN (left+TS, width-3);
for (row=top; row < mrow; row++)
for (col=left; col < mcol; col++)
memcpy (rgb[0][row-top][col-left], image[row*width+col], 6);
FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb);
/* Interpolate green horizontally, vertically, and along both diagonals: */
for (row=top; row < mrow; row++)
for (col=left; col < mcol; col++) {
if ((f = fcol(row,col)) == 1) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][0];
color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) -
46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]);
color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 +
92 * (pix[ 0 ][f] - pix[ -hex[2]][f]);
FORC(2) color[1][2+c] =
164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 *
(2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]);
FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] =
LIM(color[1][c] >> 8,pix[0][1],pix[0][3]);
}
for (pass=0; pass < passes; pass++) {
if (pass == 1)
memcpy (rgb+=4, buffer, 4*sizeof *rgb);
/* Recalculate green from interpolated values of closer pixels: */
if (pass) {
for (row=top+2; row < mrow-2; row++)
for (col=left+2; col < mcol-2; col++) {
if ((f = fcol(row,col)) == 1) continue;
pix = image + row*width + col;
hex = allhex[row % 3][col % 3][1];
for (d=3; d < 6; d++) {
rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left];
val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1]
- rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f];
rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]);
}
}
}
/* Interpolate red and blue values for solitary green pixels: */
for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3)
for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) {
rix = &rgb[0][row-top][col-left];
h = fcol(row,col+1);
memset (diff, 0, sizeof diff);
for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) {
for (c=0; c < 2; c++, h^=2) {
g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1];
color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h];
if (d > 1)
diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1]
- rix[i<<c][h] + rix[-i<<c][h]) + SQR(g);
}
if (d > 1 && (d & 1))
if (diff[d-1] < diff[d])
FORC(2) color[c*2][d] = color[c*2][d-1];
if (d < 2 || (d & 1)) {
FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2);
rix += TS*TS;
}
}
}
/* Interpolate red for blue pixels and vice versa: */
for (row=top+3; row < mrow-3; row++)
for (col=left+3; col < mcol-3; col++) {
if ((f = 2-fcol(row,col)) == 1) continue;
rix = &rgb[0][row-top][col-left];
c = (row-sgrow) % 3 ? TS:1;
h = 3 * (c ^ TS ^ 1);
for (d=0; d < 4; d++, rix += TS*TS) {
i = d > 1 || ((d ^ c) & 1) ||
((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) <
2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h;
rix[0][f] = CLIP((rix[i][f] + rix[-i][f] +
2*rix[0][1] - rix[i][1] - rix[-i][1])/2);
}
}
/* Fill in red and blue for 2x2 blocks of green: */
for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3)
for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) {
rix = &rgb[0][row-top][col-left];
hex = allhex[row % 3][col % 3][1];
for (d=0; d < ndir; d+=2, rix += TS*TS)
if (hex[d] + hex[d+1]) {
g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1];
for (c=0; c < 4; c+=2) rix[0][c] =
CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3);
} else {
g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1];
for (c=0; c < 4; c+=2) rix[0][c] =
CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2);
}
}
}
rgb = (ushort(*)[TS][TS][3]) buffer;
mrow -= top;
mcol -= left;
/* Convert to CIELab and differentiate in all directions: */
for (d=0; d < ndir; d++) {
for (row=2; row < mrow-2; row++)
for (col=2; col < mcol-2; col++)
cielab (rgb[d][row][col], lab[row][col]);
for (f=dir[d & 3],row=3; row < mrow-3; row++)
for (col=3; col < mcol-3; col++) {
lix = &lab[row][col];
g = 2*lix[0][0] - lix[f][0] - lix[-f][0];
drv[d][row][col] = SQR(g)
+ SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232))
+ SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580));
}
}
/* Build homogeneity maps from the derivatives: */
memset(homo, 0, ndir*TS*TS);
for (row=4; row < mrow-4; row++)
for (col=4; col < mcol-4; col++) {
for (tr=FLT_MAX, d=0; d < ndir; d++)
if (tr > drv[d][row][col])
tr = drv[d][row][col];
tr *= 8;
for (d=0; d < ndir; d++)
for (v=-1; v <= 1; v++)
for (h=-1; h <= 1; h++)
if (drv[d][row+v][col+h] <= tr)
homo[d][row][col]++;
}
/* Average the most homogenous pixels for the final result: */
if (height-top < TS+4) mrow = height-top+2;
if (width-left < TS+4) mcol = width-left+2;
for (row = MIN(top,8); row < mrow-8; row++)
for (col = MIN(left,8); col < mcol-8; col++) {
for (d=0; d < ndir; d++)
for (hm[d]=0, v=-2; v <= 2; v++)
for (h=-2; h <= 2; h++)
hm[d] += homo[d][row+v][col+h];
for (d=0; d < ndir-4; d++)
if (hm[d] < hm[d+4]) hm[d ] = 0; else
if (hm[d] > hm[d+4]) hm[d+4] = 0;
for (max=hm[0],d=1; d < ndir; d++)
if (max < hm[d]) max = hm[d];
max -= max >> 3;
memset (avg, 0, sizeof avg);
for (d=0; d < ndir; d++)
if (hm[d] >= max) {
FORC3 avg[c] += rgb[d][row][col][c];
avg[3]++;
}
FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3];
}
}
free(buffer);
border_interpolate(8);
}
#undef fcol
/*
Adaptive Homogeneity-Directed interpolation is based on
the work of Keigo Hirakawa, Thomas Parks, and Paul Lee.
*/
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3])
{
int row, col;
int c, val;
ushort (*pix)[4];
const int rowlimit = MIN(top+TS, height-2);
const int collimit = MIN(left+TS, width-2);
for (row = top; row < rowlimit; row++) {
col = left + (FC(row,left) & 1);
for (c = FC(row,col); col < collimit; col+=2) {
pix = image + row*width+col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
- pix[-2][c] - pix[2][c]) >> 2;
out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
- pix[-2*width][c] - pix[2*width][c]) >> 2;
out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
}
}
}
void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3])
{
unsigned row, col;
int c, val;
ushort (*pix)[4];
ushort (*rix)[3];
short (*lix)[3];
float xyz[3];
const unsigned num_pix_per_row = 4*width;
const unsigned rowlimit = MIN(top+TS-1, height-3);
const unsigned collimit = MIN(left+TS-1, width-3);
ushort *pix_above;
ushort *pix_below;
int t1, t2;
for (row = top+1; row < rowlimit; row++) {
pix = image + row*width + left;
rix = &inout_rgb[row-top][0];
lix = &out_lab[row-top][0];
for (col = left+1; col < collimit; col++) {
pix++;
pix_above = &pix[0][0] - num_pix_per_row;
pix_below = &pix[0][0] + num_pix_per_row;
rix++;
lix++;
c = 2 - FC(row, col);
if (c == 1) {
c = FC(row+1,col);
t1 = 2-c;
val = pix[0][1] + (( pix[-1][t1] + pix[1][t1]
- rix[-1][1] - rix[1][1] ) >> 1);
rix[0][t1] = CLIP(val);
val = pix[0][1] + (( pix_above[c] + pix_below[c]
- rix[-TS][1] - rix[TS][1] ) >> 1);
} else {
t1 = -4+c; /* -4+c: pixel of color c to the left */
t2 = 4+c; /* 4+c: pixel of color c to the right */
val = rix[0][1] + (( pix_above[t1] + pix_above[t2]
+ pix_below[t1] + pix_below[t2]
- rix[-TS-1][1] - rix[-TS+1][1]
- rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
}
rix[0][c] = CLIP(val);
c = FC(row,col);
rix[0][c] = pix[0][c];
cielab(rix[0],lix[0]);
}
}
}
void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3])
{
int direction;
for (direction = 0; direction < 2; direction++) {
ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]);
}
}
void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int direction;
int i;
short (*lix)[3];
short (*lixs[2])[3];
short *adjacent_lix;
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
static const int dir[4] = { -1, 1, -TS, TS };
const int rowlimit = MIN(top+TS-2, height-4);
const int collimit = MIN(left+TS-2, width-4);
int homogeneity;
char (*homogeneity_map_p)[2];
memset (out_homogeneity_map, 0, 2*TS*TS);
for (row=top+2; row < rowlimit; row++) {
tr = row-top;
homogeneity_map_p = &out_homogeneity_map[tr][1];
for (direction=0; direction < 2; direction++) {
lixs[direction] = &lab[direction][tr][1];
}
for (col=left+2; col < collimit; col++) {
tc = col-left;
homogeneity_map_p++;
for (direction=0; direction < 2; direction++) {
lix = ++lixs[direction];
for (i=0; i < 4; i++) {
adjacent_lix = lix[dir[i]];
ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]);
abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1])
+ SQR(lix[0][2]-adjacent_lix[2]);
}
}
leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
MAX(ldiff[1][2],ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
MAX(abdiff[1][2],abdiff[1][3]));
for (direction=0; direction < 2; direction++) {
homogeneity = 0;
for (i=0; i < 4; i++) {
if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) {
homogeneity++;
}
}
homogeneity_map_p[0][direction] = homogeneity;
}
}
}
}
void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2])
{
int row, col;
int tr, tc;
int i, j;
int direction;
int hm[2];
int c;
const int rowlimit = MIN(top+TS-3, height-5);
const int collimit = MIN(left+TS-3, width-5);
ushort (*pix)[4];
ushort (*rix[2])[3];
for (row=top+3; row < rowlimit; row++) {
tr = row-top;
pix = &image[row*width+left+2];
for (direction = 0; direction < 2; direction++) {
rix[direction] = &rgb[direction][tr][2];
}
for (col=left+3; col < collimit; col++) {
tc = col-left;
pix++;
for (direction = 0; direction < 2; direction++) {
rix[direction]++;
}
for (direction=0; direction < 2; direction++) {
hm[direction] = 0;
for (i=tr-1; i <= tr+1; i++) {
for (j=tc-1; j <= tc+1; j++) {
hm[direction] += homogeneity_map[i][j][direction];
}
}
}
if (hm[0] != hm[1]) {
memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort));
} else {
FORC3 {
pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1;
}
}
}
}
}
void CLASS ahd_interpolate()
{
int i, j, k, top, left;
float xyz_cam[3][4],r;
char *buffer;
ushort (*rgb)[TS][TS][3];
short (*lab)[TS][TS][3];
char (*homo)[TS][2];
int terminate_flag = 0;
cielab(0,0);
border_interpolate(5);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag)
#endif
#endif
{
buffer = (char *) malloc (26*TS*TS); /* 1664 kB */
merror (buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
homo = (char (*)[TS][2]) (buffer + 24*TS*TS);
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
#pragma omp for schedule(dynamic)
#endif
#endif
for (top=2; top < height-5; top += TS-6){
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_USE_OPENMP
if(0== omp_get_thread_num())
#endif
if(callbacks.progress_cb) {
int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7);
if(rr)
terminate_flag = 1;
}
#endif
for (left=2; !terminate_flag && (left < width-5); left += TS-6) {
ahd_interpolate_green_h_and_v(top, left, rgb);
ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab);
ahd_interpolate_build_homogeneity_map(top, left, lab, homo);
ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo);
}
}
free (buffer);
}
#ifdef LIBRAW_LIBRARY_BUILD
if(terminate_flag)
throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK;
#endif
}
#else
void CLASS ahd_interpolate()
{
int i, j, top, left, row, col, tr, tc, c, d, val, hm[2];
static const int dir[4] = { -1, 1, -TS, TS };
unsigned ldiff[2][4], abdiff[2][4], leps, abeps;
ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4];
short (*lab)[TS][TS][3], (*lix)[3];
char (*homo)[TS][TS], *buffer;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("AHD interpolation...\n"));
#endif
cielab (0,0);
border_interpolate(5);
buffer = (char *) malloc (26*TS*TS);
merror (buffer, "ahd_interpolate()");
rgb = (ushort(*)[TS][TS][3]) buffer;
lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS);
homo = (char (*)[TS][TS]) (buffer + 24*TS*TS);
for (top=2; top < height-5; top += TS-6)
for (left=2; left < width-5; left += TS-6) {
/* Interpolate green horizontally and vertically: */
for (row=top; row < top+TS && row < height-2; row++) {
col = left + (FC(row,left) & 1);
for (c = FC(row,col); col < left+TS && col < width-2; col+=2) {
pix = image + row*width+col;
val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2
- pix[-2][c] - pix[2][c]) >> 2;
rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]);
val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2
- pix[-2*width][c] - pix[2*width][c]) >> 2;
rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]);
}
}
/* Interpolate red and blue, and convert to CIELab: */
for (d=0; d < 2; d++)
for (row=top+1; row < top+TS-1 && row < height-3; row++)
for (col=left+1; col < left+TS-1 && col < width-3; col++) {
pix = image + row*width+col;
rix = &rgb[d][row-top][col-left];
lix = &lab[d][row-top][col-left];
if ((c = 2 - FC(row,col)) == 1) {
c = FC(row+1,col);
val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c]
- rix[-1][1] - rix[1][1] ) >> 1);
rix[0][2-c] = CLIP(val);
val = pix[0][1] + (( pix[-width][c] + pix[width][c]
- rix[-TS][1] - rix[TS][1] ) >> 1);
} else
val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c]
+ pix[+width-1][c] + pix[+width+1][c]
- rix[-TS-1][1] - rix[-TS+1][1]
- rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2);
rix[0][c] = CLIP(val);
c = FC(row,col);
rix[0][c] = pix[0][c];
cielab (rix[0],lix[0]);
}
/* Build homogeneity maps from the CIELab images: */
memset (homo, 0, 2*TS*TS);
for (row=top+2; row < top+TS-2 && row < height-4; row++) {
tr = row-top;
for (col=left+2; col < left+TS-2 && col < width-4; col++) {
tc = col-left;
for (d=0; d < 2; d++) {
lix = &lab[d][tr][tc];
for (i=0; i < 4; i++) {
ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]);
abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1])
+ SQR(lix[0][2]-lix[dir[i]][2]);
}
}
leps = MIN(MAX(ldiff[0][0],ldiff[0][1]),
MAX(ldiff[1][2],ldiff[1][3]));
abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]),
MAX(abdiff[1][2],abdiff[1][3]));
for (d=0; d < 2; d++)
for (i=0; i < 4; i++)
if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps)
homo[d][tr][tc]++;
}
}
/* Combine the most homogenous pixels for the final result: */
for (row=top+3; row < top+TS-3 && row < height-5; row++) {
tr = row-top;
for (col=left+3; col < left+TS-3 && col < width-5; col++) {
tc = col-left;
for (d=0; d < 2; d++)
for (hm[d]=0, i=tr-1; i <= tr+1; i++)
for (j=tc-1; j <= tc+1; j++)
hm[d] += homo[d][i][j];
if (hm[0] != hm[1])
FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c];
else
FORC3 image[row*width+col][c] =
(rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1;
}
}
}
free (buffer);
}
#endif
#undef TS
void CLASS median_filter()
{
ushort (*pix)[4];
int pass, c, i, j, k, med[9];
static const uchar opt[] = /* Optimal 9-element median search */
{ 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8,
0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 };
for (pass=1; pass <= med_passes; pass++) {
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes);
#endif
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Median filter pass %d...\n"), pass);
#endif
for (c=0; c < 3; c+=2) {
for (pix = image; pix < image+width*height; pix++)
pix[0][3] = pix[0][c];
for (pix = image+width; pix < image+width*(height-1); pix++) {
if ((pix-image+1) % width < 2) continue;
for (k=0, i = -width; i <= width; i += width)
for (j = i-1; j <= i+1; j++)
med[k++] = pix[j][3] - pix[j][1];
for (i=0; i < sizeof opt; i+=2)
if (med[opt[i]] > med[opt[i+1]])
SWAP (med[opt[i]] , med[opt[i+1]]);
pix[0][c] = CLIP(med[4] + pix[0][1]);
}
}
}
}
void CLASS blend_highlights()
{
int clip=INT_MAX, row, col, c, i, j;
static const float trans[2][4][4] =
{ { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } },
{ { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
static const float itrans[2][4][4] =
{ { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } },
{ { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } };
float cam[2][4], lab[2][4], sum[2], chratio;
if ((unsigned) (colors-3) > 1) return;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Blending highlights...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2);
#endif
FORCC if (clip > (i = 65535*pre_mul[c])) clip = i;
for (row=0; row < height; row++)
for (col=0; col < width; col++) {
FORCC if (image[row*width+col][c] > clip) break;
if (c == colors) continue;
FORCC {
cam[0][c] = image[row*width+col][c];
cam[1][c] = MIN(cam[0][c],clip);
}
for (i=0; i < 2; i++) {
FORCC for (lab[i][c]=j=0; j < colors; j++)
lab[i][c] += trans[colors-3][c][j] * cam[i][j];
for (sum[i]=0,c=1; c < colors; c++)
sum[i] += SQR(lab[i][c]);
}
chratio = sqrt(sum[1]/sum[0]);
for (c=1; c < colors; c++)
lab[0][c] *= chratio;
FORCC for (cam[0][c]=j=0; j < colors; j++)
cam[0][c] += itrans[colors-3][c][j] * lab[0][j];
FORCC image[row*width+col][c] = cam[0][c] / colors;
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2);
#endif
}
#define SCALE (4 >> shrink)
void CLASS recover_highlights()
{
float *map, sum, wgt, grow;
int hsat[4], count, spread, change, val, i;
unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x;
ushort *pixel;
static const signed char dir[8][2] =
{ {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} };
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Rebuilding highlights...\n"));
#endif
grow = pow (2.0, 4-highlight);
FORCC hsat[c] = 32000 * pre_mul[c];
for (kc=0, c=1; c < colors; c++)
if (pre_mul[kc] < pre_mul[c]) kc = c;
high = height / SCALE;
wide = width / SCALE;
map = (float *) calloc (high, wide*sizeof *map);
merror (map, "recover_highlights()");
FORCC if (c != kc) {
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1);
#endif
memset (map, 0, high*wide*sizeof *map);
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
sum = wgt = count = 0;
for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
pixel = image[row*width+col];
if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) {
sum += pixel[c];
wgt += pixel[kc];
count++;
}
}
if (count == SCALE*SCALE)
map[mrow*wide+mcol] = sum / wgt;
}
for (spread = 32/grow; spread--; ) {
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
if (map[mrow*wide+mcol]) continue;
sum = count = 0;
for (d=0; d < 8; d++) {
y = mrow + dir[d][0];
x = mcol + dir[d][1];
if (y < high && x < wide && map[y*wide+x] > 0) {
sum += (1 + (d & 1)) * map[y*wide+x];
count += 1 + (d & 1);
}
}
if (count > 3)
map[mrow*wide+mcol] = - (sum+grow) / (count+grow);
}
for (change=i=0; i < high*wide; i++)
if (map[i] < 0) {
map[i] = -map[i];
change = 1;
}
if (!change) break;
}
for (i=0; i < high*wide; i++)
if (map[i] == 0) map[i] = 1;
for (mrow=0; mrow < high; mrow++)
for (mcol=0; mcol < wide; mcol++) {
for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++)
for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) {
pixel = image[row*width+col];
if (pixel[c] / hsat[c] > 1) {
val = pixel[kc] * map[mrow*wide+mcol];
if (pixel[c] < val) pixel[c] = CLIP(val);
}
}
}
}
free (map);
}
#undef SCALE
void CLASS tiff_get (unsigned base,
unsigned *tag, unsigned *type, unsigned *len, unsigned *save)
{
*tag = get2();
*type = get2();
*len = get4();
*save = ftell(ifp) + 4;
if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4)
fseek (ifp, get4()+base, SEEK_SET);
}
void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen)
{
unsigned entries, tag, type, len, save;
entries = get2();
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
if (tag == toff) thumb_offset = get4()+base;
if (tag == tlen) thumb_length = get4();
fseek (ifp, save, SEEK_SET);
}
}
//@end COMMON
int CLASS parse_tiff_ifd (int base);
//@out COMMON
static float powf_lim(float a, float b, float limup)
{
return (b>limup || b < -limup)?0.f:powf(a,b);
}
static float powf64(float a, float b)
{
return powf_lim(a,b,64.f);
}
#ifdef LIBRAW_LIBRARY_BUILD
static float my_roundf(float x) {
float t;
if (x >= 0.0) {
t = ceilf(x);
if (t - x > 0.5) t -= 1.0;
return t;
} else {
t = ceilf(-x);
if (t + x > 0.5) t -= 1.0;
return -t;
}
}
static float _CanonConvertAperture(ushort in)
{
if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f;
return powf64(2.0, in/64.0);
}
static float _CanonConvertEV (short in)
{
short EV, Sign, Frac;
float Frac_f;
EV = in;
if (EV < 0) {
EV = -EV;
Sign = -1;
} else {
Sign = 1;
}
Frac = EV & 0x1f;
EV -= Frac; // remove fraction
if (Frac == 0x0c) { // convert 1/3 and 2/3 codes
Frac_f = 32.0f / 3.0f;
} else if (Frac == 0x14) {
Frac_f = 64.0f / 3.0f;
} else Frac_f = (float) Frac;
return ((float)Sign * ((float)EV + Frac_f))/32.0f;
}
void CLASS setCanonBodyFeatures (unsigned id)
{
imgdata.lens.makernotes.CamID = id;
if (
(id == 0x80000001) || // 1D
(id == 0x80000174) || // 1D2
(id == 0x80000232) || // 1D2N
(id == 0x80000169) || // 1D3
(id == 0x80000281) // 1D4
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else
if (
(id == 0x80000167) || // 1Ds
(id == 0x80000188) || // 1Ds2
(id == 0x80000215) || // 1Ds3
(id == 0x80000269) || // 1DX
(id == 0x80000328) || // 1DX2
(id == 0x80000324) || // 1DC
(id == 0x80000213) || // 5D
(id == 0x80000218) || // 5D2
(id == 0x80000285) || // 5D3
(id == 0x80000349) || // 5D4
(id == 0x80000382) || // 5DS
(id == 0x80000401) || // 5DS R
(id == 0x80000302) // 6D
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
}
else
if (
(id == 0x80000331) || // M
(id == 0x80000355) || // M2
(id == 0x80000374) || // M3
(id == 0x80000384) || // M10
(id == 0x80000394) // M5
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M;
}
else
if (
(id == 0x01140000) || // D30
(id == 0x01668000) || // D60
(id > 0x80000000)
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen)
{
ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0;
if(maxlen<16) return; // too short, so broken
CameraInfo[0] = 0;
CameraInfo[1] = 0;
switch (id) {
case 0x80000001: // 1D
case 0x80000167: // 1DS
iCanonCurFocal = 10;
iCanonLensID = 13;
iCanonMinFocal = 14;
iCanonMaxFocal = 16;
if (!imgdata.lens.makernotes.CurFocal)
imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal);
if (!imgdata.lens.makernotes.MinFocal)
imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal);
if (!imgdata.lens.makernotes.MaxFocal)
imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal);
break;
case 0x80000174: // 1DMkII
case 0x80000188: // 1DsMkII
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
iCanonFocalType = 45;
break;
case 0x80000232: // 1DMkII N
iCanonCurFocal = 9;
iCanonLensID = 12;
iCanonMinFocal = 17;
iCanonMaxFocal = 19;
break;
case 0x80000169: // 1DMkIII
case 0x80000215: // 1DsMkIII
iCanonCurFocal = 29;
iCanonLensID = 273;
iCanonMinFocal = 275;
iCanonMaxFocal = 277;
break;
case 0x80000281: // 1DMkIV
iCanonCurFocal = 30;
iCanonLensID = 335;
iCanonMinFocal = 337;
iCanonMaxFocal = 339;
break;
case 0x80000269: // 1D X
iCanonCurFocal = 35;
iCanonLensID = 423;
iCanonMinFocal = 425;
iCanonMaxFocal = 427;
break;
case 0x80000213: // 5D
iCanonCurFocal = 40;
if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151;
else iCanonLensID = 12;
iCanonMinFocal = 147;
iCanonMaxFocal = 149;
break;
case 0x80000218: // 5DMkII
iCanonCurFocal = 30;
iCanonLensID = 230;
iCanonMinFocal = 232;
iCanonMaxFocal = 234;
break;
case 0x80000285: // 5DMkIII
iCanonCurFocal = 35;
iCanonLensID = 339;
iCanonMinFocal = 341;
iCanonMaxFocal = 343;
break;
case 0x80000302: // 6D
iCanonCurFocal = 35;
iCanonLensID = 353;
iCanonMinFocal = 355;
iCanonMaxFocal = 357;
break;
case 0x80000250: // 7D
iCanonCurFocal = 30;
iCanonLensID = 274;
iCanonMinFocal = 276;
iCanonMaxFocal = 278;
break;
case 0x80000190: // 40D
iCanonCurFocal = 29;
iCanonLensID = 214;
iCanonMinFocal = 216;
iCanonMaxFocal = 218;
iCanonLens = 2347;
break;
case 0x80000261: // 50D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000287: // 60D
iCanonCurFocal = 30;
iCanonLensID = 232;
iCanonMinFocal = 234;
iCanonMaxFocal = 236;
break;
case 0x80000325: // 70D
iCanonCurFocal = 35;
iCanonLensID = 358;
iCanonMinFocal = 360;
iCanonMaxFocal = 362;
break;
case 0x80000176: // 450D
iCanonCurFocal = 29;
iCanonLensID = 222;
iCanonLens = 2355;
break;
case 0x80000252: // 500D
iCanonCurFocal = 30;
iCanonLensID = 246;
iCanonMinFocal = 248;
iCanonMaxFocal = 250;
break;
case 0x80000270: // 550D
iCanonCurFocal = 30;
iCanonLensID = 255;
iCanonMinFocal = 257;
iCanonMaxFocal = 259;
break;
case 0x80000286: // 600D
case 0x80000288: // 1100D
iCanonCurFocal = 30;
iCanonLensID = 234;
iCanonMinFocal = 236;
iCanonMaxFocal = 238;
break;
case 0x80000301: // 650D
case 0x80000326: // 700D
iCanonCurFocal = 35;
iCanonLensID = 295;
iCanonMinFocal = 297;
iCanonMaxFocal = 299;
break;
case 0x80000254: // 1000D
iCanonCurFocal = 29;
iCanonLensID = 226;
iCanonMinFocal = 228;
iCanonMaxFocal = 230;
iCanonLens = 2359;
break;
}
if (iCanonFocalType)
{
if(iCanonFocalType>=maxlen) return; // broken;
imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType];
if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1'
imgdata.lens.makernotes.FocalType = 1;
}
if (!imgdata.lens.makernotes.CurFocal)
{
if(iCanonCurFocal>=maxlen) return; // broken;
imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal);
}
if (!imgdata.lens.makernotes.LensID)
{
if(iCanonLensID>=maxlen) return; // broken;
imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID);
}
if (!imgdata.lens.makernotes.MinFocal)
{
if(iCanonMinFocal>=maxlen) return; // broken;
imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal);
}
if (!imgdata.lens.makernotes.MaxFocal)
{
if(iCanonMaxFocal>=maxlen) return; // broken;
imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal);
}
if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) {
if(iCanonLens+64>=maxlen) return; // broken;
if (CameraInfo[iCanonLens] < 65) // non-Canon lens
{
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4))
{
memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) {
memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60);
}
else {
memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2);
memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
imgdata.lens.makernotes.Lens[2] = 32;
memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62);
}
}
return;
}
void CLASS Canon_CameraSettings ()
{
fseek(ifp, 10, SEEK_CUR);
imgdata.shootinginfo.DriveMode = get2(); get2();
imgdata.shootinginfo.FocusMode = get2();
fseek(ifp, 18, SEEK_CUR);
imgdata.shootinginfo.MeteringMode = get2(); get2();
imgdata.shootinginfo.AFPoint = get2();
imgdata.shootinginfo.ExposureMode = get2(); get2();
imgdata.lens.makernotes.LensID = get2();
imgdata.lens.makernotes.MaxFocal = get2();
imgdata.lens.makernotes.MinFocal = get2();
imgdata.lens.makernotes.CanonFocalUnits = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2());
imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2());
fseek(ifp, 12, SEEK_CUR);
imgdata.shootinginfo.ImageStabilization = get2();
}
void CLASS Canon_WBpresets (int skip1, int skip2)
{
int c;
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
if (skip1) fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
if (skip1) fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
if (skip1) fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
if (skip1) fseek(ifp, skip1, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
if (skip2) fseek(ifp, skip2, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
return;
}
void CLASS Canon_WBCTpresets (short WBCTversion)
{
if (WBCTversion == 0)
for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
fseek (ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ;
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if (WBCTversion == 1)
for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT
{
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f);
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f);
fseek (ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) &&
((unique_id == 0x80000374) || // M3
(unique_id == 0x80000384) || // M10
(unique_id == 0x80000394) || // M5
(unique_id == 0x03970000))) // G7 X Mark II
for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek (ifp, 2, SEEK_CUR);
fseek (ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2());
imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2());
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
else if ((WBCTversion == 2) &&
((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X
for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT
{
fseek (ifp, 2, SEEK_CUR);
fseek (ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f;
imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f;
imgdata.color.WBCT_Coeffs[i][0] = get2();
}
return;
}
void CLASS processNikonLensData (uchar *LensData, unsigned len)
{
ushort i;
if (!(imgdata.lens.nikon.NikonLensType & 0x01))
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'A';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
else
{
imgdata.lens.makernotes.LensFeatures_pre[0] = 'M';
imgdata.lens.makernotes.LensFeatures_pre[1] = 'F';
}
if (imgdata.lens.nikon.NikonLensType & 0x02)
{
if (imgdata.lens.nikon.NikonLensType & 0x04)
imgdata.lens.makernotes.LensFeatures_suf[0] = 'G';
else
imgdata.lens.makernotes.LensFeatures_suf[0] = 'D';
imgdata.lens.makernotes.LensFeatures_suf[1] = ' ';
}
if (imgdata.lens.nikon.NikonLensType & 0x08)
{
imgdata.lens.makernotes.LensFeatures_suf[2] = 'V';
imgdata.lens.makernotes.LensFeatures_suf[3] = 'R';
}
if (imgdata.lens.nikon.NikonLensType & 0x10)
{
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH;
}
else
imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F;
if (imgdata.lens.nikon.NikonLensType & 0x20)
{
strcpy(imgdata.lens.makernotes.Adapter, "FT-1");
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf;
if (len < 20) {
switch (len) {
case 9:
i = 2;
break;
case 15:
i = 7;
break;
case 16:
i = 8;
break;
}
imgdata.lens.nikon.NikonLensIDNumber = LensData[i];
imgdata.lens.nikon.NikonLensFStops = LensData[i + 1];
imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f;
if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f)
{
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2])
imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3])
imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4])
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f);
if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5])
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f);
}
imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6];
if (i != 2)
{
if ((LensData[i - 1]) &&
(fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f))
imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f);
if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f);
}
imgdata.lens.makernotes.LensID =
(unsigned long long) LensData[i] << 56 |
(unsigned long long) LensData[i + 1] << 48 |
(unsigned long long) LensData[i + 2] << 40 |
(unsigned long long) LensData[i + 3] << 32 |
(unsigned long long) LensData[i + 4] << 24 |
(unsigned long long) LensData[i + 5] << 16 |
(unsigned long long) LensData[i + 6] << 8 |
(unsigned long long) imgdata.lens.nikon.NikonLensType;
}
else if ((len == 459) || (len == 590))
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64);
}
else if (len == 509)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64);
}
else if (len == 879)
{
memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64);
}
return;
}
void CLASS setOlympusBodyFeatures (unsigned long long id)
{
imgdata.lens.makernotes.CamID = id;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-300
((id & 0x00ffff0000ULL) == 0x0030300000ULL))
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT;
if ((id == 0x4434303430ULL) || // E-1
(id == 0x4434303431ULL) || // E-330
((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520
(id == 0x5330303233ULL) || // E-620
(id == 0x5330303239ULL) || // E-450
(id == 0x5330303330ULL) || // E-600
(id == 0x5330303333ULL)) // E-5
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT;
}
}
else
{
imgdata.lens.makernotes.LensMount =
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) {
if (tag == 0x0001) Canon_CameraSettings();
else if (tag == 0x0002) // focal length
{
imgdata.lens.makernotes.FocalType = get2();
imgdata.lens.makernotes.CurFocal = get2();
if (imgdata.lens.makernotes.CanonFocalUnits > 1)
{
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
}
else if (tag == 0x0004) // shot info
{
short tempAp;
fseek(ifp, 30, SEEK_CUR);
imgdata.other.FlashEC = _CanonConvertEV((signed short)get2());
fseek(ifp, 8-32, SEEK_CUR);
if ((tempAp = get2()) != 0x7fff)
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp);
if (imgdata.lens.makernotes.CurAp < 0.7f)
{
fseek(ifp, 32, SEEK_CUR);
imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2());
}
if (!aperture) aperture = imgdata.lens.makernotes.CurAp;
}
else if (tag == 0x0095 && // lens model tag
!imgdata.lens.makernotes.Lens[0])
{
fread(imgdata.lens.makernotes.Lens, 2, 1, ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens
fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp);
else
{
char efs[2];
imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0];
imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1];
fread(efs, 2, 1, ifp);
if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77))
{ // "EF-S, TS-E, MP-E, EF-M" lenses
imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0];
imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1];
imgdata.lens.makernotes.Lens[4] = 32;
if (efs[1] == 83)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
else if (efs[1] == 77)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M;
}
}
else
{ // "EF" lenses
imgdata.lens.makernotes.Lens[2] = 32;
imgdata.lens.makernotes.Lens[3] = efs[0];
imgdata.lens.makernotes.Lens[4] = efs[1];
}
fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp);
}
}
else if (tag == 0x00a9)
{
long int save1 = ftell(ifp);
fseek (ifp, save1+(0x5<<1), SEEK_SET);
Canon_WBpresets(0,0);
fseek (ifp, save1, SEEK_SET);
}
else if (tag == 0x00e0) // sensor info
{
imgdata.makernotes.canon.SensorWidth = (get2(),get2());
imgdata.makernotes.canon.SensorHeight = get2();
imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2());
imgdata.makernotes.canon.SensorTopBorder = get2();
imgdata.makernotes.canon.SensorRightBorder = get2();
imgdata.makernotes.canon.SensorBottomBorder = get2();
imgdata.makernotes.canon.BlackMaskLeftBorder = get2();
imgdata.makernotes.canon.BlackMaskTopBorder = get2();
imgdata.makernotes.canon.BlackMaskRightBorder = get2();
imgdata.makernotes.canon.BlackMaskBottomBorder = get2();
}
else if (tag == 0x4001 && len > 500)
{
int c;
long int save1 = ftell(ifp);
switch (len)
{
case 582:
imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D
{
fseek (ifp, save1+(0x23<<1), SEEK_SET);
Canon_WBpresets(2,2);
fseek (ifp, save1+(0x4b<<1), SEEK_SET);
Canon_WBCTpresets (1); // ABCT
}
break;
case 653:
imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2
{
fseek (ifp, save1+(0x27<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0xa4<<1), SEEK_SET);
Canon_WBCTpresets (1); // ABCT
}
break;
case 796:
imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x4e<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0x85<<1), SEEK_SET);
Canon_WBCTpresets (0); // BCAT
fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
break;
// 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII
// 7D / 40D / 50D / 60D / 450D / 500D
// 550D / 1000D / 1100D
case 674: case 692: case 702: case 1227: case 1250:
case 1251: case 1337: case 1338: case 1346:
imgdata.makernotes.canon.CanonColorDataVer = 4;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x53<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0xa8<<1), SEEK_SET);
Canon_WBCTpresets (0); // BCAT
fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4)
|| (imgdata.makernotes.canon.CanonColorDataSubVer == 5))
{
fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) ||
(imgdata.makernotes.canon.CanonColorDataSubVer == 7))
{
fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9)
{
fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
case 5120:
imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5
{
fseek (ifp, save1+(0x56<<1), SEEK_SET);
if ((unique_id == 0x03970000) || // G7 X Mark II
(unique_id == 0x80000394)) // EOS M5
{
fseek(ifp, 18, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
fseek(ifp, 8, SEEK_CUR);
Canon_WBpresets(8,24);
fseek(ifp, 168, SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2();
fseek(ifp, 24, SEEK_CUR);
Canon_WBCTpresets (2); // BCADT
fseek(ifp, 6, SEEK_CUR);
}
else
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2();
get2();
Canon_WBpresets(2,12);
fseek (ifp, save1+(0xba<<1), SEEK_SET);
Canon_WBCTpresets (2); // BCADT
fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short
}
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
break;
case 1273: case 1275:
imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x67<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0xbc<<1), SEEK_SET);
Canon_WBCTpresets (0); // BCAT
fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
break;
// 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D
case 1312: case 1313: case 1316: case 1506:
imgdata.makernotes.canon.CanonColorDataVer = 7;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x80<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0xd5<<1), SEEK_SET);
Canon_WBCTpresets (0); // BCAT
fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 10)
{
fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
} else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11)
{
fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
// 5DS / 5DS R / 80D / 1300D / 5D4
case 1560: case 1592: case 1353:
imgdata.makernotes.canon.CanonColorDataVer = 8;
imgdata.makernotes.canon.CanonColorDataSubVer = get2();
{
fseek (ifp, save1+(0x85<<1), SEEK_SET);
Canon_WBpresets(2,12);
fseek (ifp, save1+(0x107<<1), SEEK_SET);
Canon_WBCTpresets (0); // BCAT
fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts
int bls=0;
FORC4
bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2());
imgdata.makernotes.canon.AverageBlackLevel = bls/4;
}
if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D
{
fseek (ifp, save1+(0x231<<1), SEEK_SET);
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
else
{
fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts
imgdata.makernotes.canon.SpecularWhiteLevel = get2();
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel;
}
break;
}
fseek (ifp, save1, SEEK_SET);
}
}
void CLASS setPentaxBodyFeatures (unsigned id)
{
imgdata.lens.makernotes.CamID = id;
switch (id) {
case 0x12994:
case 0x12aa2:
case 0x12b1a:
case 0x12b60:
case 0x12b62:
case 0x12b7e:
case 0x12b80:
case 0x12b9c:
case 0x12b9d:
case 0x12ba2:
case 0x12c1e:
case 0x12c20:
case 0x12cd2:
case 0x12cd4:
case 0x12cfa:
case 0x12d72:
case 0x12d73:
case 0x12db8:
case 0x12dfe:
case 0x12e6c:
case 0x12e76:
case 0x12ef8:
case 0x12f52:
case 0x12f70:
case 0x12f71:
case 0x12fb6:
case 0x12fc0:
case 0x12fca:
case 0x1301a:
case 0x13024:
case 0x1309c:
case 0x13222:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
break;
case 0x13092:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
break;
case 0x12e08:
case 0x13010:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF;
break;
case 0x12ee4:
case 0x12f66:
case 0x12f7a:
case 0x1302e:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q;
break;
default:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
return;
}
void CLASS PentaxISO (ushort c)
{
int code [] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278};
double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200};
#define numel (sizeof(code)/sizeof(code[0]))
int i;
for (i = 0; i < numel; i++) {
if (code[i] == c) {
iso_speed = value[i];
return;
}
}
if (i == numel) iso_speed = 65535.0f;
}
#undef numel
void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207
{
ushort iLensData = 0;
uchar *table_buf;
table_buf = (uchar*)malloc(MAX(len,128));
fread(table_buf, len, 1, ifp);
if ((id < 0x12b9c) ||
(((id == 0x12b9c) || // K100D
(id == 0x12b9d) || // K110D
(id == 0x12ba2)) && // K100D Super
((!table_buf[20] ||
(table_buf[20] == 0xff)))))
{
iLensData = 3;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
(((unsigned)table_buf[0]) << 8) + table_buf[1];
}
else switch (len)
{
case 90: // LensInfo3
iLensData = 13;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 91: // LensInfo4
iLensData = 12;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4];
break;
case 80: // LensInfo5
case 128:
iLensData = 15;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5];
break;
default:
if (id >= 0x12b9c) // LensInfo2
{
iLensData = 4;
if (imgdata.lens.makernotes.LensID == -1)
imgdata.lens.makernotes.LensID =
((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3];
}
}
if (iLensData)
{
if (table_buf[iLensData+9] &&
(fabs(imgdata.lens.makernotes.CurFocal) < 0.1f))
imgdata.lens.makernotes.CurFocal =
10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2);
if (table_buf[iLensData+10] & 0xf0)
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f);
if (table_buf[iLensData+10] & 0x0f)
imgdata.lens.makernotes.MinAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f);
if (iLensData != 12)
{
switch (table_buf[iLensData] & 0x06)
{
case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break;
case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break;
case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break;
case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break;
}
if (table_buf[iLensData] & 0x70)
imgdata.lens.makernotes.LensFStops =
((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f;
imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8);
imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07);
if ((table_buf[iLensData+14] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f);
}
else if ((id != 0x12e76) && // K-5
(table_buf[iLensData+15] > 1) &&
(fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f))
{
imgdata.lens.makernotes.MaxAp4CurFocal =
powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f);
}
}
free(table_buf);
return;
}
void CLASS setPhaseOneFeatures (unsigned id) {
ushort i;
static const struct {
ushort id;
char t_model[32];
} p1_unique[] = {
// Phase One section:
{1, "Hasselblad V"},
{10, "PhaseOne/Mamiya"},
{12, "Contax 645"},
{16, "Hasselblad V"},
{17, "Hasselblad V"},
{18, "Contax 645"},
{19, "PhaseOne/Mamiya"},
{20, "Hasselblad V"},
{21, "Contax 645"},
{22, "PhaseOne/Mamiya"},
{23, "Hasselblad V"},
{24, "Hasselblad H"},
{25, "PhaseOne/Mamiya"},
{32, "Contax 645"},
{34, "Hasselblad V"},
{35, "Hasselblad V"},
{36, "Hasselblad H"},
{37, "Contax 645"},
{38, "PhaseOne/Mamiya"},
{39, "Hasselblad V"},
{40, "Hasselblad H"},
{41, "Contax 645"},
{42, "PhaseOne/Mamiya"},
{44, "Hasselblad V"},
{45, "Hasselblad H"},
{46, "Contax 645"},
{47, "PhaseOne/Mamiya"},
{48, "Hasselblad V"},
{49, "Hasselblad H"},
{50, "Contax 645"},
{51, "PhaseOne/Mamiya"},
{52, "Hasselblad V"},
{53, "Hasselblad H"},
{54, "Contax 645"},
{55, "PhaseOne/Mamiya"},
{67, "Hasselblad V"},
{68, "Hasselblad H"},
{69, "Contax 645"},
{70, "PhaseOne/Mamiya"},
{71, "Hasselblad V"},
{72, "Hasselblad H"},
{73, "Contax 645"},
{74, "PhaseOne/Mamiya"},
{76, "Hasselblad V"},
{77, "Hasselblad H"},
{78, "Contax 645"},
{79, "PhaseOne/Mamiya"},
{80, "Hasselblad V"},
{81, "Hasselblad H"},
{82, "Contax 645"},
{83, "PhaseOne/Mamiya"},
{84, "Hasselblad V"},
{85, "Hasselblad H"},
{86, "Contax 645"},
{87, "PhaseOne/Mamiya"},
{99, "Hasselblad V"},
{100, "Hasselblad H"},
{101, "Contax 645"},
{102, "PhaseOne/Mamiya"},
{103, "Hasselblad V"},
{104, "Hasselblad H"},
{105, "PhaseOne/Mamiya"},
{106, "Contax 645"},
{112, "Hasselblad V"},
{113, "Hasselblad H"},
{114, "Contax 645"},
{115, "PhaseOne/Mamiya"},
{131, "Hasselblad V"},
{132, "Hasselblad H"},
{133, "Contax 645"},
{134, "PhaseOne/Mamiya"},
{135, "Hasselblad V"},
{136, "Hasselblad H"},
{137, "Contax 645"},
{138, "PhaseOne/Mamiya"},
{140, "Hasselblad V"},
{141, "Hasselblad H"},
{142, "Contax 645"},
{143, "PhaseOne/Mamiya"},
{148, "Hasselblad V"},
{149, "Hasselblad H"},
{150, "Contax 645"},
{151, "PhaseOne/Mamiya"},
{160, "A-250"},
{161, "A-260"},
{162, "A-280"},
{167, "Hasselblad V"},
{168, "Hasselblad H"},
{169, "Contax 645"},
{170, "PhaseOne/Mamiya"},
{172, "Hasselblad V"},
{173, "Hasselblad H"},
{174, "Contax 645"},
{175, "PhaseOne/Mamiya"},
{176, "Hasselblad V"},
{177, "Hasselblad H"},
{178, "Contax 645"},
{179, "PhaseOne/Mamiya"},
{180, "Hasselblad V"},
{181, "Hasselblad H"},
{182, "Contax 645"},
{183, "PhaseOne/Mamiya"},
{208, "Hasselblad V"},
{211, "PhaseOne/Mamiya"},
{448, "Phase One 645AF"},
{457, "Phase One 645DF"},
{471, "Phase One 645DF+"},
{704, "Phase One iXA"},
{705, "Phase One iXA - R"},
{706, "Phase One iXU 150"},
{707, "Phase One iXU 150 - NIR"},
{708, "Phase One iXU 180"},
{721, "Phase One iXR"},
// Leaf section:
{333,"Mamiya"},
{329,"Universal"},
{330,"Hasselblad H1/H2"},
{332,"Contax"},
{336,"AFi"},
{327,"Mamiya"},
{324,"Universal"},
{325,"Hasselblad H1/H2"},
{326,"Contax"},
{335,"AFi"},
{340,"Mamiya"},
{337,"Universal"},
{338,"Hasselblad H1/H2"},
{339,"Contax"},
{323,"Mamiya"},
{320,"Universal"},
{322,"Hasselblad H1/H2"},
{321,"Contax"},
{334,"AFi"},
{369,"Universal"},
{370,"Mamiya"},
{371,"Hasselblad H1/H2"},
{372,"Contax"},
{373,"Afi"},
};
imgdata.lens.makernotes.CamID = id;
if (id && !imgdata.lens.makernotes.body[0]) {
for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++)
if (id == p1_unique[i].id) {
strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model);
}
}
return;
}
void CLASS parseFujiMakernotes (unsigned tag, unsigned type) {
switch (tag) {
case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break;
case 0x1011: imgdata.other.FlashEC = getreal(type); break;
case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break;
case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break;
case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break;
case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2();
imgdata.makernotes.fuji.FocusPixel[1] = get2();
break;
case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break;
case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break;
case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break;
case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break;
case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break;
case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break;
case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break;
case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break;
case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break;
case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break;
case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break;
case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2();
imgdata.makernotes.fuji.ImageStabilization[1] = get2();
imgdata.makernotes.fuji.ImageStabilization[2] = get2();
imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1];
break;
case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break;
case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break;
case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break;
case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break;
}
return;
}
void CLASS setSonyBodyFeatures (unsigned id) {
imgdata.lens.makernotes.CamID = id;
if ( // FF cameras
(id == 257) || // a900
(id == 269) || // a850
(id == 340) || // ILCE-7M2
(id == 318) || // ILCE-7S
(id == 350) || // ILCE-7SM2
(id == 311) || // ILCE-7R
(id == 347) || // ILCE-7RM2
(id == 306) || // ILCE-7
(id == 298) || // DSC-RX1
(id == 299) || // NEX-VG900
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 354) || // ILCA-99M2
(id == 294) // SLT-99, Hasselblad HV
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
else if ((id == 297) || // DSC-RX100
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) // DSC-RX100M5
)
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH;
}
else if (id != 002) // DSC-R1
{
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
}
if ( // E-mount cameras, ILCE series
(id == 302) ||
(id == 306) ||
(id == 311) ||
(id == 312) ||
(id == 313) ||
(id == 318) ||
(id == 339) ||
(id == 340) ||
(id == 346) ||
(id == 347) ||
(id == 350) ||
(id == 360)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE;
}
else if ( // E-mount cameras, NEX series
(id == 278) ||
(id == 279) ||
(id == 284) ||
(id == 288) ||
(id == 289) ||
(id == 290) ||
(id == 293) ||
(id == 295) ||
(id == 296) ||
(id == 299) ||
(id == 300) ||
(id == 305) ||
(id == 307)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX;
}
else if ( // A-mount cameras, DSLR series
(id == 256) ||
(id == 257) ||
(id == 258) ||
(id == 259) ||
(id == 260) ||
(id == 261) ||
(id == 262) ||
(id == 263) ||
(id == 264) ||
(id == 265) ||
(id == 266) ||
(id == 269) ||
(id == 270) ||
(id == 273) ||
(id == 274) ||
(id == 275) ||
(id == 282) ||
(id == 283)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR;
}
else if ( // A-mount cameras, SLT series
(id == 280) ||
(id == 281) ||
(id == 285) ||
(id == 286) ||
(id == 287) ||
(id == 291) ||
(id == 292) ||
(id == 294) ||
(id == 303)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT;
}
else if ( // A-mount cameras, ILCA series
(id == 319) ||
(id == 353) ||
(id == 354)
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA;
}
else if ( // DSC
(id == 002) || // DSC-R1
(id == 297) || // DSC-RX100
(id == 298) || // DSC-RX1
(id == 308) || // DSC-RX100M2
(id == 309) || // DSC-RX10
(id == 310) || // DSC-RX1R
(id == 344) || // DSC-RX1RM2
(id == 317) || // DSC-RX100M3
(id == 341) || // DSC-RX100M4
(id == 342) || // DSC-RX10M2
(id == 355) || // DSC-RX10M3
(id == 356) // DSC-RX100M5
)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC;
}
return;
}
void CLASS parseSonyLensType2 (uchar a, uchar b) {
ushort lid2;
lid2 = (((ushort)a)<<8) | ((ushort)b);
if (!lid2) return;
if (lid2 < 0x100)
{
if ((imgdata.lens.makernotes.AdapterID != 0x4900) &&
(imgdata.lens.makernotes.AdapterID != 0xEF00))
{
imgdata.lens.makernotes.AdapterID = lid2;
switch (lid2) {
case 1:
case 2:
case 3:
case 6:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 44:
case 78:
case 239:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
break;
}
}
}
else
imgdata.lens.makernotes.LensID = lid2;
if ((lid2 >= 50481) && (lid2 < 50500))
{
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
imgdata.lens.makernotes.AdapterID = 0x4900;
}
return;
}
#define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf)))
void CLASS parseSonyLensFeatures (uchar a, uchar b) {
ushort features;
features = (((ushort)a)<<8) | ((ushort)b);
if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) ||
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) ||
!features)
return;
imgdata.lens.makernotes.LensFeatures_pre[0] = 0;
imgdata.lens.makernotes.LensFeatures_suf[0] = 0;
if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E");
else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE");
else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT");
if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount)
{
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
if ((features & 0x0200) && (features & 0x0100)) {
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
} else if (features & 0x0200) {
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
} else if (features & 0x0100) {
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC;
}
}
if (features & 0x4000)
strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ");
if (features & 0x0008)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G");
else if (features & 0x0004)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" );
if ((features & 0x0020) && (features & 0x0040))
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro");
else if (features & 0x0020)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF");
else if (features & 0x0040)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex");
else if (features & 0x0080)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye");
if (features & 0x0001)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM");
else if (features & 0x0002)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM");
if (features & 0x8000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS");
if (features & 0x2000)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE");
if (features & 0x0800)
strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II");
if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ')
memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1,
strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1);
return;
}
#undef strnXcat
void CLASS process_Sony_0x940c (uchar * buf)
{
ushort lid2;
if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
{
switch (SonySubstitution[buf[0x0008]]) {
case 1:
case 5:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A;
break;
case 4:
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E;
break;
}
}
lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) |
((ushort)SonySubstitution[buf[0x0009]]);
if ((lid2 > 0) && (lid2 < 32784))
parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0009]]);
return;
}
void CLASS process_Sony_0x9050 (uchar * buf, unsigned id)
{
ushort lid;
if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) &&
(imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens))
{
if (buf[0])
imgdata.lens.makernotes.MaxAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f;
if (buf[1])
imgdata.lens.makernotes.MinAp4CurFocal =
my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f;
}
if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
{
if (buf[0x3d] | buf[0x3c])
{
lid = SonySubstitution[buf[0x3d]] << 8 |
SonySubstitution[buf[0x3c]];
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f);
}
if (buf[0x105] &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) &&
(imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F))
imgdata.lens.makernotes.LensMount =
SonySubstitution[buf[0x105]];
if (buf[0x106])
imgdata.lens.makernotes.LensFormat =
SonySubstitution[buf[0x106]];
}
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids
SonySubstitution[buf[0x0107]]);
}
if ((imgdata.lens.makernotes.LensID == -1) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) &&
(buf[0x010a] | buf[0x0109]))
{
imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids
SonySubstitution[buf[0x010a]] << 8 |
SonySubstitution[buf[0x0109]];
if ((imgdata.lens.makernotes.LensID > 0x4900) &&
(imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) &&
(imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
}
if ((id >= 286) && (id <= 293))
// "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E",
// "SLT-A37", "SLT-A57", "NEX-F3", "Lunar"
parseSonyLensFeatures (SonySubstitution[buf[0x115]],
SonySubstitution[buf[0x116]]);
else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)
parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]);
if ((id == 347) || (id == 350) || (id == 357))
{
unsigned long long b88 = SonySubstitution[buf[0x88]];
unsigned long long b89 = SonySubstitution[buf[0x89]];
unsigned long long b8a = SonySubstitution[buf[0x8a]];
unsigned long long b8b = SonySubstitution[buf[0x8b]];
unsigned long long b8c = SonySubstitution[buf[0x8c]];
unsigned long long b8d = SonySubstitution[buf[0x8d]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx",
(b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283))
{
unsigned long long bf0 = SonySubstitution[buf[0xf0]];
unsigned long long bf1 = SonySubstitution[buf[0xf1]];
unsigned long long bf2 = SonySubstitution[buf[0xf2]];
unsigned long long bf3 = SonySubstitution[buf[0xf3]];
unsigned long long bf4 = SonySubstitution[buf[0xf4]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx",
(bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4);
}
else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290))
{
unsigned b7c = SonySubstitution[buf[0x7c]];
unsigned b7d = SonySubstitution[buf[0x7d]];
unsigned b7e = SonySubstitution[buf[0x7e]];
unsigned b7f = SonySubstitution[buf[0x7f]];
sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f);
}
return;
}
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c;
unsigned i;
uchar NikonKey, ci, cj, ck;
unsigned serial = 0;
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
short morder, sorder = order;
char buf[10];
INT64 fsize = ifp->size();
fread(buf, 1, 10, ifp);
if (!strcmp(buf, "Nikon")) {
base = ftell(ifp);
order = get2();
if (get2() != 42) goto quit;
offset = get4();
fseek(ifp, offset - 8, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMPUS") ||
!strcmp(buf, "PENTAX ") ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) {
base = ftell(ifp) - 10;
fseek(ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O') get2();
}
else if (!strncmp(buf, "SONY", 4) ||
!strcmp(buf, "Panasonic")) {
goto nf;
}
else if (!strncmp(buf, "FUJIFILM", 8)) {
base = ftell(ifp) - 10;
nf: order = 0x4949;
fseek(ifp, 2, SEEK_CUR);
}
else if (!strcmp(buf, "OLYMP") ||
!strcmp(buf, "LEICA") ||
!strcmp(buf, "Ricoh") ||
!strcmp(buf, "EPSON"))
fseek(ifp, -2, SEEK_CUR);
else if (!strcmp(buf, "AOC") ||
!strcmp(buf, "QVC"))
fseek(ifp, -4, SEEK_CUR);
else {
fseek(ifp, -10, SEEK_CUR);
if ((!strncmp(make, "SAMSUNG", 7) &&
(dng_writer == AdobeDNG)))
base = ftell(ifp);
}
entries = get2();
if (entries > 1000) return;
morder = order;
while (entries--) {
order = morder;
tiff_get(base, &tag, &type, &len, &save);
INT64 pos = ifp->tell();
if(len > 8 && pos+len > 2* fsize) continue;
tag |= uptag << 16;
if(len > 100*1024*1024) goto next; // 100Mb tag? No!
if (!strncmp(make, "Canon",5))
{
if (tag == 0x000d && len < 256000) // camera info
{
CanonCameraInfo = (uchar*)malloc(MAX(16,len));
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
if (unique_id == 0x03740000) unique_id = 0x80000374; // M3
if (unique_id == 0x03840000) unique_id = 0x80000384; // M10
if (unique_id == 0x03940000) unique_id = 0x80000394; // M5
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else parseCanonMakernotes (tag, type, len);
}
else if (!strncmp(make, "FUJI", 4))
parseFujiMakernotes (tag, type);
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e?0:1;
for (int j=0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type);
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len,ifp);
}
if ((tag == 0x3405) ||
(tag == 0x0310) ||
(tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID>>2)<<8) |
(imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') ||
!strncasecmp (model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') ||
!strncasecmp (model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (
((tag == 0x0313) || (tag == 0x34003406)) &&
(fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5))
)
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote (base, 0x3400);
}
}
else if (!strncmp(make, "NIKON", 5))
{
if (tag == 0x1d) // serial number
while ((c = fgetc(ifp)) && c != EOF)
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model,"D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
}
else if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a*b*(12/c);
imgdata.lens.makernotes.LensFStops =
(float)imgdata.lens.nikon.NikonLensFStops /12.0f;
}
}
else if (tag == 0x0093)
{
i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0097)
{
for (i=0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp)-'0';
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100: lenNikonLensData = 9; break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203: lenNikonLensData = 15; break;
case 204: lenNikonLensData = 16; break;
case 400: lenNikonLensData = 459; break;
case 401: lenNikonLensData = 590; break;
case 402: lenNikonLensData = 509; break;
case 403: lenNikonLensData = 879; break;
}
if(lenNikonLensData)
{
table_buf = (uchar*)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0xa7) // shutter count
{
NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp);
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
else if (tag == 37 && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc, 1, 1, ifp);
iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0));
break;
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
int SubDirOffsetValid =
strncmp (model, "E-300", 5) &&
strncmp (model, "E-330", 5) &&
strncmp (model, "E-400", 5) &&
strncmp (model, "E-500", 5) &&
strncmp (model, "E-1", 3);
if ((tag == 0x2010) || (tag == 0x2020))
{
fseek(ifp, save - 4, SEEK_SET);
fseek(ifp, base + get4(), SEEK_SET);
parse_makernote_0xc634(base, tag, dng_writer);
}
if (!SubDirOffsetValid &&
((len > 4) ||
( ((type == 3) || (type == 8)) && (len > 2)) ||
( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9)))
goto skip_Oly_broken_tags;
switch (tag) {
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
unsigned long long OlyID;
fread (sOlyID, MIN(len,7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2);
break;
case 0x20100102:
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x20100201:
imgdata.lens.makernotes.LensID =
(unsigned long long)fgetc(ifp)<<16 |
(unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 |
(unsigned long long)fgetc(ifp);
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) ||
(imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
if ((!imgdata.lens.LensSerial[0]))
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens,len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID =
imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment,len, ifp);
break;
case 0x20200401:
imgdata.other.FlashEC = getreal(type);
break;
}
skip_Oly_broken_tags:;
}
else if (!strncmp(make, "PENTAX", 6) ||
!strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG)))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2()/10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f;
else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] =
imgdata.color.linear_max[1] =
imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if(len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if (tag == 0x020d)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
}
else if (tag == 0x020e)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
}
else if (tag == 0x020f)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0210)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0211)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0212)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0213)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0214)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek (ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
fseek (ifp,2,SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo [20];
fseek (ifp, 12, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7) &&
(dng_writer == AdobeDNG))
{
if (tag == 0x0002)
{
if(get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
imgdata.lens.makernotes.CamID = unique_id = get4();
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) ||
!strncasecmp(model, "HV",2))))
{
ushort lid;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x9050_present)
{
process_Sony_0x9050(table_buf_0x9050, unique_id);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x940c_present)
{
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
process_Sony_0x940c(table_buf_0x940c);
}
free (table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) &&
strncasecmp(model, "NEX-5C", 6) &&
!strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360))
)
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len) {
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))
{
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
}
break;
default:
// CameraInfo2 & 3
if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
}
free(table_buf);
}
else if (tag == 0x0104)
{
imgdata.other.FlashEC = getreal(type);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114 && len < 65535) // CameraSettings
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len) {
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2])<<8) |
((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153]) {
case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break;
case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar*)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x940c && len < 256000)
{
table_buf_0x940c = (uchar*)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 0x4900) &&
(imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) &&
(imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a && len < 256000) // Sony LensSpec
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))
{
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
free(table_buf);
}
}
next:
fseek (ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
#else
void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer)
{
/*placeholder */
}
#endif
void CLASS parse_makernote (int base, int uptag)
{
unsigned offset=0, entries, tag, type, len, save, c;
unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0};
uchar buf97[324], ci, cj, ck;
short morder, sorder=order;
char buf[10];
unsigned SamsungKey[11];
uchar NikonKey;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned custom_serial = 0;
unsigned NikonLensDataVersion = 0;
unsigned lenNikonLensData = 0;
unsigned NikonFlashInfoVersion = 0;
uchar *CanonCameraInfo;
unsigned lenCanonCameraInfo = 0;
uchar *table_buf;
uchar *table_buf_0x9050;
ushort table_buf_0x9050_present = 0;
uchar *table_buf_0x940c;
ushort table_buf_0x940c_present = 0;
INT64 fsize = ifp->size();
#endif
/*
The MakerNote might have its own TIFF header (possibly with
its own byte-order!), or it might just be a table.
*/
if (!strncmp(make,"Nokia",5)) return;
fread (buf, 1, 10, ifp);
if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */
!strncmp (buf,"VER" ,3) ||
!strncmp (buf,"IIII",4) ||
!strncmp (buf,"MMMM",4)) return;
if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */
!strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */
order = 0x4d4d;
while ((i=ftell(ifp)) < data_offset && i < 16384) {
wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3];
wb[3] = get2();
if (wb[1] == 256 && wb[3] == 256 &&
wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640)
FORC4 cam_mul[c] = wb[c];
}
goto quit;
}
if (!strcmp (buf,"Nikon")) {
base = ftell(ifp);
order = get2();
if (get2() != 42) goto quit;
offset = get4();
fseek (ifp, offset-8, SEEK_CUR);
} else if (!strcmp (buf,"OLYMPUS") ||
!strcmp (buf,"PENTAX ")) {
base = ftell(ifp)-10;
fseek (ifp, -2, SEEK_CUR);
order = get2();
if (buf[0] == 'O') get2();
} else if (!strncmp (buf,"SONY",4) ||
!strcmp (buf,"Panasonic")) {
goto nf;
} else if (!strncmp (buf,"FUJIFILM",8)) {
base = ftell(ifp)-10;
nf: order = 0x4949;
fseek (ifp, 2, SEEK_CUR);
} else if (!strcmp (buf,"OLYMP") ||
!strcmp (buf,"LEICA") ||
!strcmp (buf,"Ricoh") ||
!strcmp (buf,"EPSON"))
fseek (ifp, -2, SEEK_CUR);
else if (!strcmp (buf,"AOC") ||
!strcmp (buf,"QVC"))
fseek (ifp, -4, SEEK_CUR);
else {
fseek (ifp, -10, SEEK_CUR);
if (!strncmp(make,"SAMSUNG",7))
base = ftell(ifp);
}
// adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400
if (!strncasecmp(make, "LEICA", 5))
{
if (!strncmp(model, "M8", 2) ||
!strncasecmp(model, "Leica M8", 8) ||
!strncasecmp(model, "LEICA X", 7))
{
base = ftell(ifp)-8;
}
else if (!strncasecmp(model, "LEICA M (Typ 240)", 17))
{
base = 0;
}
else if (!strncmp(model, "M9", 2) ||
!strncasecmp(model, "Leica M9", 8) ||
!strncasecmp(model, "M Monochrom", 11) ||
!strncasecmp(model, "Leica M Monochrom", 11))
{
if (!uptag)
{
base = ftell(ifp) - 10;
fseek (ifp, 8, SEEK_CUR);
}
else if (uptag == 0x3400)
{
fseek (ifp, 10, SEEK_CUR);
base += 10;
}
}
else if (!strncasecmp(model, "LEICA T", 7))
{
base = ftell(ifp)-8;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T;
#endif
}
#ifdef LIBRAW_LIBRARY_BUILD
else if (!strncasecmp(model, "LEICA SL", 8))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF;
}
#endif
}
entries = get2();
if (entries > 1000) return;
morder = order;
while (entries--) {
order = morder;
tiff_get (base, &tag, &type, &len, &save);
tag |= uptag << 16;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos = ftell(ifp);
if(len > 8 && _pos+len > 2* fsize) continue;
if (!strncmp(make, "Canon",5))
{
if (tag == 0x000d && len < 256000) // camera info
{
CanonCameraInfo = (uchar*)malloc(MAX(16,len));
fread(CanonCameraInfo, len, 1, ifp);
lenCanonCameraInfo = len;
}
else if (tag == 0x10) // Canon ModelID
{
unique_id = get4();
if (unique_id == 0x03740000) unique_id = 0x80000374; // M3
if (unique_id == 0x03840000) unique_id = 0x80000384; // M10
if (unique_id == 0x03940000) unique_id = 0x80000394; // M5
setCanonBodyFeatures(unique_id);
if (lenCanonCameraInfo)
{
processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo);
free(CanonCameraInfo);
CanonCameraInfo = 0;
lenCanonCameraInfo = 0;
}
}
else parseCanonMakernotes (tag, type, len);
}
else if (!strncmp(make, "FUJI", 4)) {
if (tag == 0x0010) {
char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
char yy[2], mm[3], dd[3], ystr[16], ynum[16];
int year, nwords, ynum_len;
unsigned c;
stmread(FujiSerial, len, ifp);
nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial));
for (int i = 0; i < nwords; i++) {
mm[2] = dd[2] = 0;
if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18)
if (i == 0)
strncpy (imgdata.shootinginfo.InternalBodySerial,
words[0],
sizeof(imgdata.shootinginfo.InternalBodySerial)-1);
else
{
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf (tbuf, sizeof(tbuf), "%s %s",
imgdata.shootinginfo.InternalBodySerial, words[i]);
strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial)-1);
}
else
{
strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2);
strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2);
strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2);
year = (yy[0]-'0')*10 + (yy[1]-'0');
if (year <70) year += 2000; else year += 1900;
ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18;
strncpy(ynum, words[i], ynum_len);
ynum[ynum_len] = 0;
for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c;
ystr[ynum_len / 2 + 1] = 0;
strcpy (model2, ystr);
if (i == 0) {
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
if (nwords == 1)
snprintf (tbuf,sizeof(tbuf),
"%s %s %d:%s:%s",
words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12,
ystr, year, mm, dd);
else
snprintf (tbuf,sizeof(tbuf),
"%s %d:%s:%s %s",
ystr, year, mm, dd,
words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12);
strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial)-1);
} else {
char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)];
snprintf (tbuf, sizeof(tbuf),
"%s %s %d:%s:%s %s",
imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd,
words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12);
strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf,
sizeof(imgdata.shootinginfo.InternalBodySerial)-1);
}
}
}
}
else
parseFujiMakernotes (tag, type);
}
else if (!strncasecmp(make, "LEICA", 5))
{
if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9))
{
int ind = tag == 0x035e?0:1;
for (int j=0; j < 3; j++)
FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type);
}
if ((tag == 0x0303) && (type != 4))
{
stmread(imgdata.lens.makernotes.Lens, len, ifp);
}
if ((tag == 0x3405) ||
(tag == 0x0310) ||
(tag == 0x34003405))
{
imgdata.lens.makernotes.LensID = get4();
imgdata.lens.makernotes.LensID =
((imgdata.lens.makernotes.LensID>>2)<<8) |
(imgdata.lens.makernotes.LensID & 0x3);
if (imgdata.lens.makernotes.LensID != -1)
{
if ((model[0] == 'M') ||
!strncasecmp (model, "LEICA M", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M;
}
else if ((model[0] == 'S') ||
!strncasecmp (model, "LEICA S", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S;
}
}
}
else if (
((tag == 0x0313) || (tag == 0x34003406)) &&
(fabs(imgdata.lens.makernotes.CurAp) < 0.17f) &&
((type == 10) || (type == 5))
)
{
imgdata.lens.makernotes.CurAp = getreal(type);
if (imgdata.lens.makernotes.CurAp > 126.3)
imgdata.lens.makernotes.CurAp = 0.0f;
}
else if (tag == 0x3400)
{
parse_makernote (base, 0x3400);
}
}
else if (!strncmp(make, "NIKON",5))
{
if (tag == 0x000a)
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
else if (tag == 0x0012)
{
char a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c;
}
else if (tag == 0x0082) // lens attachment
{
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
}
else if (tag == 0x0083) // lens type
{
imgdata.lens.nikon.NikonLensType = fgetc(ifp);
}
else if (tag == 0x0084) // lens
{
imgdata.lens.makernotes.MinFocal = getreal(type);
imgdata.lens.makernotes.MaxFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type);
imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type);
}
else if (tag == 0x008b) // lens f-stops
{
uchar a, b, c;
a = fgetc(ifp);
b = fgetc(ifp);
c = fgetc(ifp);
if (c)
{
imgdata.lens.nikon.NikonLensFStops = a*b*(12/c);
imgdata.lens.makernotes.LensFStops =
(float)imgdata.lens.nikon.NikonLensFStops /12.0f;
}
}
else if (tag == 0x0093)
{
i = get2();
if ((i == 7) || (i == 9))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0098) // contains lens data
{
for (i = 0; i < 4; i++)
{
NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0';
}
switch (NikonLensDataVersion)
{
case 100: lenNikonLensData = 9; break;
case 101:
case 201: // encrypted, starting from v.201
case 202:
case 203: lenNikonLensData = 15; break;
case 204: lenNikonLensData = 16; break;
case 400: lenNikonLensData = 459; break;
case 401: lenNikonLensData = 590; break;
case 402: lenNikonLensData = 509; break;
case 403: lenNikonLensData = 879; break;
}
if(lenNikonLensData>0)
{
table_buf = (uchar*)malloc(lenNikonLensData);
fread(table_buf, lenNikonLensData, 1, ifp);
if ((NikonLensDataVersion < 201) && lenNikonLensData)
{
processNikonLensData(table_buf, lenNikonLensData);
free(table_buf);
lenNikonLensData = 0;
}
}
}
else if (tag == 0x00a0)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x00a8) // contains flash data
{
for (i = 0; i < 4; i++)
{
NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0';
}
}
}
else if (!strncmp(make, "OLYMPUS", 7))
{
switch (tag) {
case 0x0404:
case 0x101a:
case 0x20100101:
if (!imgdata.shootinginfo.BodySerial[0])
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0x20100102:
if (!imgdata.shootinginfo.InternalBodySerial[0])
stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp);
break;
case 0x0207:
case 0x20100100:
{
uchar sOlyID[8];
unsigned long long OlyID;
fread (sOlyID, MIN(len,7), 1, ifp);
sOlyID[7] = 0;
OlyID = sOlyID[0];
i = 1;
while (i < 7 && sOlyID[i])
{
OlyID = OlyID << 8 | sOlyID[i];
i++;
}
setOlympusBodyFeatures(OlyID);
}
break;
case 0x1002:
imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2);
break;
case 0x20401112:
imgdata.makernotes.olympus.OlympusCropID = get2();
break;
case 0x20401113:
FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2();
break;
case 0x20100201:
{
unsigned long long oly_lensid [3];
oly_lensid[0] = fgetc(ifp);
fgetc(ifp);
oly_lensid[1] = fgetc(ifp);
oly_lensid[2] = fgetc(ifp);
imgdata.lens.makernotes.LensID =
(oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2];
}
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT;
imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT;
if (((imgdata.lens.makernotes.LensID < 0x20000) ||
(imgdata.lens.makernotes.LensID > 0x4ffff)) &&
(imgdata.lens.makernotes.LensID & 0x10))
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT;
}
break;
case 0x20100202:
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0x20100203:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x20100205:
imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100206:
imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100207:
imgdata.lens.makernotes.MinFocal = (float)get2();
break;
case 0x20100208:
imgdata.lens.makernotes.MaxFocal = (float)get2();
if (imgdata.lens.makernotes.MaxFocal > 1000.0f)
imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal;
break;
case 0x2010020a:
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f);
break;
case 0x20100301:
imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8;
fgetc(ifp);
imgdata.lens.makernotes.TeleconverterID =
imgdata.lens.makernotes.TeleconverterID | fgetc(ifp);
break;
case 0x20100303:
stmread(imgdata.lens.makernotes.Teleconverter, len, ifp);
break;
case 0x20100403:
stmread(imgdata.lens.makernotes.Attachment, len, ifp);
break;
}
}
else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) &&
!strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
char buffer[17];
int count=0;
fread(buffer, 16, 1, ifp);
buffer[16] = 0;
for (int i=0; i<16; i++)
{
// sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]);
if ((isspace(buffer[i])) ||
(buffer[i] == 0x2D) ||
(isalnum(buffer[i])))
count++;
}
if (count == 16)
{
sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8);
buffer[8] = 0;
sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else
{
sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]);
sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]);
}
}
else if ((tag == 0x1001) && (type == 3))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
imgdata.lens.makernotes.FocalType = 1;
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
}
else if (!strncmp(make, "RICOH", 5) &&
strncmp(model, "PENTAX", 6))
{
if ((tag == 0x0005) && !strncmp(model, "GXR", 3))
{
char buffer[9];
buffer[8] = 0;
fread(buffer, 8, 1, ifp);
sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer);
}
else if ((tag == 0x100b) && (type == 10))
{
imgdata.other.FlashEC = getreal(type);
}
else if ((tag == 0x1017) && (get2() == 2))
{
strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter");
}
else if (tag == 0x1500)
{
imgdata.lens.makernotes.CurFocal = getreal(type);
}
else if ((tag == 0x2001) && !strncmp(model, "GXR", 3))
{
short ntags, cur_tag;
fseek(ifp, 20, SEEK_CUR);
ntags = get2();
cur_tag = get2();
while (cur_tag != 0x002c)
{
fseek(ifp, 10, SEEK_CUR);
cur_tag = get2();
}
fseek(ifp, 6, SEEK_CUR);
fseek(ifp, get4()+20, SEEK_SET);
stread(imgdata.shootinginfo.BodySerial, 12, ifp);
get2();
imgdata.lens.makernotes.LensID = getc(ifp) - '0';
switch(imgdata.lens.makernotes.LensID) {
case 1:
case 2:
case 3:
case 5:
case 6:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule;
break;
case 8:
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M;
imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC;
imgdata.lens.makernotes.LensID = -1;
break;
default:
imgdata.lens.makernotes.LensID = -1;
}
fseek(ifp, 17, SEEK_CUR);
stread(imgdata.lens.LensSerial, 12, ifp);
}
}
else if ((!strncmp(make, "PENTAX", 6) ||
!strncmp(model, "PENTAX", 6) ||
(!strncmp(make, "SAMSUNG", 7) && dng_version)) &&
strncmp(model, "GR", 2))
{
if (tag == 0x0005)
{
unique_id = get4();
setPentaxBodyFeatures(unique_id);
}
else if (tag == 0x0013)
{
imgdata.lens.makernotes.CurAp = (float)get2()/10.0f;
}
else if (tag == 0x0014)
{
PentaxISO(get2());
}
else if (tag == 0x001d)
{
imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f;
}
else if (tag == 0x003f)
{
imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp);
}
else if (tag == 0x004d)
{
if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f;
else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f;
}
else if (tag == 0x007e)
{
imgdata.color.linear_max[0] =
imgdata.color.linear_max[1] =
imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = (long)(-1) * get4();
}
else if (tag == 0x0207)
{
if(len < 65535) // Safety belt
PentaxLensInfo(imgdata.lens.makernotes.CamID, len);
}
else if (tag == 0x020d)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
}
else if (tag == 0x020e)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
}
else if (tag == 0x020f)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0210)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0211)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0212)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0213)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0214)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0221)
{
int nWB = get2();
if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0]))
for (int i = 0; i < nWB; i++)
{
imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2();
fseek(ifp, 2, SEEK_CUR);
imgdata.color.WBCT_Coeffs[i][1] = get2();
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000;
imgdata.color.WBCT_Coeffs[i][3] = get2();
}
}
else if (tag == 0x0215)
{
fseek (ifp, 16, SEEK_CUR);
sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4());
}
else if (tag == 0x0229)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0x022d)
{
fseek (ifp,2,SEEK_CUR);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2();
getc(ifp);
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2();
}
else if (tag == 0x0239) // Q-series lens info (LensInfoQ)
{
char LensInfo [20];
fseek (ifp, 2, SEEK_CUR);
stread(imgdata.lens.makernotes.Lens, 30, ifp);
strcat(imgdata.lens.makernotes.Lens, " ");
stread(LensInfo, 20, ifp);
strcat(imgdata.lens.makernotes.Lens, LensInfo);
}
}
else if (!strncmp(make, "SAMSUNG", 7))
{
if (tag == 0x0002)
{
if(get4() == 0x2000)
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (!strncmp(model, "NX mini", 7))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M;
}
else
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
}
else if (tag == 0x0003)
{
unique_id = imgdata.lens.makernotes.CamID = get4();
}
else if (tag == 0xa002)
{
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
}
else if (tag == 0xa003)
{
imgdata.lens.makernotes.LensID = get2();
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX;
}
else if (tag == 0xa005)
{
stmread(imgdata.lens.InternalLensSerial, len, ifp);
}
else if (tag == 0xa019)
{
imgdata.lens.makernotes.CurAp = getreal(type);
}
else if (tag == 0xa01a)
{
imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f;
if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f)
imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f;
}
}
else if (!strncasecmp(make, "SONY", 4) ||
!strncasecmp(make, "Konica", 6) ||
!strncasecmp(make, "Minolta", 7) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "Lusso", 5) ||
!strncasecmp(model, "HV",2))))
{
ushort lid;
if (tag == 0xb001) // Sony ModelID
{
unique_id = get2();
setSonyBodyFeatures(unique_id);
if (table_buf_0x9050_present)
{
process_Sony_0x9050(table_buf_0x9050, unique_id);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
if (table_buf_0x940c_present)
{
if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)
{
process_Sony_0x940c(table_buf_0x940c);
}
free (table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if ((tag == 0x0010) && // CameraInfo
strncasecmp(model, "DSLR-A100", 9) &&
strncasecmp(model, "NEX-5C", 6) &&
!strncasecmp(make, "SONY", 4) &&
((len == 368) || // a700
(len == 5478) || // a850, a900
(len == 5506) || // a200, a300, a350
(len == 6118) || // a230, a290, a330, a380, a390
// a450, a500, a550, a560, a580
// a33, a35, a55
// NEX3, NEX5, NEX5C, NEXC3, VG10E
(len == 15360))
)
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) &&
memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8))
{
switch (len)
{
case 368:
case 5478:
// a700, a850, a900: CameraInfo
if (table_buf[0] | table_buf[3])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]);
if (table_buf[2] | table_buf[5])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]);
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f;
if (table_buf[4])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f;
parseSonyLensFeatures(table_buf[1], table_buf[6]);
break;
default:
// CameraInfo2 & 3
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
}
}
free(table_buf);
}
else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing
!strncasecmp(model, "DSLR-A100", 9))
{
fseek(ifp,0x49dc,SEEK_CUR);
stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp);
}
else if (tag == 0x0104)
{
imgdata.other.FlashEC = getreal(type);
}
else if (tag == 0x0105) // Teleconverter
{
imgdata.lens.makernotes.TeleconverterID = get2();
}
else if (tag == 0x0114 && len < 256000) // CameraSettings
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
switch (len) {
case 280:
case 364:
case 332:
// CameraSettings and CameraSettings2 are big endian
if (table_buf[2] | table_buf[3])
{
lid = (((ushort)table_buf[2])<<8) |
((ushort)table_buf[3]);
imgdata.lens.makernotes.CurAp =
powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f);
}
break;
case 1536:
case 2048:
// CameraSettings3 are little endian
parseSonyLensType2(table_buf[1016], table_buf[1015]);
if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF)
{
switch (table_buf[153]) {
case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break;
case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break;
}
}
break;
}
free(table_buf);
}
else if (tag == 0x9050 && len < 256000) // little endian
{
table_buf_0x9050 = (uchar*)malloc(len);
table_buf_0x9050_present = 1;
fread(table_buf_0x9050, len, 1, ifp);
if (imgdata.lens.makernotes.CamID)
{
process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID);
free (table_buf_0x9050);
table_buf_0x9050_present = 0;
}
}
else if (tag == 0x940c && len <256000)
{
table_buf_0x940c = (uchar*)malloc(len);
table_buf_0x940c_present = 1;
fread(table_buf_0x940c, len, 1, ifp);
if ((imgdata.lens.makernotes.CamID) &&
(imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E))
{
process_Sony_0x940c(table_buf_0x940c);
free(table_buf_0x940c);
table_buf_0x940c_present = 0;
}
}
else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1))
{
imgdata.lens.makernotes.LensID = get4();
if ((imgdata.lens.makernotes.LensID > 0x4900) &&
(imgdata.lens.makernotes.LensID <= 0x5900))
{
imgdata.lens.makernotes.AdapterID = 0x4900;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F;
strcpy(imgdata.lens.makernotes.Adapter, "MC-11");
}
else if ((imgdata.lens.makernotes.LensID > 0xEF00) &&
(imgdata.lens.makernotes.LensID < 0xFFFF) &&
(imgdata.lens.makernotes.LensID != 0xFF00))
{
imgdata.lens.makernotes.AdapterID = 0xEF00;
imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF;
}
if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A;
}
else if (tag == 0xb02a && len < 256000) // Sony LensSpec
{
table_buf = (uchar*)malloc(len);
fread(table_buf, len, 1, ifp);
if (table_buf[1] | table_buf[2])
imgdata.lens.makernotes.MinFocal =
bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]);
if (table_buf[3] | table_buf[4])
imgdata.lens.makernotes.MaxFocal =
bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]);
if (table_buf[5])
imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f;
if (table_buf[6])
imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f;
parseSonyLensFeatures(table_buf[0], table_buf[7]);
free(table_buf);
}
}
fseek(ifp,_pos,SEEK_SET);
#endif
if (tag == 2 && strstr(make,"NIKON") && !iso_speed)
iso_speed = (get2(),get2());
if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535))
{
unsigned char cc;
fread(&cc,1,1,ifp);
iso_speed = int(100.0 * powf64(2.0f,float(cc)/12.0-5.0));
}
if (tag == 4 && len > 26 && len < 35) {
if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535))
iso_speed = 50 * powf64(2.0, i/32.0 - 4);
#ifdef LIBRAW_LIBRARY_BUILD
get4();
#else
if ((i=(get2(),get2())) != 0x7fff && !aperture)
aperture = powf64(2.0, i/64.0);
#endif
if ((i=get2()) != 0xffff && !shutter)
shutter = powf64(2.0, (short) i/-32.0);
wbi = (get2(),get2());
shot_order = (get2(),get2());
}
if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) {
fseek (ifp, tag == 4 ? 140:160, SEEK_CUR);
switch (get2()) {
case 72: flip = 0; break;
case 76: flip = 6; break;
case 82: flip = 5; break;
}
}
if (tag == 7 && type == 2 && len > 20)
fgets (model2, 64, ifp);
if (tag == 8 && type == 4)
shot_order = get4();
if (tag == 9 && !strncmp(make,"Canon",5))
fread (artist, 64, 1, ifp);
if (tag == 0xc && len == 4)
FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type);
if (tag == 0xd && type == 7 && get2() == 0xaaaa) {
for (c=i=2; (ushort) c != 0xbbbb && i < len; i++)
c = c << 8 | fgetc(ifp);
while ((i+=4) < len-5)
if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3)
flip = "065"[c]-'0';
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x10 && type == 4) unique_id = get4();
#endif
#ifdef LIBRAW_LIBRARY_BUILD
INT64 _pos2 = ftell(ifp);
if (!strncasecmp(make,"Olympus",7))
{
short nWB, tWB;
if ((tag == 0x20300108) || (tag == 0x20310109))
imgdata.makernotes.olympus.ColorSpace = get2();
if ((tag == 0x20400102) && (len == 2) &&
(!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5)))
{
int i;
for (i=0; i<64; i++)
imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] =
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
for (i=64; i<256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
if ((tag >= 0x20400102) && (tag <= 0x2040010d))
{
ushort CT;
nWB = tag-0x20400102;
switch (nWB)
{
case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break;
case 1 : CT = 3300; tWB = 0x100; break;
case 2 : CT = 3600; tWB = 0x100; break;
case 3 : CT = 3900; tWB = 0x100; break;
case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break;
case 5 : CT = 4300; tWB = 0x100; break;
case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break;
case 7 : CT = 4800; tWB = 0x100; break;
case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break;
case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break;
case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break;
case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break;
default: CT = 0; tWB = 0x100;
}
if (CT)
{
imgdata.color.WBCT_Coeffs[nWB][0] = CT;
imgdata.color.WBCT_Coeffs[nWB][1] = get2();
imgdata.color.WBCT_Coeffs[nWB][3] = get2();
if (len == 4)
{
imgdata.color.WBCT_Coeffs[nWB][2] = get2();
imgdata.color.WBCT_Coeffs[nWB][4] = get2();
}
}
if (tWB != 0x100)
FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1];
}
if ((tag >= 0x20400113) && (tag <= 0x2040011e))
{
nWB = tag-0x20400113;
imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2();
switch (nWB)
{
case 0: tWB = LIBRAW_WBI_Tungsten; break;
case 4: tWB = LIBRAW_WBI_FL_W; break;
case 6: tWB = LIBRAW_WBI_FL_D; break;
case 8: tWB = LIBRAW_WBI_FineWeather; break;
case 9: tWB = LIBRAW_WBI_Cloudy; break;
case 10: tWB = LIBRAW_WBI_FL_N; break;
case 11: tWB = LIBRAW_WBI_Shade; break;
default: tWB = 0x100;
}
if (tWB != 0x100)
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] =
imgdata.color.WBCT_Coeffs[nWB][2];
}
if (tag == 0x20400121)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
if (len == 4)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2();
}
}
if (tag == 0x2040011f)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2();
}
if (tag == 0x30000120)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
if (len == 2)
{
for (int i=0; i<256; i++)
imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100;
}
}
if (tag == 0x30000121)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
}
if (tag == 0x30000122)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2();
}
if (tag == 0x30000123)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
}
if (tag == 0x30000124)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2();
}
if (tag == 0x30000130)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
}
if (tag == 0x30000131)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
}
if (tag == 0x30000132)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
}
if (tag == 0x30000133)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
}
if((tag == 0x20400805) && (len == 2))
{
imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type);
imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type);
FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0];
}
if (tag == 0x20200401)
{
imgdata.other.FlashEC = getreal(type);
}
}
fseek(ifp,_pos2,SEEK_SET);
#endif
if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) {
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
}
if (tag == 0x14 && type == 7) {
if (len == 2560) {
fseek (ifp, 1248, SEEK_CUR);
goto get2_256;
}
fread (buf, 1, 10, ifp);
if (!strncmp(buf,"NRW ",4)) {
fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR);
cam_mul[0] = get4() << 2;
cam_mul[1] = get4() + get4();
cam_mul[2] = get4() << 2;
}
}
if (tag == 0x15 && type == 2 && is_raw)
fread (model, 64, 1, ifp);
if (strstr(make,"PENTAX")) {
if (tag == 0x1b) tag = 0x1018;
if (tag == 0x1c) tag = 0x1017;
}
if (tag == 0x1d) {
while ((c = fgetc(ifp)) && c != EOF)
#ifdef LIBRAW_LIBRARY_BUILD
{
if ((!custom_serial) && (!isdigit(c)))
{
if ((strbuflen(model) == 3) && (!strcmp(model,"D50")))
{
custom_serial = 34;
}
else
{
custom_serial = 96;
}
}
#endif
serial = serial*10 + (isdigit(c) ? c - '0' : c % 10);
#ifdef LIBRAW_LIBRARY_BUILD
}
if (!imgdata.shootinginfo.BodySerial[0])
sprintf(imgdata.shootinginfo.BodySerial, "%d", serial);
#endif
}
if (tag == 0x29 && type == 1) { // Canon PowerShot G9
c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0;
fseek (ifp, 8 + c*32, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4();
}
#ifndef LIBRAW_LIBRARY_BUILD
if (tag == 0x3d && type == 3 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps);
#endif
if (tag == 0x81 && type == 4) {
data_offset = get4();
fseek (ifp, data_offset + 41, SEEK_SET);
raw_height = get2() * 2;
raw_width = get2();
filters = 0x61616161;
}
if ((tag == 0x81 && type == 7) ||
(tag == 0x100 && type == 7) ||
(tag == 0x280 && type == 1)) {
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (tag == 0x88 && type == 4 && (thumb_offset = get4()))
thumb_offset += base;
if (tag == 0x89 && type == 4)
thumb_length = get4();
if (tag == 0x8c || tag == 0x96)
meta_offset = ftell(ifp);
if (tag == 0x97) {
for (i=0; i < 4; i++)
ver97 = ver97 * 10 + fgetc(ifp)-'0';
switch (ver97) {
case 100:
fseek (ifp, 68, SEEK_CUR);
FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2();
break;
case 102:
fseek (ifp, 6, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
break;
case 103:
fseek (ifp, 16, SEEK_CUR);
FORC4 cam_mul[c] = get2();
}
if (ver97 >= 200) {
if (ver97 != 205) fseek (ifp, 280, SEEK_CUR);
fread (buf97, 324, 1, ifp);
}
}
if (tag == 0xa1 && type == 7) {
order = 0x4949;
fseek (ifp, 140, SEEK_CUR);
FORC3 cam_mul[c] = get4();
}
if (tag == 0xa4 && type == 3) {
fseek (ifp, wbi*48, SEEK_CUR);
FORC3 cam_mul[c] = get2();
}
if (tag == 0xa7) { // shutter count
NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp);
if ( (unsigned) (ver97-200) < 17) {
ci = xlat[0][serial & 0xff];
cj = xlat[1][NikonKey];
ck = 0x60;
for (i=0; i < 324; i++)
buf97[i] ^= (cj += ci * ck++);
i = "66666>666;6A;:;55"[ver97-200] - '0';
FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] =
sget2 (buf97 + (i & -2) + c*2);
}
#ifdef LIBRAW_LIBRARY_BUILD
if ((NikonLensDataVersion > 200) && lenNikonLensData)
{
if (custom_serial)
{
ci = xlat[0][custom_serial];
}
else
{
ci = xlat[0][serial & 0xff];
}
cj = xlat[1][NikonKey];
ck = 0x60;
for (i = 0; i < lenNikonLensData; i++)
table_buf[i] ^= (cj += ci * ck++);
processNikonLensData(table_buf, lenNikonLensData);
lenNikonLensData = 0;
free(table_buf);
}
if (ver97 == 601) // Coolpix A
{
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
}
#endif
}
if(tag == 0xb001 && type == 3) // Sony ModelID
{
unique_id = get2();
}
if (tag == 0x200 && len == 3)
shot_order = (get4(),get4());
if (tag == 0x200 && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x201 && len == 4)
FORC4 cam_mul[c ^ (c >> 1)] = get2();
if (tag == 0x220 && type == 7)
meta_offset = ftell(ifp);
if (tag == 0x401 && type == 4 && len == 4)
FORC4 cblack[c ^ c >> 1] = get4();
#ifdef LIBRAW_LIBRARY_BUILD
// not corrected for file bitcount, to be patched in open_datastream
if (tag == 0x03d && strstr(make,"NIKON") && len == 4)
{
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if(i>cblack[c]) i = cblack[c];
FORC4 cblack[c]-=i;
black += i;
}
#endif
if (tag == 0xe01) { /* Nikon Capture Note */
#ifdef LIBRAW_LIBRARY_BUILD
int loopc = 0;
#endif
order = 0x4949;
fseek (ifp, 22, SEEK_CUR);
for (offset=22; offset+22 < len; offset += 22+i) {
#ifdef LIBRAW_LIBRARY_BUILD
if(loopc++>1024)
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
tag = get4();
fseek (ifp, 14, SEEK_CUR);
i = get4()-4;
if (tag == 0x76a43207) flip = get2();
else fseek (ifp, i, SEEK_CUR);
}
}
if (tag == 0xe80 && len == 256 && type == 7) {
fseek (ifp, 48, SEEK_CUR);
cam_mul[0] = get2() * 508 * 1.078 / 0x10000;
cam_mul[2] = get2() * 382 * 1.173 / 0x10000;
}
if (tag == 0xf00 && type == 7) {
if (len == 614)
fseek (ifp, 176, SEEK_CUR);
else if (len == 734 || len == 1502)
fseek (ifp, 148, SEEK_CUR);
else goto next;
goto get2_256;
}
if ((tag == 0x1011 && len == 9) || tag == 0x20400200)
for (i=0; i < 3; i++)
{
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.makernotes.olympus.ColorSpace)
{
FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
}
else
{
FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0;
}
#else
FORC3 cmatrix[i][c] = ((short) get2()) / 256.0;
#endif
}
if ((tag == 0x1012 || tag == 0x20400600) && len == 4)
FORC4 cblack[c ^ c >> 1] = get2();
if (tag == 0x1017 || tag == 0x20400100)
cam_mul[0] = get2() / 256.0;
if (tag == 0x1018 || tag == 0x20400100)
cam_mul[2] = get2() / 256.0;
if (tag == 0x2011 && len == 2) {
get2_256:
order = 0x4d4d;
cam_mul[0] = get2() / 256.0;
cam_mul[2] = get2() / 256.0;
}
if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13))
fseek (ifp, get4()+base, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
if (tag == 0x2010)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, 0x2010);
fseek(ifp,_pos3,SEEK_SET);
}
if (
((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) &&
((type == 7) || (type == 13)) &&
!strncasecmp(make,"Olympus",7)
)
{
INT64 _pos3 = ftell(ifp);
parse_makernote(base, tag);
fseek(ifp,_pos3,SEEK_SET);
}
// IB end
#endif
if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5))
parse_thumb_note (base, 257, 258);
if (tag == 0x2040)
parse_makernote (base, 0x2040);
if (tag == 0xb028) {
fseek (ifp, get4()+base, SEEK_SET);
parse_thumb_note (base, 136, 137);
}
if (tag == 0x4001 && len > 500 && len < 100000) {
i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126;
fseek (ifp, i, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
for (i+=18; i <= len; i+=10) {
get2();
FORC4 sraw_mul[c ^ (c >> 1)] = get2();
if (sraw_mul[1] == 1170) break;
}
}
if(!strncasecmp(make,"Samsung",7))
{
if (tag == 0xa020) // get the full Samsung encryption key
for (i=0; i<11; i++) SamsungKey[i] = get4();
if (tag == 0xa021) // get and decode Samsung cam_mul array
FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c];
#ifdef LIBRAW_LIBRARY_BUILD
if (tag == 0xa023)
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4;
}
}
if (tag == 0xa024)
{
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1];
if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1))
{
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4;
imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4;
}
}
if (tag == 0xa025)
imgdata.color.linear_max[0]=
imgdata.color.linear_max[1]=
imgdata.color.linear_max[2]=
imgdata.color.linear_max[3]= get4() - SamsungKey[0];
if (tag == 0xa030 && len == 9)
for (i=0; i < 3; i++)
FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0;
#endif
if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix
for (i=0; i < 3; i++)
FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0;
if (tag == 0xa028)
FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c];
}
else
{
// Somebody else use 0xa021 and 0xa028?
if (tag == 0xa021)
FORC4 cam_mul[c ^ (c >> 1)] = get4();
if (tag == 0xa028)
FORC4 cam_mul[c ^ (c >> 1)] -= get4();
}
if (tag == 0x4021 && get4() && get4())
FORC4 cam_mul[c] = 1024;
next:
fseek (ifp, save, SEEK_SET);
}
quit:
order = sorder;
}
/*
Since the TIFF DateTime string has no timezone information,
assume that the camera's clock was set to Universal Time.
*/
void CLASS get_timestamp (int reversed)
{
struct tm t;
char str[20];
int i;
str[19] = 0;
if (reversed)
for (i=19; i--; ) str[i] = fgetc(ifp);
else
fread (str, 19, 1, ifp);
memset (&t, 0, sizeof t);
if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon,
&t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6)
return;
t.tm_year -= 1900;
t.tm_mon -= 1;
t.tm_isdst = -1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
void CLASS parse_exif (int base)
{
unsigned kodak, entries, tag, type, len, save, c;
double expo,ape;
kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3;
entries = get2();
if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if(len > 8 && savepos + len > fsize*2) continue;
if(callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
#endif
switch (tag) {
#ifdef LIBRAW_LIBRARY_BUILD
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.dng.MinFocal = getreal(type);
imgdata.lens.dng.MaxFocal = getreal(type);
imgdata.lens.dng.MaxAp4MinFocal = getreal(type);
imgdata.lens.dng.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
#endif
case 33434: tiff_ifd[tiff_nifds-1].t_shutter =
shutter = getreal(type); break;
case 33437: aperture = getreal(type); break; // 0x829d FNumber
case 34855: iso_speed = get2(); break;
case 34866:
if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5)))
iso_speed = getreal(type);
break;
case 36867:
case 36868: get_timestamp(0); break;
case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.)
tiff_ifd[tiff_nifds-1].t_shutter =
shutter = powf64(2.0, expo);
break;
case 37378: // 0x9202 ApertureValue
if ((fabs(ape = getreal(type))<256.0) && (!aperture))
aperture = powf64(2.0, ape/2);
break;
case 37385: flash_used = getreal(type); break;
case 37386: focal_len = getreal(type); break;
case 37500: // tag 0x927c
#ifdef LIBRAW_LIBRARY_BUILD
if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) ||
((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) ||
((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) {
char mn_text[512];
char* pos;
char ccms[512];
ushort l;
float num;
fgets(mn_text, len, ifp);
pos = strstr(mn_text, "gain_r=");
if (pos) cam_mul[0] = atof(pos+7);
pos = strstr(mn_text, "gain_b=");
if (pos) cam_mul[2] = atof(pos+7);
if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f;
else cam_mul[0] = cam_mul[2] = 0.0f;
pos = strstr(mn_text, "ccm=") + 4;
l = strstr(pos, " ") - pos;
memcpy (ccms, pos, l);
ccms[l] = '\0';
pos = strtok (ccms, ",");
for (l=0; l<4; l++) {
num = 0.0;
for (c=0; c<3; c++) {
imgdata.color.ccm[l][c] = (float)atoi(pos);
num += imgdata.color.ccm[l][c];
pos = strtok (NULL, ",");
}
if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num;
}
}
else
#endif
parse_makernote (base, 0);
break;
case 40962: if (kodak) raw_width = get4(); break;
case 40963: if (kodak) raw_height = get4(); break;
case 41730:
if (get4() == 0x20002)
for (exif_cfa=c=0; c < 8; c+=2)
exif_cfa |= fgetc(ifp) * 0x01010101 << c;
}
fseek (ifp, save, SEEK_SET);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS parse_gps_libraw(int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
if (entries > 200)
return;
if (entries > 0)
imgdata.other.parsed_gps.gpsparsed = 1;
while (entries--) {
tiff_get(base, &tag, &type, &len, &save);
if(len > 1024) continue; // no GPS tags are 1k or larger
switch (tag) {
case 1: imgdata.other.parsed_gps.latref = getc(ifp); break;
case 3: imgdata.other.parsed_gps.longref = getc(ifp); break;
case 5: imgdata.other.parsed_gps.altref = getc(ifp); break;
case 2:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type);
break;
case 4:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type);
break;
case 7:
if (len == 3)
FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type);
break;
case 6:
imgdata.other.parsed_gps.altitude = getreal(type);
break;
case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break;
}
fseek(ifp, save, SEEK_SET);
}
}
#endif
void CLASS parse_gps (int base)
{
unsigned entries, tag, type, len, save, c;
entries = get2();
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
if(len > 1024) continue; // no GPS tags are 1k or larger
switch (tag) {
case 1: case 3: case 5:
gpsdata[29+tag/2] = getc(ifp); break;
case 2: case 4: case 7:
FORC(6) gpsdata[tag/3*6+c] = get4(); break;
case 6:
FORC(2) gpsdata[18+c] = get4(); break;
case 18: case 29:
fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp);
}
fseek (ifp, save, SEEK_SET);
}
}
void CLASS romm_coeff (float romm_cam[3][3])
{
static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */
{ { 2.034193, -0.727420, -0.306766 },
{ -0.228811, 1.231729, -0.002922 },
{ -0.008565, -0.153273, 1.161839 } };
int i, j, k;
for (i=0; i < 3; i++)
for (j=0; j < 3; j++)
for (cmatrix[i][j] = k=0; k < 3; k++)
cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j];
}
void CLASS parse_mos (int offset)
{
char data[40];
int skip, from, i, c, neut[4], planes=0, frot=0;
static const char *mod[] =
{ "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22",
"Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65",
"Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7",
"AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5",
"","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" };
float romm_cam[3][3];
fseek (ifp, offset, SEEK_SET);
while (1) {
if (get4() != 0x504b5453) break;
get4();
fread (data, 1, 40, ifp);
skip = get4();
from = ftell(ifp);
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp(data,"CameraObj_camera_type")) {
stmread(imgdata.lens.makernotes.body, skip, ifp);
}
if (!strcmp(data,"back_serial_number")) {
char buffer [sizeof(imgdata.shootinginfo.BodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial));
strcpy (imgdata.shootinginfo.BodySerial, words[0]);
}
if (!strcmp(data,"CaptProf_serial_number")) {
char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)];
char *words[4];
int nwords;
stmread(buffer, skip, ifp);
nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial));
strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]);
}
#endif
// IB end
if (!strcmp(data,"JPEG_preview_data")) {
thumb_offset = from;
thumb_length = skip;
}
if (!strcmp(data,"icc_camera_profile")) {
profile_offset = from;
profile_length = skip;
}
if (!strcmp(data,"ShootObj_back_type")) {
fscanf (ifp, "%d", &i);
if ((unsigned) i < sizeof mod / sizeof (*mod))
strcpy (model, mod[i]);
}
if (!strcmp(data,"icc_camera_to_tone_matrix")) {
for (i=0; i < 9; i++)
((float *)romm_cam)[i] = int_to_float(get4());
romm_coeff (romm_cam);
}
if (!strcmp(data,"CaptProf_color_matrix")) {
for (i=0; i < 9; i++)
fscanf (ifp, "%f", (float *)romm_cam + i);
romm_coeff (romm_cam);
}
if (!strcmp(data,"CaptProf_number_of_planes"))
fscanf (ifp, "%d", &planes);
if (!strcmp(data,"CaptProf_raw_data_rotation"))
fscanf (ifp, "%d", &flip);
if (!strcmp(data,"CaptProf_mosaic_pattern"))
FORC4 {
fscanf (ifp, "%d", &i);
if (i == 1) frot = c ^ (c >> 1);
}
if (!strcmp(data,"ImgProf_rotation_angle")) {
fscanf (ifp, "%d", &i);
flip = i - flip;
}
if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) {
FORC4 fscanf (ifp, "%d", neut+c);
FORC3 cam_mul[c] = (float) neut[0] / neut[c+1];
}
if (!strcmp(data,"Rows_data"))
load_flags = get4();
parse_mos (from);
fseek (ifp, skip+from, SEEK_SET);
}
if (planes)
filters = (planes == 1) * 0x01010101 *
(uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3];
}
void CLASS linear_table (unsigned len)
{
int i;
if (len > 0x10000) len = 0x10000;
read_shorts (curve, len);
for (i=len; i < 0x10000; i++)
curve[i] = curve[i-1];
maximum = curve[len<0x1000?0xfff:len-1];
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS Kodak_WB_0x08tags (int wb, unsigned type)
{
float mul[3]={1,1,1}, num, mul2;
int c;
FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num;
imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1];
mul2 = mul[1] * mul[1];
imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0];
imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2];
return;
}
/* Thanks to Alexey Danilchenko for wb as-shot parsing code */
void CLASS parse_kodak_ifd (int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi=-2;
float mul[3]={1,1,1}, num;
static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
entries = get2();
if (entries > 1024) return;
INT64 fsize = ifp->size();
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
INT64 savepos = ftell(ifp);
if(len > 8 && len + savepos > 2*fsize) continue;
if(callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
if (tag == 1011) imgdata.other.FlashEC = getreal(type);
if (tag == 1020) wbi = getint(type);
if (tag == 1021 && len == 72) { /* WB set in software */
fseek (ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2());
wbi = -2;
}
if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type);
if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type);
if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type);
if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type);
if (tag == 0x0e93) imgdata.color.linear_max[0] =
imgdata.color.linear_max[1] =
imgdata.color.linear_max[2] =
imgdata.color.linear_max[3] = get2();
if (tag == 0x09ce)
stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp);
if (tag == 0xfa00)
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if (tag == 0xfa27)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
}
if (tag == 0xfa28)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
}
if (tag == 0xfa29)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
}
if (tag == 0xfa2a)
{
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
}
if (tag == 2120 + wbi ||
(wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */
{
FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num;
FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */
}
if (tag == 2317) linear_table (len);
if (tag == 0x903) iso_speed = getreal(type);
//if (tag == 6020) iso_speed = getint(type);
if (tag == 64013) wbi = fgetc(ifp);
if ((unsigned) wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019) width = getint(type);
if (tag == 64020) height = (getint(type)+1) & -2;
fseek (ifp, save, SEEK_SET);
}
}
#else
void CLASS parse_kodak_ifd (int base)
{
unsigned entries, tag, type, len, save;
int i, c, wbi=-2, wbtemp=6500;
float mul[3]={1,1,1}, num;
static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 };
entries = get2();
if (entries > 1024) return;
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
if (tag == 1020) wbi = getint(type);
if (tag == 1021 && len == 72) { /* WB set in software */
fseek (ifp, 40, SEEK_CUR);
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2());
wbi = -2;
}
if (tag == 2118) wbtemp = getint(type);
if (tag == 2120 + wbi && wbi >= 0)
FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type));
if (tag == 2130 + wbi)
FORC3 mul[c] = getreal(type);
if (tag == 2140 + wbi && wbi >= 0)
FORC3 {
for (num=i=0; i < 4; i++)
num += getreal(type) * pow (wbtemp/100.0, i);
cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c]));
}
if (tag == 2317) linear_table (len);
if (tag == 6020) iso_speed = getint(type);
if (tag == 64013) wbi = fgetc(ifp);
if ((unsigned) wbi < 7 && tag == wbtag[wbi])
FORC3 cam_mul[c] = get4();
if (tag == 64019) width = getint(type);
if (tag == 64020) height = (getint(type)+1) & -2;
fseek (ifp, save, SEEK_SET);
}
}
#endif
//@end COMMON
void CLASS parse_minolta (int base);
int CLASS parse_tiff (int base);
//@out COMMON
int CLASS parse_tiff_ifd (int base)
{
unsigned entries, tag, type, len, plen=16, save;
int ifd, use_cm=0, cfa, i, j, c, ima_len=0;
char *cbuf, *cp;
uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256];
double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num;
double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 };
unsigned sony_curve[] = { 0,0,0,0,0,4095 };
unsigned *buf, sony_offset=0, sony_length=0, sony_key=0;
struct jhead jh;
int pana_raw = 0;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *sfp;
#endif
if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0])
return 1;
ifd = tiff_nifds++;
for (j=0; j < 4; j++)
for (i=0; i < 4; i++)
cc[j][i] = i == j;
entries = get2();
if (entries > 512) return 1;
#ifdef LIBRAW_LIBRARY_BUILD
INT64 fsize = ifp->size();
#endif
while (entries--) {
tiff_get (base, &tag, &type, &len, &save);
#ifdef LIBRAW_LIBRARY_BUILD
INT64 savepos = ftell(ifp);
if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile
if(callbacks.exif_cb)
{
callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp);
fseek(ifp,savepos,SEEK_SET);
}
#endif
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncasecmp(make, "SONY", 4) ||
(!strncasecmp(make, "Hasselblad", 10) &&
(!strncasecmp(model, "Stellar", 7) ||
!strncasecmp(model, "Lunar", 5) ||
!strncasecmp(model, "HV",2))))
{
switch (tag) {
case 0x7300: // SR2 black level
for (int i = 0; i < 4 && i < len; i++)
cblack[i] = get2();
break;
case 0x7480:
case 0x7820:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1];
break;
case 0x7481:
case 0x7821:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1];
break;
case 0x7482:
case 0x7822:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1];
break;
case 0x7483:
case 0x7823:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1];
break;
case 0x7484:
case 0x7824:
imgdata.color.WBCT_Coeffs[0][0] = 4500;
FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2();
imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2];
break;
case 0x7486:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1];
break;
case 0x7825:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1];
break;
case 0x7826:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1];
break;
case 0x7827:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1];
break;
case 0x7828:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1];
break;
case 0x7829:
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1];
break;
case 0x782a:
imgdata.color.WBCT_Coeffs[1][0] = 8500;
FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2();
imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2];
break;
case 0x782b:
imgdata.color.WBCT_Coeffs[2][0] = 6000;
FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2();
imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2];
break;
case 0x782c:
imgdata.color.WBCT_Coeffs[3][0] = 3200;
FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1];
break;
case 0x782d:
imgdata.color.WBCT_Coeffs[4][0] = 2500;
FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2();
imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2];
break;
case 0x787f:
FORC3 imgdata.color.linear_max[c] = get2();
imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
break;
}
}
#endif
switch (tag) {
case 1: if(len==4) pana_raw = get4(); break;
case 5: width = get2(); break;
case 6: height = get2(); break;
case 7: width += get2(); break;
case 9: if ((i = get2())) filters = i;
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
pana_black[3]+=i;
#endif
break;
case 8:
case 10:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
pana_black[3]+=get2();
#endif
break;
case 14: case 15: case 16:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw) {
imgdata.color.linear_max[tag-14] = get2();
if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1];
}
#endif
break;
case 17: case 18:
if (type == 3 && len == 1)
cam_mul[(tag-17)*2] = get2() / 256.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 19:
if(pana_raw) {
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100) break;
for (cnt=0; cnt<nWB; cnt++) {
tWB = get2();
if (tWB < 0x100) {
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100;
} else get4();
}
}
break;
#endif
case 23:
if (type == 3) iso_speed = get2();
break;
case 28: case 29: case 30:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw && len == 1 && type ==3)
{
pana_black[tag-28] = get2();
}
else
#endif
{
cblack[tag-28] = get2();
cblack[3] = cblack[1];
}
break;
case 36: case 37: case 38:
cam_mul[tag-36] = get2();
break;
case 39:
#ifdef LIBRAW_LIBRARY_BUILD
if(pana_raw) {
ushort nWB, cnt, tWB;
nWB = get2();
if (nWB > 0x100) break;
for (cnt=0; cnt<nWB; cnt++) {
tWB = get2();
if (tWB < 0x100) {
imgdata.color.WB_Coeffs[tWB][0] = get2();
imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2();
imgdata.color.WB_Coeffs[tWB][2] = get2();
} else fseek(ifp, 6, SEEK_CUR);
}
}
break;
#endif
if (len < 50 || cam_mul[0]) break;
fseek (ifp, 12, SEEK_CUR);
FORC3 cam_mul[c] = get2();
break;
case 46:
if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break;
thumb_offset = ftell(ifp) - 2;
thumb_length = len;
break;
case 61440: /* Fuji HS10 table */
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
break;
case 2: case 256: case 61441: /* ImageWidth */
tiff_ifd[ifd].t_width = getint(type);
break;
case 3: case 257: case 61442: /* ImageHeight */
tiff_ifd[ifd].t_height = getint(type);
break;
case 258: /* BitsPerSample */
case 61443:
tiff_ifd[ifd].samples = len & 7;
tiff_ifd[ifd].bps = getint(type);
if (tiff_bps < tiff_ifd[ifd].bps)
tiff_bps = tiff_ifd[ifd].bps;
break;
case 61446:
raw_height = 0;
if (tiff_ifd[ifd].bps > 12) break;
load_raw = &CLASS packed_load_raw;
load_flags = get4() ? 24:80;
break;
case 259: /* Compression */
tiff_ifd[ifd].comp = getint(type);
break;
case 262: /* PhotometricInterpretation */
tiff_ifd[ifd].phint = get2();
break;
case 270: /* ImageDescription */
fread (desc, 512, 1, ifp);
break;
case 271: /* Make */
fgets (make, 64, ifp);
break;
case 272: /* Model */
fgets (model, 64, ifp);
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 278:
tiff_ifd[ifd].rows_per_strip = getint(type);
break;
#endif
case 280: /* Panasonic RW2 offset */
if (type != 4) break;
load_raw = &CLASS panasonic_load_raw;
load_flags = 0x2008;
case 273: /* StripOffset */
#ifdef LIBRAW_LIBRARY_BUILD
if(len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int));
tiff_ifd[ifd].strip_offsets_count = len;
for(int i=0; i< len; i++)
tiff_ifd[ifd].strip_offsets[i]=get4()+base;
fseek(ifp,sav,SEEK_SET); // restore position
}
/* fallback */
#endif
case 513: /* JpegIFOffset */
case 61447:
tiff_ifd[ifd].offset = get4()+base;
if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) {
fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
tiff_ifd[ifd].comp = 6;
tiff_ifd[ifd].t_width = jh.wide;
tiff_ifd[ifd].t_height = jh.high;
tiff_ifd[ifd].bps = jh.bits;
tiff_ifd[ifd].samples = jh.clrs;
if (!(jh.sraw || (jh.clrs & 1)))
tiff_ifd[ifd].t_width *= jh.clrs;
if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) {
tiff_ifd[ifd].t_width /= 2;
tiff_ifd[ifd].t_height *= 2;
}
i = order;
parse_tiff (tiff_ifd[ifd].offset + 12);
order = i;
}
}
break;
case 274: /* Orientation */
tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0';
break;
case 277: /* SamplesPerPixel */
tiff_ifd[ifd].samples = getint(type) & 7;
break;
case 279: /* StripByteCounts */
#ifdef LIBRAW_LIBRARY_BUILD
if(len > 1 && len < 16384)
{
off_t sav = ftell(ifp);
tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int));
tiff_ifd[ifd].strip_byte_counts_count = len;
for(int i=0; i< len; i++)
tiff_ifd[ifd].strip_byte_counts[i]=get4();
fseek(ifp,sav,SEEK_SET); // restore position
}
/* fallback */
#endif
case 514:
case 61448:
tiff_ifd[ifd].bytes = get4();
break;
case 61454:
FORC3 cam_mul[(4-c) % 3] = getint(type);
break;
case 305: case 11: /* Software */
fgets (software, 64, ifp);
if (!strncmp(software,"Adobe",5) ||
!strncmp(software,"dcraw",5) ||
!strncmp(software,"UFRaw",5) ||
!strncmp(software,"Bibble",6) ||
!strcmp (software,"Digital Photo Professional"))
is_raw = 0;
break;
case 306: /* DateTime */
get_timestamp(0);
break;
case 315: /* Artist */
fread (artist, 64, 1, ifp);
break;
case 317:
tiff_ifd[ifd].predictor = getint(type);
break;
case 322: /* TileWidth */
tiff_ifd[ifd].t_tile_width = getint(type);
break;
case 323: /* TileLength */
tiff_ifd[ifd].t_tile_length = getint(type);
break;
case 324: /* TileOffsets */
tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4();
if (len == 1)
tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0;
if (len == 4) {
load_raw = &CLASS sinar_4shot_load_raw;
is_raw = 5;
}
break;
case 325:
tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4();
break;
case 330: /* SubIFDs */
if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) {
load_raw = &CLASS sony_arw_load_raw;
data_offset = get4()+base;
ifd++;
#ifdef LIBRAW_LIBRARY_BUILD
if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0])
throw LIBRAW_EXCEPTION_IO_CORRUPT;
#endif
break;
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) {
fseek (ifp, ftell(ifp)+4, SEEK_SET);
fseek (ifp, get4()+base, SEEK_SET);
parse_tiff_ifd (base);
break;
}
#endif
if(len > 1000) len=1000; /* 1000 SubIFDs is enough */
while (len--) {
i = ftell(ifp);
fseek (ifp, get4()+base, SEEK_SET);
if (parse_tiff_ifd (base)) break;
fseek (ifp, i+4, SEEK_SET);
}
break;
case 339:
tiff_ifd[ifd].sample_format = getint(type);
break;
case 400:
strcpy (make, "Sarnoff");
maximum = 0xfff;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 700:
if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000)
{
xmpdata = (char*)malloc(xmplen = len+1);
fread(xmpdata,len,1,ifp);
xmpdata[len]=0;
}
break;
#endif
case 28688:
FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff;
for (i=0; i < 5; i++)
for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++)
curve[j] = curve[j-1] + (1 << i);
break;
case 29184: sony_offset = get4(); break;
case 29185: sony_length = get4(); break;
case 29217: sony_key = get4(); break;
case 29264:
parse_minolta (ftell(ifp));
raw_width = 0;
break;
case 29443:
FORC4 cam_mul[c ^ (c < 2)] = get2();
break;
case 29459:
FORC4 cam_mul[c] = get2();
i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1;
SWAP (cam_mul[i],cam_mul[i+1])
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800
for (i=0; i < 3; i++) {
float num = 0.0;
for (c=0; c<3; c++) {
imgdata.color.ccm[i][c] = (float) ((short)get2());
num += imgdata.color.ccm[i][c];
}
if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num;
}
break;
#endif
case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4
FORC4 cblack[c ^ c >> 1] = get2();
i = cblack[3];
FORC3 if(i>cblack[c]) i = cblack[c];
FORC4 cblack[c]-=i;
black = i;
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]);
#endif
break;
case 33405: /* Model2 */
fgets (model2, 64, ifp);
break;
case 33421: /* CFARepeatPatternDim */
if (get2() == 6 && get2() == 6)
filters = 9;
break;
case 33422: /* CFAPattern */
if (filters == 9) {
FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3;
break;
}
case 64777: /* Kodak P-series */
if(len == 36)
{
filters = 9;
colors = 3;
FORC(36) xtrans[0][c] = fgetc(ifp) & 3;
}
else if(len > 0)
{
if ((plen=len) > 16) plen = 16;
fread (cfa_pat, 1, plen, ifp);
for (colors=cfa=i=0; i < plen && colors < 4; i++) {
colors += !(cfa & (1 << cfa_pat[i]));
cfa |= 1 << cfa_pat[i];
}
if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */
if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */
goto guess_cfa_pc;
}
break;
case 33424:
case 65024:
fseek (ifp, get4()+base, SEEK_SET);
parse_kodak_ifd (base);
break;
case 33434: /* ExposureTime */
tiff_ifd[ifd].t_shutter = shutter = getreal(type);
break;
case 33437: /* FNumber */
aperture = getreal(type);
break;
#ifdef LIBRAW_LIBRARY_BUILD
// IB start
case 0xa405: // FocalLengthIn35mmFormat
imgdata.lens.FocalLengthIn35mmFormat = get2();
break;
case 0xa431: // BodySerialNumber
case 0xc62f:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
break;
case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa435: // LensSerialNumber
stmread(imgdata.lens.LensSerial, len, ifp);
break;
case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard
imgdata.lens.MinFocal = getreal(type);
imgdata.lens.MaxFocal = getreal(type);
imgdata.lens.MaxAp4MinFocal = getreal(type);
imgdata.lens.MaxAp4MaxFocal = getreal(type);
break;
case 0xa433: // LensMake
stmread(imgdata.lens.LensMake, len, ifp);
break;
case 0xa434: // LensModel
stmread(imgdata.lens.Lens, len, ifp);
if (!strncmp(imgdata.lens.Lens, "----", 4))
imgdata.lens.Lens[0] = 0;
break;
case 0x9205:
imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f));
break;
// IB end
#endif
case 34306: /* Leaf white balance */
FORC4 cam_mul[c ^ 1] = 4096.0 / get2();
break;
case 34307: /* Leaf CatchLight color matrix */
fread (software, 1, 7, ifp);
if (strncmp(software,"MATRIX",6)) break;
colors = 4;
for (raw_color = i=0; i < 3; i++) {
FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]);
if (!use_camera_wb) continue;
num = 0;
FORC4 num += rgb_cam[i][c];
FORC4 rgb_cam[i][c] /= MAX(1,num);
}
break;
case 34310: /* Leaf metadata */
parse_mos (ftell(ifp));
case 34303:
strcpy (make, "Leaf");
break;
case 34665: /* EXIF tag */
fseek (ifp, get4()+base, SEEK_SET);
parse_exif (base);
break;
case 34853: /* GPSInfo tag */
{
unsigned pos;
fseek(ifp, pos = (get4() + base), SEEK_SET);
parse_gps(base);
#ifdef LIBRAW_LIBRARY_BUILD
fseek(ifp, pos, SEEK_SET);
parse_gps_libraw(base);
#endif
}
break;
case 34675: /* InterColorProfile */
case 50831: /* AsShotICCProfile */
profile_offset = ftell(ifp);
profile_length = len;
break;
case 37122: /* CompressedBitsPerPixel */
kodak_cbpp = get4();
break;
case 37386: /* FocalLength */
focal_len = getreal(type);
break;
case 37393: /* ImageNumber */
shot_order = getint(type);
break;
case 37400: /* old Kodak KDC tag */
for (raw_color = i=0; i < 3; i++) {
getreal(type);
FORC3 rgb_cam[i][c] = getreal(type);
}
break;
case 40976:
strip_offset = get4();
switch (tiff_ifd[ifd].comp) {
case 32770: load_raw = &CLASS samsung_load_raw; break;
case 32772: load_raw = &CLASS samsung2_load_raw; break;
case 32773: load_raw = &CLASS samsung3_load_raw; break;
}
break;
case 46275: /* Imacon tags */
strcpy (make, "Imacon");
data_offset = ftell(ifp);
ima_len = len;
break;
case 46279:
if (!ima_len) break;
fseek (ifp, 38, SEEK_CUR);
case 46274:
fseek (ifp, 40, SEEK_CUR);
raw_width = get4();
raw_height = get4();
left_margin = get4() & 7;
width = raw_width - left_margin - (get4() & 7);
top_margin = get4() & 7;
height = raw_height - top_margin - (get4() & 7);
if (raw_width == 7262 && ima_len == 234317952 ) {
height = 5412;
width = 7216;
left_margin = 7;
filters=0;
} else if (raw_width == 7262) {
height = 5444;
width = 7244;
left_margin = 7;
}
fseek (ifp, 52, SEEK_CUR);
FORC3 cam_mul[c] = getreal(11);
fseek (ifp, 114, SEEK_CUR);
flip = (get2() >> 7) * 90;
if (width * height * 6 == ima_len) {
if (flip % 180 == 90) SWAP(width,height);
raw_width = width;
raw_height = height;
left_margin = top_margin = filters = flip = 0;
}
sprintf (model, "Ixpress %d-Mp", height*width/1000000);
load_raw = &CLASS imacon_full_load_raw;
if (filters) {
if (left_margin & 1) filters = 0x61616161;
load_raw = &CLASS unpacked_load_raw;
}
maximum = 0xffff;
break;
case 50454: /* Sinar tag */
case 50455:
if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break;
#ifndef LIBRAW_LIBRARY_BUILD
fread (cbuf, 1, len, ifp);
#else
if(fread (cbuf, 1, len, ifp) != len)
throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle
#endif
cbuf[len-1] = 0;
for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n'))
if (!strncmp (++cp,"Neutral ",8))
sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2);
free (cbuf);
break;
case 50458:
if (!make[0]) strcpy (make, "Hasselblad");
break;
case 50459: /* Hasselblad tag */
#ifdef LIBRAW_LIBRARY_BUILD
libraw_internal_data.unpacker_data.hasselblad_parser_flag=1;
#endif
i = order;
j = ftell(ifp);
c = tiff_nifds;
order = get2();
fseek (ifp, j+(get2(),get4()), SEEK_SET);
parse_tiff_ifd (j);
maximum = 0xffff;
tiff_nifds = c;
order = i;
break;
case 50706: /* DNGVersion */
FORC4 dng_version = (dng_version << 8) + fgetc(ifp);
if (!make[0]) strcpy (make, "DNG");
is_raw = 1;
break;
case 50708: /* UniqueCameraModel */
#ifdef LIBRAW_LIBRARY_BUILD
stmread(imgdata.color.UniqueCameraModel, len, ifp);
imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0;
#endif
if (model[0]) break;
#ifndef LIBRAW_LIBRARY_BUILD
fgets (make, 64, ifp);
#else
strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel)));
#endif
if ((cp = strchr(make,' '))) {
strcpy(model,cp+1);
*cp = 0;
}
break;
case 50710: /* CFAPlaneColor */
if (filters == 9) break;
if (len > 4) len = 4;
colors = len;
fread (cfa_pc, 1, colors, ifp);
guess_cfa_pc:
FORCC tab[cfa_pc[c]] = c;
cdesc[c] = 0;
for (i=16; i--; )
filters = filters << 2 | tab[cfa_pat[i % plen]];
filters -= !filters;
break;
case 50711: /* CFALayout */
if (get2() == 2) fuji_width = 1;
break;
case 291:
case 50712: /* LinearizationTable */
linear_table (len);
break;
case 50713: /* BlackLevelRepeatDim */
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_cblack[4] =
#endif
cblack[4] = get2();
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_cblack[5] =
#endif
cblack[5] = get2();
if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6))
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_cblack[4]=
imgdata.color.dng_levels.dng_cblack[5]=
#endif
cblack[4] = cblack[5] = 1;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0xf00c: {
unsigned fwb[4];
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000)
{
long long f_save = ftell(ifp);
int fj, found = 0;
ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData);
fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET);
fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp);
fseek(ifp, f_save, SEEK_SET);
for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++)
{
if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2]))
{
if (rafdata[fi-15] != fwb[0]) continue;
fi = fi - 15;
imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13];
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16];
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17];
fi += 111;
for (fj = fi; fj<(fi+15); fj+=3)
if (rafdata[fj] != rafdata[fi])
{
found = 1;
break;
}
if (found)
{
int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000};
fj = fj - 93;
for (int iCCT=0; iCCT < 31; iCCT++)
{
imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT];
imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj];
imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj];
imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj];
}
}
free (rafdata);
break;
}
}
}
}
FORC4 fwb[c] = get4();
if (fwb[3] < 0x100)
{
imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1];
imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0];
imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2];
}
}
break;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
case 50709:
stmread(imgdata.color.LocalizedCameraModel,len, ifp);
break;
#endif
case 61450:
cblack[4] = cblack[5] = MIN(sqrt((double)len),64);
case 50714: /* BlackLevel */
#ifdef LIBRAW_LIBRARY_BUILD
if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black
{
for(i=0; i < colors && i < 4 && i < len; i++)
imgdata.color.dng_levels.dng_cblack[i]=
cblack[i]=
getreal(type)+0.5;
imgdata.color.dng_levels.dng_black= black = 0;
}
else
#endif
if((cblack[4] * cblack[5] < 2) && len == 1)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_black=
#endif
black =
getreal(type);
}
else if(cblack[4] * cblack[5] <= len)
{
FORC (cblack[4] * cblack[5])
cblack[6+c] = getreal(type);
black = 0;
FORC4
cblack[c] = 0;
#ifdef LIBRAW_LIBRARY_BUILD
if(tag == 50714)
{
FORC (cblack[4] * cblack[5])
imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c];
imgdata.color.dng_levels.dng_black=0;
FORC4
imgdata.color.dng_levels.dng_cblack[c]= 0;
}
#endif
}
break;
case 50715: /* BlackLevelDeltaH */
case 50716: /* BlackLevelDeltaV */
for (num=i=0; i < len && i < 65536; i++)
num += getreal(type);
black += num/len + 0.5;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_black += num/len + 0.5;
#endif
break;
case 50717: /* WhiteLevel */
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.dng_whitelevel[0]=
#endif
maximum = getint(type);
#ifdef LIBRAW_LIBRARY_BUILD
if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case
for(i=1; i < colors && i < 4 && i < len; i++)
imgdata.color.dng_levels.dng_whitelevel[i]=getint(type);
#endif
break;
case 50718: /* DefaultScale */
pixel_aspect = getreal(type);
pixel_aspect /= getreal(type);
if(pixel_aspect > 0.995 && pixel_aspect < 1.005)
pixel_aspect = 1.0;
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50778:
imgdata.color.dng_color[0].illuminant = get2();
break;
case 50779:
imgdata.color.dng_color[1].illuminant = get2();
break;
#endif
case 50721: /* ColorMatrix1 */
case 50722: /* ColorMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 50721?0:1;
#endif
FORCC for (j=0; j < 3; j++)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_color[i].colormatrix[c][j]=
#endif
cm[c][j] = getreal(type);
}
use_cm = 1;
break;
case 0xc714: /* ForwardMatrix1 */
case 0xc715: /* ForwardMatrix2 */
#ifdef LIBRAW_LIBRARY_BUILD
i = tag == 0xc714?0:1;
#endif
for (j=0; j < 3; j++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_color[i].forwardmatrix[j][c]=
#endif
fm[j][c] = getreal(type);
}
break;
case 50723: /* CameraCalibration1 */
case 50724: /* CameraCalibration2 */
#ifdef LIBRAW_LIBRARY_BUILD
j = tag == 50723?0:1;
#endif
for (i=0; i < colors; i++)
FORCC
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_color[j].calibration[i][c]=
#endif
cc[i][c] = getreal(type);
}
break;
case 50727: /* AnalogBalance */
FORCC{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.dng_levels.analogbalance[c]=
#endif
ab[c] = getreal(type);
}
break;
case 50728: /* AsShotNeutral */
FORCC asn[c] = getreal(type);
break;
case 50729: /* AsShotWhiteXY */
xyz[0] = getreal(type);
xyz[1] = getreal(type);
xyz[2] = 1 - xyz[0] - xyz[1];
FORC3 xyz[c] /= d65_white[c];
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 50730: /* DNG: Baseline Exposure */
baseline_exposure = getreal(type);
break;
#endif
// IB start
case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */
#ifdef LIBRAW_LIBRARY_BUILD
{
char mbuf[64];
unsigned short makernote_found = 0;
INT64 curr_pos, start_pos = ftell(ifp);
unsigned MakN_order, m_sorder = order;
unsigned MakN_length;
unsigned pos_in_original_raw;
fread(mbuf, 1, 6, ifp);
if (!strcmp(mbuf, "Adobe"))
{
order = 0x4d4d; // Adobe header is always in "MM" / big endian
curr_pos = start_pos + 6;
while (curr_pos + 8 - start_pos <= len)
{
fread(mbuf, 1, 4, ifp);
curr_pos += 8;
if (!strncmp(mbuf, "MakN", 4)) {
makernote_found = 1;
MakN_length = get4();
MakN_order = get2();
pos_in_original_raw = get4();
order = MakN_order;
parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG);
break;
}
}
}
else
{
fread(mbuf + 6, 1, 2, ifp);
if (!strcmp(mbuf, "PENTAX ") ||
!strcmp(mbuf, "SAMSUNG"))
{
makernote_found = 1;
fseek(ifp, start_pos, SEEK_SET);
parse_makernote_0xc634(base, 0, CameraDNG);
}
}
fseek(ifp, start_pos, SEEK_SET);
order = m_sorder;
}
// IB end
#endif
if (dng_version) break;
parse_minolta (j = get4()+base);
fseek (ifp, j, SEEK_SET);
parse_tiff_ifd (base);
break;
case 50752:
read_shorts (cr2_slice, 3);
break;
case 50829: /* ActiveArea */
top_margin = getint(type);
left_margin = getint(type);
height = getint(type) - top_margin;
width = getint(type) - left_margin;
break;
case 50830: /* MaskedAreas */
for (i=0; i < len && i < 32; i++)
((int*)mask)[i] = getint(type);
black = 0;
break;
case 51009: /* OpcodeList2 */
meta_offset = ftell(ifp);
break;
case 64772: /* Kodak P-series */
if (len < 13) break;
fseek (ifp, 16, SEEK_CUR);
data_offset = get4();
fseek (ifp, 28, SEEK_CUR);
data_offset += get4();
load_raw = &CLASS packed_load_raw;
break;
case 65026:
if (type == 2) fgets (model2, 64, ifp);
}
fseek (ifp, save, SEEK_SET);
}
if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) {
fseek (ifp, sony_offset, SEEK_SET);
fread (buf, sony_length, 1, ifp);
sony_decrypt (buf, sony_length/4, 1, sony_key);
#ifndef LIBRAW_LIBRARY_BUILD
sfp = ifp;
if ((ifp = tmpfile())) {
fwrite (buf, sony_length, 1, ifp);
fseek (ifp, 0, SEEK_SET);
parse_tiff_ifd (-sony_offset);
fclose (ifp);
}
ifp = sfp;
#else
if( !ifp->tempbuffer_open(buf,sony_length))
{
parse_tiff_ifd(-sony_offset);
ifp->tempbuffer_close();
}
#endif
free (buf);
}
for (i=0; i < colors; i++)
FORCC cc[i][c] *= ab[i];
if (use_cm) {
FORCC for (i=0; i < 3; i++)
for (cam_xyz[c][i]=j=0; j < colors; j++)
cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i];
cam_xyz_coeff (cmatrix, cam_xyz);
}
if (asn[0]) {
cam_mul[3] = 0;
FORCC cam_mul[c] = 1 / asn[c];
}
if (!use_cm)
FORCC pre_mul[c] /= cc[c][c];
return 0;
}
int CLASS parse_tiff (int base)
{
int doff;
fseek (ifp, base, SEEK_SET);
order = get2();
if (order != 0x4949 && order != 0x4d4d) return 0;
get2();
while ((doff = get4())) {
fseek (ifp, doff+base, SEEK_SET);
if (parse_tiff_ifd (base)) break;
}
return 1;
}
void CLASS apply_tiff()
{
int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i;
struct jhead jh;
thumb_misc = 16;
if (thumb_offset) {
fseek (ifp, thumb_offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000)
{
thumb_misc = jh.bits;
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
}
for (i=tiff_nifds; i--; ) {
if (tiff_ifd[i].t_shutter)
shutter = tiff_ifd[i].t_shutter;
tiff_ifd[i].t_shutter = shutter;
}
for (i=0; i < tiff_nifds; i++) {
if (max_samp < tiff_ifd[i].samples)
max_samp = tiff_ifd[i].samples;
if (max_samp > 3) max_samp = 3;
os = raw_width*raw_height;
ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height;
if (tiff_bps) {
os *= tiff_bps;
ns *= tiff_ifd[i].bps;
}
if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) &&
unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
(unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 &&
ns && ((ns > os && (ties = 1)) ||
(ns == os && shot_select == ties++))) {
raw_width = tiff_ifd[i].t_width;
raw_height = tiff_ifd[i].t_height;
tiff_bps = tiff_ifd[i].bps;
tiff_compress = tiff_ifd[i].comp;
data_offset = tiff_ifd[i].offset;
#ifdef LIBRAW_LIBRARY_BUILD
data_size = tiff_ifd[i].bytes;
#endif
tiff_flip = tiff_ifd[i].t_flip;
tiff_samples = tiff_ifd[i].samples;
tile_width = tiff_ifd[i].t_tile_width;
tile_length = tiff_ifd[i].t_tile_length;
shutter = tiff_ifd[i].t_shutter;
raw = i;
}
}
if (is_raw == 1 && ties) is_raw = ties;
if (!tile_width ) tile_width = INT_MAX;
if (!tile_length) tile_length = INT_MAX;
for (i=tiff_nifds; i--; )
if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip;
if (raw >= 0 && !load_raw)
switch (tiff_compress) {
case 32767:
if (tiff_ifd[raw].bytes == raw_width*raw_height) {
tiff_bps = 12;
load_raw = &CLASS sony_arw2_load_raw; break;
}
if (!strncasecmp(make,"Sony",4) &&
tiff_ifd[raw].bytes == raw_width*raw_height*2) {
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw; break;
}
if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) {
raw_height += 8;
load_raw = &CLASS sony_arw_load_raw; break;
}
load_flags = 79;
case 32769:
load_flags++;
case 32770:
case 32773: goto slr;
case 0: case 1:
#ifdef LIBRAW_LIBRARY_BUILD
// Sony 14-bit uncompressed
if(!strncasecmp(make,"Sony",4) &&
tiff_ifd[raw].bytes == raw_width*raw_height*2)
{
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
break;
}
if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10))
{
load_raw = &CLASS nikon_coolscan_load_raw;
raw_color = 1;
filters = 0;
break;
}
#endif
if (!strncmp(make,"OLYMPUS",7) &&
tiff_ifd[raw].bytes*2 == raw_width*raw_height*3)
load_flags = 24;
if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) {
load_flags = 81;
tiff_bps = 12;
} slr:
switch (tiff_bps) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 12: if (tiff_ifd[raw].phint == 2)
load_flags = 6;
load_raw = &CLASS packed_load_raw; break;
case 14: load_flags = 0;
case 16: load_raw = &CLASS unpacked_load_raw;
if (!strncmp(make,"OLYMPUS",7) &&
tiff_ifd[raw].bytes*7 > raw_width*raw_height)
load_raw = &CLASS olympus_load_raw;
}
break;
case 6: case 7: case 99:
load_raw = &CLASS lossless_jpeg_load_raw; break;
case 262:
load_raw = &CLASS kodak_262_load_raw; break;
case 34713:
if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) {
load_raw = &CLASS packed_load_raw;
load_flags = 1;
} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) {
load_raw = &CLASS packed_load_raw;
if (model[0] == 'N') load_flags = 80;
} else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) {
load_raw = &CLASS nikon_yuv_load_raw;
gamma_curve (1/2.4, 12.92, 1, 4095);
memset (cblack, 0, sizeof cblack);
filters = 0;
} else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) {
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
order = 0x4d4d;
} else
#ifdef LIBRAW_LIBRARY_BUILD
if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2)
{
load_raw = &CLASS packed_load_raw;
load_flags=80;
}
else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count &&
tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count)
{
int fit = 1;
for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last
if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3)
{
fit = 0;
break;
}
if(fit)
load_raw = &CLASS nikon_load_striped_packed_raw;
else
load_raw = &CLASS nikon_load_raw; // fallback
}
else
#endif
load_raw = &CLASS nikon_load_raw; break;
case 65535:
load_raw = &CLASS pentax_load_raw; break;
case 65000:
switch (tiff_ifd[raw].phint) {
case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break;
case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break;
case 32803: load_raw = &CLASS kodak_65000_load_raw;
}
case 32867: case 34892: break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8: break;
#endif
default: is_raw = 0;
}
if (!dng_version)
if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 &&
(tiff_compress & -16) != 32768)
|| (tiff_bps == 8 && strncmp(make,"Phase",5) &&
!strcasestr(make,"Kodak") &&
!strstr(model2,"DEBUG RAW")))
&& strncmp(software,"Nikon Scan",10))
is_raw = 0;
for (i=0; i < tiff_nifds; i++)
if (i != raw
&& (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */
&& tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33
&& tiff_ifd[i].phint != 32803
&& tiff_ifd[i].phint != 34892
&& unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 &&
tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) >
thumb_width * thumb_height / (SQR(thumb_misc)+1)
&& tiff_ifd[i].comp != 34892) {
thumb_width = tiff_ifd[i].t_width;
thumb_height = tiff_ifd[i].t_height;
thumb_offset = tiff_ifd[i].offset;
thumb_length = tiff_ifd[i].bytes;
thumb_misc = tiff_ifd[i].bps;
thm = i;
}
if (thm >= 0) {
thumb_misc |= tiff_ifd[thm].samples << 5;
switch (tiff_ifd[thm].comp) {
case 0:
write_thumb = &CLASS layer_thumb;
break;
case 1:
if (tiff_ifd[thm].bps <= 8)
write_thumb = &CLASS ppm_thumb;
else if (!strncmp(make,"Imacon",6))
write_thumb = &CLASS ppm16_thumb;
else
thumb_load_raw = &CLASS kodak_thumb_load_raw;
break;
case 65000:
thumb_load_raw = tiff_ifd[thm].phint == 6 ?
&CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw;
}
}
}
void CLASS parse_minolta (int base)
{
int save, tag, len, offset, high=0, wide=0, i, c;
short sorder=order;
fseek (ifp, base, SEEK_SET);
if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return;
order = fgetc(ifp) * 0x101;
offset = base + get4() + 8;
while ((save=ftell(ifp)) < offset) {
for (tag=i=0; i < 4; i++)
tag = tag << 8 | fgetc(ifp);
len = get4();
switch (tag) {
case 0x505244: /* PRD */
fseek (ifp, 8, SEEK_CUR);
high = get2();
wide = get2();
break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x524946: /* RIF */
if (!strncasecmp(model,"DSLR-A100", 9))
{
fseek(ifp, 8, SEEK_CUR);
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2();
get4();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2();
imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] =
imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100;
}
break;
#endif
case 0x574247: /* WBG */
get4();
i = strcmp(model,"DiMAGE A200") ? 0:3;
FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2();
break;
case 0x545457: /* TTW */
parse_tiff (ftell(ifp));
data_offset = offset;
}
fseek (ifp, save+len+8, SEEK_SET);
}
raw_height = high;
raw_width = wide;
order = sorder;
}
/*
Many cameras have a "debug mode" that writes JPEG and raw
at the same time. The raw file has no header, so try to
to open the matching JPEG file and read its metadata.
*/
void CLASS parse_external_jpeg()
{
const char *file, *ext;
char *jname, *jfile, *jext;
#ifndef LIBRAW_LIBRARY_BUILD
FILE *save=ifp;
#else
#if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310)
if(ifp->wfname())
{
std::wstring rawfile(ifp->wfname());
rawfile.replace(rawfile.length()-3,3,L"JPG");
if(!ifp->subfile_open(rawfile.c_str()))
{
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
return;
}
#endif
if(!ifp->fname())
{
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
return;
}
#endif
ext = strrchr (ifname, '.');
file = strrchr (ifname, '/');
if (!file) file = strrchr (ifname, '\\');
#ifndef LIBRAW_LIBRARY_BUILD
if (!file) file = ifname-1;
#else
if (!file) file = (char*)ifname-1;
#endif
file++;
if (!ext || strlen(ext) != 4 || ext-file != 8) return;
jname = (char *) malloc (strlen(ifname) + 1);
merror (jname, "parse_external_jpeg()");
strcpy (jname, ifname);
jfile = file - ifname + jname;
jext = ext - ifname + jname;
if (strcasecmp (ext, ".jpg")) {
strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg");
if (isdigit(*file)) {
memcpy (jfile, file+4, 4);
memcpy (jfile+4, file, 4);
}
} else
while (isdigit(*--jext)) {
if (*jext != '9') {
(*jext)++;
break;
}
*jext = '0';
}
#ifndef LIBRAW_LIBRARY_BUILD
if (strcmp (jname, ifname)) {
if ((ifp = fopen (jname, "rb"))) {
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Reading metadata from %s ...\n"), jname);
#endif
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
fclose (ifp);
}
}
#else
if (strcmp (jname, ifname))
{
if(!ifp->subfile_open(jname))
{
parse_tiff (12);
thumb_offset = 0;
is_raw = 1;
ifp->subfile_close();
}
else
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
}
#endif
if (!timestamp)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("Failed to read metadata from %s\n"), jname);
#endif
}
free (jname);
#ifndef LIBRAW_LIBRARY_BUILD
ifp = save;
#endif
}
/*
CIFF block 0x1030 contains an 8x8 white sample.
Load this into white[][] for use in scale_colors().
*/
void CLASS ciff_block_1030()
{
static const ushort key[] = { 0x410, 0x45f3 };
int i, bpp, row, col, vbits=0;
unsigned long bitbuf=0;
if ((get2(),get4()) != 0x80008 || !get4()) return;
bpp = get2();
if (bpp != 10 && bpp != 12) return;
for (i=row=0; row < 8; row++)
for (col=0; col < 8; col++) {
if (vbits < bpp) {
bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]);
vbits += 16;
}
white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp);
}
}
/*
Parse a CIFF file, better known as Canon CRW format.
*/
void CLASS parse_ciff (int offset, int length, int depth)
{
int tboff, nrecs, c, type, len, save, wbi=-1;
ushort key[] = { 0x410, 0x45f3 };
fseek (ifp, offset+length-4, SEEK_SET);
tboff = get4() + offset;
fseek (ifp, tboff, SEEK_SET);
nrecs = get2();
if ((nrecs | depth) > 127) return;
while (nrecs--) {
type = get2();
len = get4();
save = ftell(ifp) + 4;
fseek (ifp, offset+get4(), SEEK_SET);
if ((((type >> 8) + 8) | 8) == 0x38) {
parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1);
#endif
if (type == 0x0810)
fread (artist, 64, 1, ifp);
if (type == 0x080a) {
fread (make, 64, 1, ifp);
fseek (ifp, strbuflen(make) - 63, SEEK_CUR);
fread (model, 64, 1, ifp);
}
if (type == 0x1810) {
width = get4();
height = get4();
pixel_aspect = int_to_float(get4());
flip = get4();
}
if (type == 0x1835) /* Get the decoder table */
tiff_compress = get4();
if (type == 0x2007) {
thumb_offset = ftell(ifp);
thumb_length = len;
}
if (type == 0x1818) {
shutter = powf64(2.0f, -int_to_float((get4(),get4())));
aperture = powf64(2.0f, int_to_float(get4())/2);
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurAp = aperture;
#endif
}
if (type == 0x102a) {
// iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50;
iso_speed = powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f;
#ifdef LIBRAW_LIBRARY_BUILD
aperture = _CanonConvertAperture((get2(),get2()));
imgdata.lens.makernotes.CurAp = aperture;
#else
aperture = powf64(2.0, (get2(),(short)get2())/64.0);
#endif
shutter = powf64(2.0,-((short)get2())/32.0);
wbi = (get2(),get2());
if (wbi > 17) wbi = 0;
fseek (ifp, 32, SEEK_CUR);
if (shutter > 1e6) shutter = get2()/10.0;
}
if (type == 0x102c) {
if (get2() > 512) { /* Pro90, G1 */
fseek (ifp, 118, SEEK_CUR);
FORC4 cam_mul[c ^ 2] = get2();
} else { /* G2, S30, S40 */
fseek (ifp, 98, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2();
}
}
#ifdef LIBRAW_LIBRARY_BUILD
if (type == 0x10a9)
{
INT64 o = ftell(ifp);
fseek (ifp, (0x5<<1), SEEK_CUR);
Canon_WBpresets(0,0);
fseek(ifp,o,SEEK_SET);
}
if (type == 0x102d)
{
INT64 o = ftell(ifp);
Canon_CameraSettings();
fseek(ifp,o,SEEK_SET);
}
if (type == 0x580b)
{
if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len);
else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff);
}
#endif
if (type == 0x0032) {
if (len == 768) { /* EOS D30 */
fseek (ifp, 72, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2();
if (!wbi) cam_mul[0] = -1; /* use my auto white balance */
} else if (!cam_mul[0]) {
if (get2() == key[0]) /* Pro1, G6, S60, S70 */
c = (strstr(model,"Pro1") ?
"012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2;
else { /* G3, G5, S45, S50 */
c = "023457000000006000"[LIM(0,wbi,17)]-'0';
key[0] = key[1] = 0;
}
fseek (ifp, 78 + c*8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1];
if (!wbi) cam_mul[0] = -1;
}
}
if (type == 0x10a9) { /* D60, 10D, 300D, and clones */
if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0';
fseek (ifp, 2 + wbi*8, SEEK_CUR);
FORC4 cam_mul[c ^ (c >> 1)] = get2();
}
if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1))
ciff_block_1030(); /* all that don't have 0x10a9 */
if (type == 0x1031) {
raw_width = (get2(),get2());
raw_height = get2();
}
if (type == 0x501c) {
iso_speed = len & 0xffff;
}
if (type == 0x5029) {
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CurFocal = len >> 16;
imgdata.lens.makernotes.FocalType = len & 0xffff;
if (imgdata.lens.makernotes.FocalType == 2) {
imgdata.lens.makernotes.CanonFocalUnits = 32;
if(imgdata.lens.makernotes.CanonFocalUnits>1)
imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits;
}
focal_len = imgdata.lens.makernotes.CurFocal;
#else
focal_len = len >> 16;
if ((len & 0xffff) == 2) focal_len /= 32;
#endif
}
if (type == 0x5813) flash_used = int_to_float(len);
if (type == 0x5814) canon_ev = int_to_float(len);
if (type == 0x5817) shot_order = len;
if (type == 0x5834)
{
unique_id = len;
#ifdef LIBRAW_LIBRARY_BUILD
setCanonBodyFeatures(unique_id);
#endif
}
if (type == 0x580e) timestamp = len;
if (type == 0x180e) timestamp = get4();
#ifdef LOCALTIME
if ((type | 0x4000) == 0x580e)
timestamp = mktime (gmtime (×tamp));
#endif
fseek (ifp, save, SEEK_SET);
}
}
void CLASS parse_rollei()
{
char line[128], *val;
struct tm t;
fseek (ifp, 0, SEEK_SET);
memset (&t, 0, sizeof t);
do {
fgets (line, 128, ifp);
if ((val = strchr(line,'=')))
*val++ = 0;
else
val = line + strbuflen(line);
if (!strcmp(line,"DAT"))
sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year);
if (!strcmp(line,"TIM"))
sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec);
if (!strcmp(line,"HDR"))
thumb_offset = atoi(val);
if (!strcmp(line,"X "))
raw_width = atoi(val);
if (!strcmp(line,"Y "))
raw_height = atoi(val);
if (!strcmp(line,"TX "))
thumb_width = atoi(val);
if (!strcmp(line,"TY "))
thumb_height = atoi(val);
} while (strncmp(line,"EOHD",4));
data_offset = thumb_offset + thumb_width * thumb_height * 2;
t.tm_year -= 1900;
t.tm_mon -= 1;
if (mktime(&t) > 0)
timestamp = mktime(&t);
strcpy (make, "Rollei");
strcpy (model,"d530flex");
write_thumb = &CLASS rollei_thumb;
}
void CLASS parse_sinar_ia()
{
int entries, off;
char str[8], *cp;
order = 0x4949;
fseek (ifp, 4, SEEK_SET);
entries = get4();
fseek (ifp, get4(), SEEK_SET);
while (entries--) {
off = get4(); get4();
fread (str, 8, 1, ifp);
if (!strcmp(str,"META")) meta_offset = off;
if (!strcmp(str,"THUMB")) thumb_offset = off;
if (!strcmp(str,"RAW0")) data_offset = off;
}
fseek (ifp, meta_offset+20, SEEK_SET);
fread (make, 64, 1, ifp);
make[63] = 0;
if ((cp = strchr(make,' '))) {
strcpy (model, cp+1);
*cp = 0;
}
raw_width = get2();
raw_height = get2();
load_raw = &CLASS unpacked_load_raw;
thumb_width = (get4(),get2());
thumb_height = get2();
write_thumb = &CLASS ppm_thumb;
maximum = 0x3fff;
}
void CLASS parse_phase_one (int base)
{
unsigned entries, tag, type, len, data, save, i, c;
float romm_cam[3][3];
char *cp;
memset (&ph1, 0, sizeof ph1);
fseek (ifp, base, SEEK_SET);
order = get4() & 0xffff;
if (get4() >> 8 != 0x526177) return; /* "Raw" */
fseek (ifp, get4()+base, SEEK_SET);
entries = get4();
get4();
while (entries--) {
tag = get4();
type = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, base+data, SEEK_SET);
switch (tag) {
#ifdef LIBRAW_LIBRARY_BUILD
case 0x0102:
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) {
unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
} else {
unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
break;
case 0x0401:
if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data)/2.0f));
else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type)/2.0f));
break;
case 0x0403:
if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data);
else imgdata.lens.makernotes.CurFocal = getreal(type);
break;
case 0x0410:
stmread(imgdata.lens.makernotes.body, len, ifp);
break;
case 0x0412:
stmread(imgdata.lens.makernotes.Lens, len, ifp);
break;
case 0x0414:
if (type == 4) {
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f));
} else {
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0415:
if (type == 4) {
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f));
} else {
imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f));
}
break;
case 0x0416:
if (type == 4) {
imgdata.lens.makernotes.MinFocal = int_to_float(data);
} else {
imgdata.lens.makernotes.MinFocal = getreal(type);
}
if (imgdata.lens.makernotes.MinFocal > 1000.0f)
{
imgdata.lens.makernotes.MinFocal = 0.0f;
}
break;
case 0x0417:
if (type == 4) {
imgdata.lens.makernotes.MaxFocal = int_to_float(data);
} else {
imgdata.lens.makernotes.MaxFocal = getreal(type);
}
break;
#endif
case 0x100: flip = "0653"[data & 3]-'0'; break;
case 0x106:
for (i=0; i < 9; i++)
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.color.P1_color[0].romm_cam[i]=
#endif
((float *)romm_cam)[i] = getreal(11);
romm_coeff (romm_cam);
break;
case 0x107:
FORC3 cam_mul[c] = getreal(11);
break;
case 0x108: raw_width = data; break;
case 0x109: raw_height = data; break;
case 0x10a: left_margin = data; break;
case 0x10b: top_margin = data; break;
case 0x10c: width = data; break;
case 0x10d: height = data; break;
case 0x10e: ph1.format = data; break;
case 0x10f: data_offset = data+base; break;
case 0x110: meta_offset = data+base;
meta_length = len; break;
case 0x112: ph1.key_off = save - 4; break;
case 0x210: ph1.tag_210 = int_to_float(data); break;
case 0x21a: ph1.tag_21a = data; break;
case 0x21c: strip_offset = data+base; break;
case 0x21d: ph1.t_black = data; break;
case 0x222: ph1.split_col = data; break;
case 0x223: ph1.black_col = data+base; break;
case 0x224: ph1.split_row = data; break;
case 0x225: ph1.black_row = data+base; break;
#ifdef LIBRAW_LIBRARY_BUILD
case 0x226:
for (i=0; i < 9; i++)
imgdata.color.P1_color[1].romm_cam[i] = getreal(11);
break;
#endif
case 0x301:
model[63] = 0;
fread (model, 1, 63, ifp);
if ((cp = strstr(model," camera"))) *cp = 0;
}
fseek (ifp, save, SEEK_SET);
}
#ifdef LIBRAW_LIBRARY_BUILD
if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) {
fseek (ifp, meta_offset, SEEK_SET);
order = get2();
fseek (ifp, 6, SEEK_CUR);
fseek (ifp, meta_offset+get4(), SEEK_SET);
entries = get4(); get4();
while (entries--) {
tag = get4();
len = get4();
data = get4();
save = ftell(ifp);
fseek (ifp, meta_offset+data, SEEK_SET);
if (tag == 0x0407) {
stmread(imgdata.shootinginfo.BodySerial, len, ifp);
if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) {
unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41;
} else {
unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41;
}
setPhaseOneFeatures(unique_id);
}
fseek (ifp, save, SEEK_SET);
}
}
#endif
load_raw = ph1.format < 3 ?
&CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c;
maximum = 0xffff;
strcpy (make, "Phase One");
if (model[0]) return;
switch (raw_height) {
case 2060: strcpy (model,"LightPhase"); break;
case 2682: strcpy (model,"H 10"); break;
case 4128: strcpy (model,"H 20"); break;
case 5488: strcpy (model,"H 25"); break;
}
}
void CLASS parse_fuji (int offset)
{
unsigned entries, tag, len, save, c;
fseek (ifp, offset, SEEK_SET);
entries = get4();
if (entries > 255) return;
while (entries--) {
tag = get2();
len = get2();
save = ftell(ifp);
if (tag == 0x100) {
raw_height = get2();
raw_width = get2();
} else if (tag == 0x121) {
height = get2();
if ((width = get2()) == 4284) width += 3;
} else if (tag == 0x130) {
fuji_layout = fgetc(ifp) >> 7;
fuji_width = !(fgetc(ifp) & 8);
} else if (tag == 0x131) {
filters = 9;
FORC(36)
{
int q = fgetc(ifp);
xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/
}
} else if (tag == 0x2ff0) {
FORC4 cam_mul[c ^ 1] = get2();
}
// IB start
#ifdef LIBRAW_LIBRARY_BUILD
else if (tag == 0x9650)
{
short a = (short)get2();
float b =fMAX(1.0f, get2());
imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b;
} else if (tag == 0x2100) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2();
} else if (tag == 0x2200) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2();
} else if (tag == 0x2300) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2();
} else if (tag == 0x2301) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2();
} else if (tag == 0x2302) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2();
} else if (tag == 0x2310) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2();
} else if (tag == 0x2400) {
FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2();
}
#endif
// IB end
else if (tag == 0xc000) {
c = order;
order = 0x4949;
if ((tag = get4()) > 10000) tag = get4();
if (tag > 10000) tag = get4();
width = tag;
height = get4();
#ifdef LIBRAW_LIBRARY_BUILD
libraw_internal_data.unpacker_data.posRAFData = save;
libraw_internal_data.unpacker_data.lenRAFData = (len>>1);
#endif
order = c;
}
fseek (ifp, save+len, SEEK_SET);
}
height <<= fuji_layout;
width >>= fuji_layout;
}
int CLASS parse_jpeg (int offset)
{
int len, save, hlen, mark;
fseek (ifp, offset, SEEK_SET);
if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0;
while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) {
order = 0x4d4d;
len = get2() - 2;
save = ftell(ifp);
if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) {
fgetc(ifp);
raw_height = get2();
raw_width = get2();
}
order = get2();
hlen = get4();
if (get4() == 0x48454150
#ifdef LIBRAW_LIBRARY_BUILD
&& (save+hlen) >= 0 && (save+hlen)<=ifp->size()
#endif
) /* "HEAP" */
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff (save+hlen, len-hlen, 0);
}
if (parse_tiff (save+6)) apply_tiff();
fseek (ifp, save+len, SEEK_SET);
}
return 1;
}
void CLASS parse_riff()
{
unsigned i, size, end;
char tag[4], date[64], month[64];
static const char mon[12][4] =
{ "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" };
struct tm t;
order = 0x4949;
fread (tag, 4, 1, ifp);
size = get4();
end = ftell(ifp) + size;
if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) {
int maxloop = 1000;
get4();
while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--)
parse_riff();
} else if (!memcmp(tag,"nctg",4)) {
while (ftell(ifp)+7 < end) {
i = get2();
size = get2();
if ((i+1) >> 1 == 10 && size == 20)
get_timestamp(0);
else fseek (ifp, size, SEEK_CUR);
}
} else if (!memcmp(tag,"IDIT",4) && size < 64) {
fread (date, 64, 1, ifp);
date[size] = 0;
memset (&t, 0, sizeof t);
if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday,
&t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) {
for (i=0; i < 12 && strcasecmp(mon[i],month); i++);
t.tm_mon = i;
t.tm_year -= 1900;
if (mktime(&t) > 0)
timestamp = mktime(&t);
}
} else
fseek (ifp, size, SEEK_CUR);
}
void CLASS parse_qt (int end)
{
unsigned save, size;
char tag[4];
order = 0x4d4d;
while (ftell(ifp)+7 < end) {
save = ftell(ifp);
if ((size = get4()) < 8) return;
fread (tag, 4, 1, ifp);
if (!memcmp(tag,"moov",4) ||
!memcmp(tag,"udta",4) ||
!memcmp(tag,"CNTH",4))
parse_qt (save+size);
if (!memcmp(tag,"CNDA",4))
parse_jpeg (ftell(ifp));
fseek (ifp, save+size, SEEK_SET);
}
}
void CLASS parse_smal (int offset, int fsize)
{
int ver;
fseek (ifp, offset+2, SEEK_SET);
order = 0x4949;
ver = fgetc(ifp);
if (ver == 6)
fseek (ifp, 5, SEEK_CUR);
if (get4() != fsize) return;
if (ver > 6) data_offset = get4();
raw_height = height = get2();
raw_width = width = get2();
strcpy (make, "SMaL");
sprintf (model, "v%d %dx%d", ver, width, height);
if (ver == 6) load_raw = &CLASS smal_v6_load_raw;
if (ver == 9) load_raw = &CLASS smal_v9_load_raw;
}
void CLASS parse_cine()
{
unsigned off_head, off_setup, off_image, i;
order = 0x4949;
fseek (ifp, 4, SEEK_SET);
is_raw = get2() == 2;
fseek (ifp, 14, SEEK_CUR);
is_raw *= get4();
off_head = get4();
off_setup = get4();
off_image = get4();
timestamp = get4();
if ((i = get4())) timestamp = i;
fseek (ifp, off_head+4, SEEK_SET);
raw_width = get4();
raw_height = get4();
switch (get2(),get2()) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 16: load_raw = &CLASS unpacked_load_raw;
}
fseek (ifp, off_setup+792, SEEK_SET);
strcpy (make, "CINE");
sprintf (model, "%d", get4());
fseek (ifp, 12, SEEK_CUR);
switch ((i=get4()) & 0xffffff) {
case 3: filters = 0x94949494; break;
case 4: filters = 0x49494949; break;
default: is_raw = 0;
}
fseek (ifp, 72, SEEK_CUR);
switch ((get4()+3600) % 360) {
case 270: flip = 4; break;
case 180: flip = 1; break;
case 90: flip = 7; break;
case 0: flip = 2;
}
cam_mul[0] = getreal(11);
cam_mul[2] = getreal(11);
maximum = ~((~0u) << get4());
fseek (ifp, 668, SEEK_CUR);
shutter = get4()/1000000000.0;
fseek (ifp, off_image, SEEK_SET);
if (shot_select < is_raw)
fseek (ifp, shot_select*8, SEEK_CUR);
data_offset = (INT64) get4() + 8;
data_offset += (INT64) get4() << 32;
}
void CLASS parse_redcine()
{
unsigned i, len, rdvo;
order = 0x4d4d;
is_raw = 0;
fseek (ifp, 52, SEEK_SET);
width = get4();
height = get4();
fseek (ifp, 0, SEEK_END);
fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR);
if (get4() != i || get4() != 0x52454f42) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname);
#endif
fseek (ifp, 0, SEEK_SET);
while ((len = get4()) != EOF) {
if (get4() == 0x52454456)
if (is_raw++ == shot_select)
data_offset = ftello(ifp) - 8;
fseek (ifp, len-8, SEEK_CUR);
}
} else {
rdvo = get4();
fseek (ifp, 12, SEEK_CUR);
is_raw = get4();
fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET);
data_offset = get4();
}
}
//@end COMMON
char * CLASS foveon_gets (int offset, char *str, int len)
{
int i;
fseek (ifp, offset, SEEK_SET);
for (i=0; i < len-1; i++)
if ((str[i] = get2()) == 0) break;
str[i] = 0;
return str;
}
void CLASS parse_foveon()
{
int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2];
char name[64], value[64];
order = 0x4949; /* Little-endian */
fseek (ifp, 36, SEEK_SET);
flip = get4();
fseek (ifp, -4, SEEK_END);
fseek (ifp, get4(), SEEK_SET);
if (get4() != 0x64434553) return; /* SECd */
entries = (get4(),get4());
while (entries--) {
off = get4();
len = get4();
tag = get4();
save = ftell(ifp);
fseek (ifp, off, SEEK_SET);
if (get4() != (0x20434553 | (tag << 24))) return;
switch (tag) {
case 0x47414d49: /* IMAG */
case 0x32414d49: /* IMA2 */
fseek (ifp, 8, SEEK_CUR);
pent = get4();
wide = get4();
high = get4();
if (wide > raw_width && high > raw_height) {
switch (pent) {
case 5: load_flags = 1;
case 6: load_raw = &CLASS foveon_sd_load_raw; break;
case 30: load_raw = &CLASS foveon_dp_load_raw; break;
default: load_raw = 0;
}
raw_width = wide;
raw_height = high;
data_offset = off+28;
is_foveon = 1;
}
fseek (ifp, off+28, SEEK_SET);
if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8
&& thumb_length < len-28) {
thumb_offset = off+28;
thumb_length = len-28;
write_thumb = &CLASS jpeg_thumb;
}
if (++img == 2 && !thumb_length) {
thumb_offset = off+24;
thumb_width = wide;
thumb_height = high;
write_thumb = &CLASS foveon_thumb;
}
break;
case 0x464d4143: /* CAMF */
meta_offset = off+8;
meta_length = len-28;
break;
case 0x504f5250: /* PROP */
pent = (get4(),get4());
fseek (ifp, 12, SEEK_CUR);
off += pent*8 + 24;
if ((unsigned) pent > 256) pent=256;
for (i=0; i < pent*2; i++)
((int *)poff)[i] = off + get4()*2;
for (i=0; i < pent; i++) {
foveon_gets (poff[i][0], name, 64);
foveon_gets (poff[i][1], value, 64);
if (!strcmp (name, "ISO"))
iso_speed = atoi(value);
if (!strcmp (name, "CAMMANUF"))
strcpy (make, value);
if (!strcmp (name, "CAMMODEL"))
strcpy (model, value);
if (!strcmp (name, "WB_DESC"))
strcpy (model2, value);
if (!strcmp (name, "TIME"))
timestamp = atoi(value);
if (!strcmp (name, "EXPTIME"))
shutter = atoi(value) / 1000000.0;
if (!strcmp (name, "APERTURE"))
aperture = atof(value);
if (!strcmp (name, "FLENGTH"))
focal_len = atof(value);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strcmp (name, "CAMSERIAL"))
strcpy (imgdata.shootinginfo.BodySerial, value);
if (!strcmp (name, "FLEQ35MM"))
imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value);
if (!strcmp (name, "LENSARANGE"))
{
char *sp;
imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value);
sp = strrchr (value, ' ');
if (sp)
{
imgdata.lens.makernotes.MinAp4CurFocal = atof(sp);
if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal)
my_swap (float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal);
}
}
if (!strcmp (name, "LENSFRANGE"))
{
char *sp;
imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value);
sp = strrchr (value, ' ');
if (sp)
{
imgdata.lens.makernotes.MaxFocal = atof(sp);
if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal)
my_swap (float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal);
}
}
if (!strcmp (name, "LENSMODEL"))
{
char *sp;
imgdata.lens.makernotes.LensID = strtol (value, &sp, 16); // atoi(value);
if (imgdata.lens.makernotes.LensID)
imgdata.lens.makernotes.LensMount = Sigma_X3F;
}
}
#endif
}
#ifdef LOCALTIME
timestamp = mktime (gmtime (×tamp));
#endif
}
fseek (ifp, save, SEEK_SET);
}
}
//@out COMMON
/*
All matrices are from Adobe DNG Converter unless otherwise noted.
*/
void CLASS adobe_coeff (const char *t_make, const char *t_model
#ifdef LIBRAW_LIBRARY_BUILD
,int internal_only
#endif
)
{
static const struct {
const char *prefix;
int t_black, t_maximum, trans[12];
} table[] = {
{ "AgfaPhoto DC-833m", 0, 0, /* DJC */
{ 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } },
{ "Apple QuickTake", 0, 0, /* DJC */
{ 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } },
{"Broadcom RPi IMX219", 66, 0x3ff,
{ 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */
{ "Broadcom RPi OV5647", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Canon EOS D2000", 0, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Canon EOS D6000", 0, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Canon EOS D30", 0, 0,
{ 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } },
{ "Canon EOS D60", 0, 0xfa0,
{ 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } },
{ "Canon EOS 5DS", 0, 0x3c96,
{ 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } },
{ "Canon EOS 5D Mark IV", 0, 0,
{ 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }},
{ "Canon EOS 5D Mark III", 0, 0x3c80,
{ 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } },
{ "Canon EOS 5D Mark II", 0, 0x3cf0,
{ 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } },
{ "Canon EOS 5D", 0, 0xe6c,
{ 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } },
{ "Canon EOS 6D", 0, 0x3c82,
{ 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } },
{ "Canon EOS 7D Mark II", 0, 0x3510,
{ 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } },
{ "Canon EOS 7D", 0, 0x3510,
{ 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } },
{ "Canon EOS 80D", 0, 0,
{ 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } },
{ "Canon EOS 10D", 0, 0xfa0,
{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
{ "Canon EOS 20Da", 0, 0,
{ 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } },
{ "Canon EOS 20D", 0, 0xfff,
{ 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } },
{ "Canon EOS 30D", 0, 0,
{ 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } },
{ "Canon EOS 40D", 0, 0x3f60,
{ 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } },
{ "Canon EOS 50D", 0, 0x3d93,
{ 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } },
{ "Canon EOS 60D", 0, 0x2ff7,
{ 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } },
{ "Canon EOS 70D", 0, 0x3bc7,
{ 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } },
{ "Canon EOS 100D", 0, 0x350f,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 300D", 0, 0xfa0,
{ 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } },
{ "Canon EOS 350D", 0, 0xfff,
{ 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } },
{ "Canon EOS 400D", 0, 0xe8e,
{ 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } },
{ "Canon EOS 450D", 0, 0x390d,
{ 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } },
{ "Canon EOS 500D", 0, 0x3479,
{ 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } },
{ "Canon EOS 550D", 0, 0x3dd7,
{ 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } },
{ "Canon EOS 600D", 0, 0x3510,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 650D", 0, 0x354d,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 750D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 760D", 0, 0x3c00,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS 700D", 0, 0x3c00,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS 1000D", 0, 0xe43,
{ 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } },
{ "Canon EOS 1100D", 0, 0x3510,
{ 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } },
{ "Canon EOS 1200D", 0, 0x37c2,
{ 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } },
{ "Canon EOS 1300D", 0, 0x37c2,
{ 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } },
{ "Canon EOS M3", 0, 0,
{ 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } },
{ "Canon EOS M5", 0, 0, /* Adobe */
{ 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }},
{ "Canon EOS M10", 0, 0,
{ 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } },
{ "Canon EOS M", 0, 0,
{ 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } },
{ "Canon EOS-1Ds Mark III", 0, 0x3bb0,
{ 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } },
{ "Canon EOS-1Ds Mark II", 0, 0xe80,
{ 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } },
{ "Canon EOS-1D Mark IV", 0, 0x3bb0,
{ 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } },
{ "Canon EOS-1D Mark III", 0, 0x3bb0,
{ 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } },
{ "Canon EOS-1D Mark II N", 0, 0xe80,
{ 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } },
{ "Canon EOS-1D Mark II", 0, 0xe80,
{ 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } },
{ "Canon EOS-1DS", 0, 0xe20,
{ 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } },
{ "Canon EOS-1D C", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D X Mark II", 0, 0x3c4e,
{ 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } },
{ "Canon EOS-1D X", 0, 0x3c4e,
{ 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } },
{ "Canon EOS-1D", 0, 0xe20,
{ 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } },
{ "Canon EOS C500", 853, 0, /* DJC */
{ 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } },
{ "Canon PowerShot A530", 0, 0,
{ 0 } }, /* don't want the A5 matrix */
{ "Canon PowerShot A50", 0, 0,
{ -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } },
{ "Canon PowerShot A5", 0, 0,
{ -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } },
{ "Canon PowerShot G10", 0, 0,
{ 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } },
{ "Canon PowerShot G11", 0, 0,
{ 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } },
{ "Canon PowerShot G12", 0, 0,
{ 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } },
{ "Canon PowerShot G15", 0, 0,
{ 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } },
{ "Canon PowerShot G16", 0, 0,
{ 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } },
{ "Canon PowerShot G1 X Mark II", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1 X", 0, 0,
{ 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } },
{ "Canon PowerShot G1", 0, 0,
{ -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } },
{ "Canon PowerShot G2", 0, 0,
{ 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } },
{ "Canon PowerShot G3 X", 0, 0,
{ 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } },
{ "Canon PowerShot G3", 0, 0,
{ 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } },
{ "Canon PowerShot G5 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G5", 0, 0,
{ 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } },
{ "Canon PowerShot G6", 0, 0,
{ 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } },
{ "Canon PowerShot G7 X Mark II", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G7 X", 0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9 X",0, 0,
{ 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } },
{ "Canon PowerShot G9", 0, 0,
{ 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } },
{ "Canon PowerShot Pro1", 0, 0,
{ 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } },
{ "Canon PowerShot Pro70", 34, 0,
{ -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } },
{ "Canon PowerShot Pro90", 0, 0,
{ -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } },
{ "Canon PowerShot S30", 0, 0,
{ 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } },
{ "Canon PowerShot S40", 0, 0,
{ 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } },
{ "Canon PowerShot S45", 0, 0,
{ 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } },
{ "Canon PowerShot S50", 0, 0,
{ 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } },
{ "Canon PowerShot S60", 0, 0,
{ 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } },
{ "Canon PowerShot S70", 0, 0,
{ 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } },
{ "Canon PowerShot S90", 0, 0,
{ 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } },
{ "Canon PowerShot S95", 0, 0,
{ 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } },
{ "Canon PowerShot S120", 0, 0,
{ 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } },
{ "Canon PowerShot S110", 0, 0,
{ 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } },
{ "Canon PowerShot S100", 0, 0,
{ 7968,-2565,-636,-2873,10697,2513,180,667,4211 } },
{ "Canon PowerShot SX1 IS", 0, 0,
{ 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } },
{ "Canon PowerShot SX50 HS", 0, 0,
{ 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } },
{ "Canon PowerShot SX60 HS", 0, 0,
{ 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } },
{ "Canon PowerShot A3300", 0, 0, /* DJC */
{ 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } },
{ "Canon PowerShot A470", 0, 0, /* DJC */
{ 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } },
{ "Canon PowerShot A610", 0, 0, /* DJC */
{ 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } },
{ "Canon PowerShot A620", 0, 0, /* DJC */
{ 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } },
{ "Canon PowerShot A630", 0, 0, /* DJC */
{ 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } },
{ "Canon PowerShot A640", 0, 0, /* DJC */
{ 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } },
{ "Canon PowerShot A650", 0, 0, /* DJC */
{ 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } },
{ "Canon PowerShot A720", 0, 0, /* DJC */
{ 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } },
{ "Canon PowerShot S3 IS", 0, 0, /* DJC */
{ 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } },
{ "Canon PowerShot SX110 IS", 0, 0, /* DJC */
{ 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } },
{ "Canon PowerShot SX220", 0, 0, /* DJC */
{ 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } },
{ "Canon IXUS 160", 0, 0, /* DJC */
{ 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } },
{ "Casio EX-S20", 0, 0, /* DJC */
{ 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } },
{ "Casio EX-Z750", 0, 0, /* DJC */
{ 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } },
{ "Casio EX-Z10", 128, 0xfff, /* DJC */
{ 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } },
{ "CINE 650", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE 660", 0, 0,
{ 3390,480,-500,-800,3610,340,-550,2336,1192 } },
{ "CINE", 0, 0,
{ 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } },
{ "Contax N Digital", 0, 0xf1e,
{ 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } },
{ "DXO ONE", 0, 0,
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Epson R-D1", 0, 0,
{ 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } },
{ "Fujifilm E550", 0, 0,
{ 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } },
{ "Fujifilm E900", 0, 0,
{ 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } },
{ "Fujifilm F5", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F6", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F77", 0, 0xfe9,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm F7", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm F8", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm S100FS", 514, 0,
{ 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } },
{ "Fujifilm S1", 0, 0,
{ 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } },
{ "Fujifilm S20Pro", 0, 0,
{ 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } },
{ "Fujifilm S20", 512, 0x3fff,
{ 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } },
{ "Fujifilm S2Pro", 128, 0,
{ 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } },
{ "Fujifilm S3Pro", 0, 0,
{ 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } },
{ "Fujifilm S5Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm S5000", 0, 0,
{ 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } },
{ "Fujifilm S5100", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5500", 0, 0,
{ 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } },
{ "Fujifilm S5200", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S5600", 0, 0,
{ 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } },
{ "Fujifilm S6", 0, 0,
{ 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } },
{ "Fujifilm S7000", 0, 0,
{ 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } },
{ "Fujifilm S9000", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9500", 0, 0,
{ 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } },
{ "Fujifilm S9100", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm S9600", 0, 0,
{ 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } },
{ "Fujifilm SL1000", 0, 0,
{ 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } },
{ "Fujifilm IS-1", 0, 0,
{ 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } },
{ "Fujifilm IS Pro", 0, 0,
{ 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } },
{ "Fujifilm HS10 HS11", 0, 0xf68,
{ 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } },
{ "Fujifilm HS2", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS3", 0, 0,
{ 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } },
{ "Fujifilm HS50EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm F900EXR", 0, 0,
{ 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } },
{ "Fujifilm X100S", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100T", 0, 0,
{ 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } },
{ "Fujifilm X100", 0, 0,
{ 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } },
{ "Fujifilm X10", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X20", 0, 0,
{ 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } },
{ "Fujifilm X30", 0, 0,
{ 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } },
{ "Fujifilm X70", 0, 0,
{ 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } },
{ "Fujifilm X-Pro1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-Pro2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm X-A1", 0, 0,
{ 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } },
{ "Fujifilm X-A2", 0, 0,
{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
{ "Fujifilm X-E1", 0, 0,
{ 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } },
{ "Fujifilm X-E2S", 0, 0,
{ 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } },
{ "Fujifilm X-E2", 0, 0,
{ 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } },
{ "Fujifilm XF1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-M1", 0, 0,
{ 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } },
{ "Fujifilm X-S1", 0, 0,
{ 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } },
{ "Fujifilm X-T10", 0, 0,
{ 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } },
{ "Fujifilm X-T1", 0, 0,
{ 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } },
{ "Fujifilm X-T2", 0, 0,
{ 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } },
{ "Fujifilm XQ1", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "Fujifilm XQ2", 0, 0,
{ 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } },
{ "GITUP GIT2", 3200, 0,
{8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}},
{ "Hasselblad Lunar", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Hasselblad Stellar", -800, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Hasselblad CFV", 0, 0, /* Adobe */
{ 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } },
{ "Hasselblad H-16MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-22MP", 0, 0, /* LibRaw */
{ 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } },
{ "Hasselblad H-31MP",0, 0, /* LibRaw */
{ 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } },
{ "Hasselblad H-39MP",0, 0, /* Adobe */
{ 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } },
{ "Hasselblad H3D-50", 0, 0, /* Adobe */
{ 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } },
{ "Hasselblad H4D-40",0, 0, /* LibRaw */
{ 6325,-860,-957,-6559,15945,266,167,770,5936 } },
{ "Hasselblad H4D-50",0, 0, /* LibRaw */
{ 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } },
{ "Hasselblad H4D-60",0, 0, /* Adobe */
{ 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } },
{ "Hasselblad H5D-50c",0, 0, /* Adobe */
{ 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } },
{ "Hasselblad H5D-50",0, 0, /* Adobe */
{ 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } },
{ "Hasselblad X1D",0, 0, /* Adobe */
{4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }},
{ "HTC One A9", 64, 1023, /* this is CM1 transposed */
{ 101, -20, -2, -11, 145, 41, -24, 1, 56 } },
{ "Imacon Ixpress", 0, 0, /* DJC */
{ 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } },
{ "Kodak NC2000", 0, 0,
{ 13891,-6055,-803,-465,9919,642,2121,82,1291 } },
{ "Kodak DCS315C", -8, 0,
{ 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } },
{ "Kodak DCS330C", -8, 0,
{ 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } },
{ "Kodak DCS420", 0, 0,
{ 10868,-1852,-644,-1537,11083,484,2343,628,2216 } },
{ "Kodak DCS460", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS1", 0, 0,
{ 10592,-2206,-967,-1944,11685,230,2206,670,1273 } },
{ "Kodak EOSDCS3B", 0, 0,
{ 9898,-2700,-940,-2478,12219,206,1985,634,1031 } },
{ "Kodak DCS520C", -178, 0,
{ 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } },
{ "Kodak DCS560C", -177, 0,
{ 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } },
{ "Kodak DCS620C", -177, 0,
{ 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } },
{ "Kodak DCS620X", -176, 0,
{ 13095,-6231,154,12221,-21,-2137,895,4602,2258 } },
{ "Kodak DCS660C", -173, 0,
{ 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } },
{ "Kodak DCS720X", 0, 0,
{ 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } },
{ "Kodak DCS760C", 0, 0,
{ 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } },
{ "Kodak DCS Pro SLR", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14nx", 0, 0,
{ 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } },
{ "Kodak DCS Pro 14", 0, 0,
{ 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } },
{ "Kodak ProBack645", 0, 0,
{ 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } },
{ "Kodak ProBack", 0, 0,
{ 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } },
{ "Kodak P712", 0, 0,
{ 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } },
{ "Kodak P850", 0, 0xf7c,
{ 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } },
{ "Kodak P880", 0, 0xfff,
{ 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } },
{ "Kodak EasyShare Z980", 0, 0,
{ 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } },
{ "Kodak EasyShare Z981", 0, 0,
{ 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } },
{ "Kodak EasyShare Z990", 0, 0xfed,
{ 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } },
{ "Kodak EASYSHARE Z1015", 0, 0xef1,
{ 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } },
{ "Leaf CMost", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Valeo 6", 0, 0,
{ 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } },
{ "Leaf Aptus 54S", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Leaf Aptus 65", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Aptus 75", 0, 0,
{ 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } },
{ "Leaf Credo 40", 0, 0,
{ 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } },
{ "Leaf Credo 50", 0, 0,
{ 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } },
{ "Leaf Credo 60", 0, 0,
{ 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } },
{ "Leaf Credo 80", 0, 0,
{ 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } },
{ "Leaf", 0, 0,
{ 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } },
{ "Mamiya ZD", 0, 0,
{ 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } },
{ "Micron 2010", 110, 0, /* DJC */
{ 16695,-3761,-2151,155,9682,163,3433,951,4904 } },
{ "Minolta DiMAGE 5", 0, 0xf7d,
{ 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } },
{ "Minolta DiMAGE 7Hi", 0, 0xf7d,
{ 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } },
{ "Minolta DiMAGE 7", 0, 0xf7d,
{ 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } },
{ "Minolta DiMAGE A1", 0, 0xf8b,
{ 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } },
{ "Minolta DiMAGE A200", 0, 0,
{ 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } },
{ "Minolta DiMAGE A2", 0, 0xf8f,
{ 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } },
{ "Minolta DiMAGE Z2", 0, 0, /* DJC */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Minolta DYNAX 5", 0, 0xffb,
{ 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } },
{ "Minolta DYNAX 7", 0, 0xffb,
{ 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } },
{ "Motorola PIXL", 0, 0, /* DJC */
{ 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } },
{ "Nikon D100", 0, 0,
{ 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } },
{ "Nikon D1H", 0, 0,
{ 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } },
{ "Nikon D1X", 0, 0,
{ 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } },
{ "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */
{ 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } },
{ "Nikon D200", 0, 0xfbc,
{ 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } },
{ "Nikon D2H", 0, 0,
{ 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } },
{ "Nikon D2X", 0, 0,
{ 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } },
{ "Nikon D3000", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D3100", 0, 0,
{ 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } },
{ "Nikon D3200", 0, 0xfb9,
{ 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } },
{ "Nikon D3300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D3400", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D300", 0, 0,
{ 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } },
{ "Nikon D3X", 0, 0,
{ 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } },
{ "Nikon D3S", 0, 0,
{ 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } },
{ "Nikon D3", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D40X", 0, 0,
{ 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } },
{ "Nikon D40", 0, 0,
{ 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } },
{ "Nikon D4S", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D4", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon Df", 0, 0,
{ 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } },
{ "Nikon D5000", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } },
{ "Nikon D5100", 0, 0x3de6,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D5200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D5300", 0, 0,
{ 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } },
{ "Nikon D5500", 0, 0,
{ 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } },
{ "Nikon D500", 0, 0,
{ 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } },
{ "Nikon D50", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D5", 0, 0,
{ 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } },
{ "Nikon D600", 0, 0x3e07,
{ 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } },
{ "Nikon D610",0, 0,
{ 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } },
{ "Nikon D60", 0, 0,
{ 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } },
{ "Nikon D7000", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon D7100", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D7200", 0, 0,
{ 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } },
{ "Nikon D750", -600, 0,
{ 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } },
{ "Nikon D700", 0, 0,
{ 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } },
{ "Nikon D70", 0, 0,
{ 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } },
{ "Nikon D810A", 0, 0,
{ 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } },
{ "Nikon D810", 0, 0,
{ 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } },
{ "Nikon D800", 0, 0,
{ 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } },
{ "Nikon D80", 0, 0,
{ 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } },
{ "Nikon D90", 0, 0xf00,
{ 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } },
{ "Nikon E700", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E800", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E950", 0, 0x3dd, /* DJC */
{ -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } },
{ "Nikon E995", 0, 0, /* copied from E5000 */
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E2100", 0, 0, /* copied from Z2, new white balance */
{ 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } },
{ "Nikon E2500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E3200", 0, 0, /* DJC */
{ 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } },
{ "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */
{ 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } },
{ "Nikon E4500", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5000", 0, 0,
{ -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } },
{ "Nikon E5400", 0, 0,
{ 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } },
{ "Nikon E5700", 0, 0,
{ -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } },
{ "Nikon E8400", 0, 0,
{ 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } },
{ "Nikon E8700", 0, 0,
{ 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } },
{ "Nikon E8800", 0, 0,
{ 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } },
{ "Nikon COOLPIX A", 0, 0,
{ 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } },
{ "Nikon COOLPIX B700", 0, 0,
{ 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } },
{ "Nikon COOLPIX P330", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P340", -200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P6000", 0, 0,
{ 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } },
{ "Nikon COOLPIX P7000", 0, 0,
{ 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } },
{ "Nikon COOLPIX P7100", 0, 0,
{ 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } },
{ "Nikon COOLPIX P7700", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon COOLPIX P7800", -3200, 0,
{ 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } },
{ "Nikon 1 V3", -200, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J4", 0, 0,
{ 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } },
{ "Nikon 1 J5", 0, 0,
{ 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} },
{ "Nikon 1 S2", -200, 0,
{ 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } },
{ "Nikon 1 V2", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 J3", 0, 0,
{ 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } },
{ "Nikon 1 AW1", 0, 0,
{ 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } },
{ "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */
{ 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } },
{ "Olympus AIR-A01", 0, 0xfe1,
{ 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } },
{ "Olympus C5050", 0, 0,
{ 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } },
{ "Olympus C5060", 0, 0,
{ 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } },
{ "Olympus C7070", 0, 0,
{ 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } },
{ "Olympus C70", 0, 0,
{ 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } },
{ "Olympus C80", 0, 0,
{ 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } },
{ "Olympus E-10", 0, 0xffc,
{ 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } },
{ "Olympus E-1", 0, 0,
{ 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } },
{ "Olympus E-20", 0, 0xffc,
{ 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } },
{ "Olympus E-300", 0, 0,
{ 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } },
{ "Olympus E-330", 0, 0,
{ 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } },
{ "Olympus E-30", 0, 0xfbc,
{ 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } },
{ "Olympus E-3", 0, 0xf99,
{ 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } },
{ "Olympus E-400", 0, 0,
{ 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } },
{ "Olympus E-410", 0, 0xf6a,
{ 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } },
{ "Olympus E-420", 0, 0xfd7,
{ 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } },
{ "Olympus E-450", 0, 0xfd2,
{ 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } },
{ "Olympus E-500", 0, 0,
{ 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } },
{ "Olympus E-510", 0, 0xf6a,
{ 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } },
{ "Olympus E-520", 0, 0xfd2,
{ 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } },
{ "Olympus E-5", 0, 0xeec,
{ 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } },
{ "Olympus E-600", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-620", 0, 0xfaf,
{ 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } },
{ "Olympus E-P1", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P2", 0, 0xffd,
{ 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } },
{ "Olympus E-P3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-P5", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL1s", 0, 0,
{ 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } },
{ "Olympus E-PL1", 0, 0,
{ 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } },
{ "Olympus E-PL2", 0, 0xcf3,
{ 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } },
{ "Olympus E-PL3", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PL5", 0, 0xfcb,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL6", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-PL7", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PL8", 0, 0,
{ 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } },
{ "Olympus E-PM1", 0, 0,
{ 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } },
{ "Olympus E-PM2", 0, 0,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus E-M1MarkII", 0, 0, /* Adobe */
{ 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }},
{ "Olympus E-M1", 0, 0,
{ 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } },
{ "Olympus E-M5MarkII", 0, 0,
{ 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } },
{ "Olympus E-M5", 0, 0xfe1,
{ 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } },
{ "Olympus PEN-F",0, 0,
{ 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } },
{ "Olympus SP350", 0, 0,
{ 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } },
{ "Olympus SP3", 0, 0,
{ 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } },
{ "Olympus SP500UZ", 0, 0xfff,
{ 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } },
{ "Olympus SP510UZ", 0, 0xffe,
{ 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } },
{ "Olympus SP550UZ", 0, 0xffe,
{ 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } },
{ "Olympus SP560UZ", 0, 0xff9,
{ 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } },
{ "Olympus SP570UZ", 0, 0,
{ 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } },
{ "Olympus SH-2", 0, 0,
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus SH-3", 0, 0, /* Alias of SH-2 */
{ 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } },
{ "Olympus STYLUS1",0, 0,
{ 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } },
{ "Olympus TG-4", 0, 0,
{ 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } },
{ "Olympus XZ-10", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "Olympus XZ-1", 0, 0,
{ 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } },
{ "Olympus XZ-2", 0, 0,
{ 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } },
{ "OmniVision", 16, 0x3ff,
{ 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */
{ "Pentax *ist DL2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DL", 0, 0,
{ 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } },
{ "Pentax *ist DS2", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Pentax *ist DS", 0, 0,
{ 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } },
{ "Pentax *ist D", 0, 0,
{ 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } },
{ "Pentax K10D", 0, 0,
{ 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } },
{ "Pentax K1", 0, 0,
{ 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } },
{ "Pentax K20D", 0, 0,
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Pentax K200D", 0, 0,
{ 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } },
{ "Pentax K2000", 0, 0,
{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
{ "Pentax K-m", 0, 0,
{ 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } },
{ "Pentax K-x", 0, 0,
{ 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } },
{ "Pentax K-r", 0, 0,
{ 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } },
{ "Pentax K-1", 0, 0,
{ 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } },
{ "Pentax K-30", 0, 0,
{ 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } },
{ "Pentax K-3 II", 0, 0,
{ 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } },
{ "Pentax K-3", 0, 0,
{ 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } },
{ "Pentax K-5 II", 0, 0,
{ 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } },
{ "Pentax K-5", 0, 0,
{ 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } },
{ "Pentax K-70", 0, 0,
{8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }},
{ "Pentax K-7", 0, 0,
{ 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } },
{ "Pentax K-S1", 0, 0,
{ 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } },
{ "Pentax K-S2", 0, 0,
{ 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } },
{ "Pentax Q-S1", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax MX-1", 0, 0,
{ 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } },
{ "Pentax Q10", 0, 0,
{ 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } },
{ "Pentax 645D", 0, 0x3e00,
{ 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } },
{ "Pentax 645Z", 0, 0, /* Adobe */
{ 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}},
{ "Panasonic DMC-CM10", -15, 0,
{ 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-CM1", -15, 0,
{ 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } },
{ "Panasonic DMC-FZ8", 0, 0xf7f,
{ 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } },
{ "Panasonic DMC-FZ18", 0, 0,
{ 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } },
{ "Panasonic DMC-FZ28", -15, 0xf96,
{ 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } },
{ "Panasonic DMC-FZ300", -15, 0xfff,
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300
{ 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } },
{ "Panasonic DMC-FZ30", 0, 0xf94,
{ 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } },
{ "Panasonic DMC-FZ3", -15, 0,
{ 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } },
{ "Panasonic DMC-FZ4", -15, 0,
{ 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } },
{ "Panasonic DMC-FZ50", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-FZ7", -15, 0,
{ 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } },
{ "Leica V-LUX1", 0, 0,
{ 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } },
{ "Panasonic DMC-L10", -15, 0xf96,
{ 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } },
{ "Panasonic DMC-L1", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Leica DIGILUX 3", 0, 0xf7f,
{ 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } },
{ "Panasonic DMC-LC1", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Leica DIGILUX 2", 0, 0,
{ 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } },
{ "Panasonic DMC-LX100", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX (Typ 109)", -15, 0,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Panasonic DMC-LF1", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Leica C (Typ 112)", -15, 0,
{ 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } },
{ "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/
{ "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/
{ "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */
{ 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/
{ "Panasonic DMC-LX1", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Leica D-Lux (Typ 109)", 0, 0xf7f,
{ 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } },
{ "Leica D-LUX2", 0, 0xf7f,
{ 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } },
{ "Panasonic DMC-LX2", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Leica D-LUX3", 0, 0,
{ 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } },
{ "Panasonic DMC-LX3", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Leica D-LUX 4", -15, 0,
{ 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } },
{ "Panasonic DMC-LX5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Leica D-LUX 5", -15, 0,
{ 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } },
{ "Panasonic DMC-LX7", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Leica D-LUX 6", -15, 0,
{ 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } },
{ "Panasonic DMC-FZ1000", -15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Leica V-LUX (Typ 114)", 15, 0,
{ 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } },
{ "Panasonic DMC-FZ100", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Leica V-LUX 2", -15, 0xfff,
{ 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } },
{ "Panasonic DMC-FZ150", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Leica V-LUX 3", -15, 0xfff,
{ 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } },
{ "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */
{ 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }},
{ "Panasonic DMC-FZ2500", -15, 0,
{ 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }},
{ "Panasonic DMC-FZH1", -15, 0,
{ 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }},
{ "Panasonic DMC-FZ200", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Leica V-LUX 4", -15, 0xfff,
{ 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } },
{ "Panasonic DMC-FX150", -15, 0xfff,
{ 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } },
{ "Panasonic DMC-G10", 0, 0,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G1", -15, 0xf94,
{ 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } },
{ "Panasonic DMC-G2", -15, 0xf3c,
{ 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } },
{ "Panasonic DMC-G3", -15, 0xfff,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-G5", -15, 0xfff,
{ 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } },
{ "Panasonic DMC-G6", -15, 0xfff,
{ 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } },
{ "Panasonic DMC-G7", -15, 0xfff,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GF1", -15, 0xf92,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF2", -15, 0xfff,
{ 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } },
{ "Panasonic DMC-GF3", -15, 0xfff,
{ 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } },
{ "Panasonic DMC-GF5", -15, 0xfff,
{ 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } },
{ "Panasonic DMC-GF6", -15, 0,
{ 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } },
{ "Panasonic DMC-GF7", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GF8", -15, 0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GH1", -15, 0xf92,
{ 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } },
{ "Panasonic DMC-GH2", -15, 0xf95,
{ 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } },
{ "Panasonic DMC-GH3", -15, 0,
{ 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } },
{ "Panasonic DMC-GH4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Yuneec CGO4", -15, 0,
{ 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } },
{ "Panasonic DMC-GM1", -15, 0,
{ 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } },
{ "Panasonic DMC-GM5", -15, 0,
{ 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } },
{ "Panasonic DMC-GX1", -15, 0,
{ 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } },
{ "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */
{ 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } },
{ "Panasonic DMC-GX7", -15,0,
{ 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } },
{ "Panasonic DMC-GX8", -15,0,
{ 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } },
{ "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */
{ 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } },
{ "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */
{ 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } },
{ "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */
{ 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } },
{ "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */
{ 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } },
{ "Leica S (Typ 007)", 0, 0,
{ 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } },
{ "Leica X", 0, 0, /* X and X-U, both (Typ 113) */
{ 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } },
{ "Leica Q (Typ 116)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } },
{ "Leica M (Typ 262)", 0, 0,
{ 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } },
{ "Leica SL (Typ 601)", 0, 0,
{ 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} },
{ "Phase One H 20", 0, 0, /* DJC */
{ 1313,1855,-109,-6715,15908,808,-327,1840,6020 } },
{ "Phase One H 25", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One IQ250",0, 0,
{ 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } },
{ "Phase One P 2", 0, 0,
{ 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } },
{ "Phase One P 30", 0, 0,
{ 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } },
{ "Phase One P 45", 0, 0,
{ 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } },
{ "Phase One P40", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Phase One P65", 0, 0,
{ 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } },
{ "Photron BC2-HD", 0, 0, /* DJC */
{ 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } },
{ "Red One", 704, 0xffff, /* DJC */
{ 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } },
{ "Ricoh GR II", 0, 0,
{ 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } },
{ "Ricoh GR", 0, 0,
{ 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } },
{ "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung EX1", 0, 0x3e00,
{ 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } },
{ "Samsung EX2F", 0, 0x7ff,
{ 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } },
{ "Samsung NX mini", 0, 0,
{ 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } },
{ "Samsung NX3300", 0, 0, /* same as NX3000 */
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX3000", 0, 0,
{ 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } },
{ "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2000", 0, 0,
{ 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } },
{ "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1000", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX1100", 0, 0,
{ 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } },
{ "Samsung NX11", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX10", 0, 0, /* also NX100 */
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX500", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung NX5", 0, 0,
{ 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } },
{ "Samsung NX1", 0, 0,
{ 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } },
{ "Samsung WB2000", 0, 0xfff,
{ 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } },
{ "Samsung GX-1", 0, 0,
{ 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } },
{ "Samsung GX20", 0, 0, /* copied from Pentax K20D */
{ 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } },
{ "Samsung S85", 0, 0, /* DJC */
{ 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } },
// Foveon: LibRaw color data
{ "Sigma dp0 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp1 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp2 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma dp3 Quattro", 2047, 0,
{ 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } },
{ "Sigma sd Quattro H", 256, 0,
{1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */
{ "Sigma sd Quattro", 2047, 0,
{1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */
{ "Sigma SD9", 15, 4095, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD10", 15, 16383, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD14", 15, 16383, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
{ "Sigma SD15", 15, 4095, /* LibRaw */
{ 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } },
// Merills + SD1
{ "Sigma SD1", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP1 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP2 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
{ "Sigma DP3 Merrill", 31, 4095, /* LibRaw */
{ 5133,-1895,-353,4978,744,144,3837,3069,2777 } },
// Sigma DP (non-Merill Versions)
{ "Sigma DP", 0, 4095, /* LibRaw */
// { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } },
{ 13100,-3638,-847,6855,2369,580,2723,3218,3251 } },
{ "Sinar", 0, 0, /* DJC */
{ 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } },
{ "Sony DSC-F828", 0, 0,
{ 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } },
{ "Sony DSC-R1", 0, 0,
{ 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } },
{ "Sony DSC-V3", 0, 0,
{ 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } },
{"Sony DSC-RX100M5", -800, 0, /* Adobe */
{6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }},
{ "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */
{ 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } },
{ "Sony DSC-RX100", 0, 0,
{ 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } },
{ "Sony DSC-RX10",0, 0, /* And M2/M3 too */
{ 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } },
{ "Sony DSC-RX1RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony DSC-RX1R", 0, 0,
{ 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } },
{ "Sony DSC-RX1", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
{ "Sony DSLR-A100", 0, 0xfeb,
{ 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } },
{ "Sony DSLR-A290", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A2", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A300", 0, 0,
{ 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } },
{ "Sony DSLR-A330", 0, 0,
{ 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } },
{ "Sony DSLR-A350", 0, 0xffc,
{ 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } },
{ "Sony DSLR-A380", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A390", 0, 0,
{ 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } },
{ "Sony DSLR-A450", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A580", 0, 0xfeb,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony DSLR-A500", 0, 0xfeb,
{ 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } },
{ "Sony DSLR-A5", 0, 0xfeb,
{ 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } },
{ "Sony DSLR-A700", 0, 0,
{ 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } },
{ "Sony DSLR-A850", 0, 0,
{ 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } },
{ "Sony DSLR-A900", 0, 0,
{ 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } },
{ "Sony ILCA-68", 0, 0,
{ 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } },
{ "Sony ILCA-77M2", 0, 0,
{ 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } },
{ "Sony ILCA-99M2", 0, 0, /* Adobe */
{ 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}},
{ "Sony ILCE-7M2", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-7SM2", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7S", 0, 0,
{ 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } },
{ "Sony ILCE-7RM2", 0, 0,
{ 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } },
{ "Sony ILCE-7R", 0, 0,
{ 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } },
{ "Sony ILCE-7", 0, 0,
{ 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } },
{ "Sony ILCE-6300", 0, 0,
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE-6500", 0, 0, /* Adobe */
{ 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } },
{ "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5N", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony NEX-5R", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-5T", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3N", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-3", 0, 0, /* Adobe */
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-5", 0, 0, /* Adobe */
{ 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } },
{ "Sony NEX-6", 0, 0,
{ 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } },
{ "Sony NEX-7", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A33", 0, 0,
{ 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } },
{ "Sony SLT-A35", 0, 0,
{ 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } },
{ "Sony SLT-A37", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A55", 0, 0,
{ 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } },
{ "Sony SLT-A57", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A58", 0, 0,
{ 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } },
{ "Sony SLT-A65", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A77", 0, 0,
{ 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } },
{ "Sony SLT-A99", 0, 0,
{ 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } },
};
double cam_xyz[4][3];
char name[130];
int i, j;
if(colors>4 || colors < 1) return;
int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0;
if(cblack[4]*cblack[5]>0)
{
for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++)
bl64+=cblack[c+6];
bl64 /= cblack[4]*cblack[5];
}
int rblack = black+bl4+bl64;
sprintf (name, "%s %s", t_make, t_model);
for (i=0; i < sizeof table / sizeof *table; i++)
if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) {
if(!dng_version)
{
if (table[i].t_black>0)
{
black = (ushort) table[i].t_black;
memset(cblack,0,sizeof(cblack));
}
else if(table[i].t_black <0 && rblack == 0 )
{
black = (ushort) (-table[i].t_black);
memset(cblack,0,sizeof(cblack));
}
if (table[i].t_maximum)
maximum = (ushort) table[i].t_maximum;
}
if (table[i].trans[0]) {
for (raw_color = j=0; j < 12; j++)
#ifdef LIBRAW_LIBRARY_BUILD
if(internal_only)
imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0;
else
imgdata.color.cam_xyz[0][j] =
#endif
((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0;
#ifdef LIBRAW_LIBRARY_BUILD
if(!internal_only)
#endif
cam_xyz_coeff (rgb_cam, cam_xyz);
}
break;
}
}
void CLASS simple_coeff (int index)
{
static const float table[][12] = {
/* index 0 -- all Foveon cameras */
{ 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 },
/* index 1 -- Kodak DC20 and DC25 */
{ 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 },
/* index 2 -- Logitech Fotoman Pixtura */
{ 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 },
/* index 3 -- Nikon E880, E900, and E990 */
{ -1.936280, 1.800443, -1.448486, 2.584324,
1.405365, -0.524955, -0.289090, 0.408680,
-1.204965, 1.082304, 2.941367, -1.818705 }
};
int i, c;
for (raw_color = i=0; i < 3; i++)
FORCC rgb_cam[i][c] = table[index][i*colors+c];
}
short CLASS guess_byte_order (int words)
{
uchar test[4][2];
int t=2, msb;
double diff, sum[2] = {0,0};
fread (test[0], 2, 2, ifp);
for (words-=2; words--; ) {
fread (test[t], 2, 1, ifp);
for (msb=0; msb < 2; msb++) {
diff = (test[t^2][msb] << 8 | test[t^2][!msb])
- (test[t ][msb] << 8 | test[t ][!msb]);
sum[msb] += diff*diff;
}
t = (t+1) & 3;
}
return sum[0] < sum[1] ? 0x4d4d : 0x4949;
}
float CLASS find_green (int bps, int bite, int off0, int off1)
{
UINT64 bitbuf=0;
int vbits, col, i, c;
ushort img[2][2064];
double sum[]={0,0};
FORC(2) {
fseek (ifp, c ? off1:off0, SEEK_SET);
for (vbits=col=0; col < width; col++) {
for (vbits -= bps; vbits < 0; vbits += bite) {
bitbuf <<= bite;
for (i=0; i < bite; i+=8)
bitbuf |= (unsigned) (fgetc(ifp) << i);
}
img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps);
}
}
FORC(width-1) {
sum[ c & 1] += ABS(img[0][c]-img[1][c+1]);
sum[~c & 1] += ABS(img[1][c]-img[0][c+1]);
}
return 100 * log(sum[0]/sum[1]);
}
#ifdef LIBRAW_LIBRARY_BUILD
static void remove_trailing_spaces(char *string, size_t len)
{
if(len<1) return; // not needed, b/c sizeof of make/model is 64
string[len-1]=0;
if(len<3) return; // also not needed
len = strnlen(string,len-1);
for(int i=len-1; i>=0; i--)
{
if(isspace(string[i]))
string[i]=0;
else
break;
}
}
#endif
/*
Identify which camera created this file, and set global variables
accordingly.
*/
void CLASS identify()
{
static const short pana[][6] = {
{ 3130, 1743, 4, 0, -6, 0 },
{ 3130, 2055, 4, 0, -6, 0 },
{ 3130, 2319, 4, 0, -6, 0 },
{ 3170, 2103, 18, 0,-42, 20 },
{ 3170, 2367, 18, 13,-42,-21 },
{ 3177, 2367, 0, 0, -1, 0 },
{ 3304, 2458, 0, 0, -1, 0 },
{ 3330, 2463, 9, 0, -5, 0 },
{ 3330, 2479, 9, 0,-17, 4 },
{ 3370, 1899, 15, 0,-44, 20 },
{ 3370, 2235, 15, 0,-44, 20 },
{ 3370, 2511, 15, 10,-44,-21 },
{ 3690, 2751, 3, 0, -8, -3 },
{ 3710, 2751, 0, 0, -3, 0 },
{ 3724, 2450, 0, 0, 0, -2 },
{ 3770, 2487, 17, 0,-44, 19 },
{ 3770, 2799, 17, 15,-44,-19 },
{ 3880, 2170, 6, 0, -6, 0 },
{ 4060, 3018, 0, 0, 0, -2 },
{ 4290, 2391, 3, 0, -8, -1 },
{ 4330, 2439, 17, 15,-44,-19 },
{ 4508, 2962, 0, 0, -3, -4 },
{ 4508, 3330, 0, 0, -3, -6 },
};
static const ushort canon[][11] = {
{ 1944, 1416, 0, 0, 48, 0 },
{ 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 },
{ 2224, 1456, 48, 6, 0, 2 },
{ 2376, 1728, 12, 6, 52, 2 },
{ 2672, 1968, 12, 6, 44, 2 },
{ 3152, 2068, 64, 12, 0, 0, 16 },
{ 3160, 2344, 44, 12, 4, 4 },
{ 3344, 2484, 4, 6, 52, 6 },
{ 3516, 2328, 42, 14, 0, 0 },
{ 3596, 2360, 74, 12, 0, 0 },
{ 3744, 2784, 52, 12, 8, 12 },
{ 3944, 2622, 30, 18, 6, 2 },
{ 3948, 2622, 42, 18, 0, 2 },
{ 3984, 2622, 76, 20, 0, 2, 14 },
{ 4104, 3048, 48, 12, 24, 12 },
{ 4116, 2178, 4, 2, 0, 0 },
{ 4152, 2772, 192, 12, 0, 0 },
{ 4160, 3124, 104, 11, 8, 65 },
{ 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 },
{ 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 },
{ 4312, 2876, 22, 18, 0, 2 },
{ 4352, 2874, 62, 18, 0, 0 },
{ 4476, 2954, 90, 34, 0, 0 },
{ 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 },
{ 4480, 3366, 80, 50, 0, 0 },
{ 4496, 3366, 80, 50, 12, 0 },
{ 4768, 3516, 96, 16, 0, 0, 0, 16 },
{ 4832, 3204, 62, 26, 0, 0 },
{ 4832, 3228, 62, 51, 0, 0 },
{ 5108, 3349, 98, 13, 0, 0 },
{ 5120, 3318, 142, 45, 62, 0 },
{ 5280, 3528, 72, 52, 0, 0 }, /* EOS M */
{ 5344, 3516, 142, 51, 0, 0 },
{ 5344, 3584, 126,100, 0, 2 },
{ 5360, 3516, 158, 51, 0, 0 },
{ 5568, 3708, 72, 38, 0, 0 },
{ 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 },
{ 5712, 3774, 62, 20, 10, 2 },
{ 5792, 3804, 158, 51, 0, 0 },
{ 5920, 3950, 122, 80, 2, 0 },
{ 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */
{ 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */
{ 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */
{ 8896, 5920, 160, 64, 0, 0 },
};
static const struct {
ushort id;
char t_model[20];
} unique[] = {
{ 0x001, "EOS-1D" },
{ 0x167, "EOS-1DS" },
{ 0x168, "EOS 10D" },
{ 0x169, "EOS-1D Mark III" },
{ 0x170, "EOS 300D" },
{ 0x174, "EOS-1D Mark II" },
{ 0x175, "EOS 20D" },
{ 0x176, "EOS 450D" },
{ 0x188, "EOS-1Ds Mark II" },
{ 0x189, "EOS 350D" },
{ 0x190, "EOS 40D" },
{ 0x213, "EOS 5D" },
{ 0x215, "EOS-1Ds Mark III" },
{ 0x218, "EOS 5D Mark II" },
{ 0x232, "EOS-1D Mark II N" },
{ 0x234, "EOS 30D" },
{ 0x236, "EOS 400D" },
{ 0x250, "EOS 7D" },
{ 0x252, "EOS 500D" },
{ 0x254, "EOS 1000D" },
{ 0x261, "EOS 50D" },
{ 0x269, "EOS-1D X" },
{ 0x270, "EOS 550D" },
{ 0x281, "EOS-1D Mark IV" },
{ 0x285, "EOS 5D Mark III" },
{ 0x286, "EOS 600D" },
{ 0x287, "EOS 60D" },
{ 0x288, "EOS 1100D" },
{ 0x289, "EOS 7D Mark II" },
{ 0x301, "EOS 650D" },
{ 0x302, "EOS 6D" },
{ 0x324, "EOS-1D C" },
{ 0x325, "EOS 70D" },
{ 0x326, "EOS 700D" },
{ 0x327, "EOS 1200D" },
{ 0x328, "EOS-1D X Mark II" },
{ 0x331, "EOS M" },
{ 0x335, "EOS M2" },
{ 0x374, "EOS M3"}, /* temp */
{ 0x384, "EOS M10"}, /* temp */
{ 0x394, "EOS M5"}, /* temp */
{ 0x346, "EOS 100D" },
{ 0x347, "EOS 760D" },
{ 0x349, "EOS 5D Mark IV" },
{ 0x350, "EOS 80D"},
{ 0x382, "EOS 5DS" },
{ 0x393, "EOS 750D" },
{ 0x401, "EOS 5DS R" },
{ 0x404, "EOS 1300D" },
}, sonique[] = {
{ 0x002, "DSC-R1" },
{ 0x100, "DSLR-A100" },
{ 0x101, "DSLR-A900" },
{ 0x102, "DSLR-A700" },
{ 0x103, "DSLR-A200" },
{ 0x104, "DSLR-A350" },
{ 0x105, "DSLR-A300" },
{ 0x106, "DSLR-A900" },
{ 0x107, "DSLR-A380" },
{ 0x108, "DSLR-A330" },
{ 0x109, "DSLR-A230" },
{ 0x10a, "DSLR-A290" },
{ 0x10d, "DSLR-A850" },
{ 0x10e, "DSLR-A850" },
{ 0x111, "DSLR-A550" },
{ 0x112, "DSLR-A500" },
{ 0x113, "DSLR-A450" },
{ 0x116, "NEX-5" },
{ 0x117, "NEX-3" },
{ 0x118, "SLT-A33" },
{ 0x119, "SLT-A55V" },
{ 0x11a, "DSLR-A560" },
{ 0x11b, "DSLR-A580" },
{ 0x11c, "NEX-C3" },
{ 0x11d, "SLT-A35" },
{ 0x11e, "SLT-A65V" },
{ 0x11f, "SLT-A77V" },
{ 0x120, "NEX-5N" },
{ 0x121, "NEX-7" },
{ 0x122, "NEX-VG20E"},
{ 0x123, "SLT-A37" },
{ 0x124, "SLT-A57" },
{ 0x125, "NEX-F3" },
{ 0x126, "SLT-A99V" },
{ 0x127, "NEX-6" },
{ 0x128, "NEX-5R" },
{ 0x129, "DSC-RX100" },
{ 0x12a, "DSC-RX1" },
{ 0x12b, "NEX-VG900" },
{ 0x12c, "NEX-VG30E" },
{ 0x12e, "ILCE-3000" },
{ 0x12f, "SLT-A58" },
{ 0x131, "NEX-3N" },
{ 0x132, "ILCE-7" },
{ 0x133, "NEX-5T" },
{ 0x134, "DSC-RX100M2" },
{ 0x135, "DSC-RX10" },
{ 0x136, "DSC-RX1R" },
{ 0x137, "ILCE-7R" },
{ 0x138, "ILCE-6000" },
{ 0x139, "ILCE-5000" },
{ 0x13d, "DSC-RX100M3" },
{ 0x13e, "ILCE-7S" },
{ 0x13f, "ILCA-77M2" },
{ 0x153, "ILCE-5100" },
{ 0x154, "ILCE-7M2" },
{ 0x155, "DSC-RX100M4" },
{ 0x156, "DSC-RX10M2" },
{ 0x158, "DSC-RX1RM2" },
{ 0x15a, "ILCE-QX1" },
{ 0x15b, "ILCE-7RM2" },
{ 0x15e, "ILCE-7SM2" },
{ 0x161, "ILCA-68" },
{ 0x162, "ILCA-99M2" },
{ 0x163, "DSC-RX10M3" },
{ 0x164, "DSC-RX100M5"},
{ 0x165, "ILCE-6300" },
{ 0x168, "ILCE-6500"},
};
#ifdef LIBRAW_LIBRARY_BUILD
static const libraw_custom_camera_t
const_table[]
#else
static const struct {
unsigned fsize;
ushort rw, rh;
uchar lm, tm, rm, bm, lf, cf, max, flags;
char t_make[10], t_model[20];
ushort offset;
}
table[]
#endif
= {
{ 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" },
{ 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" },
{ 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" },
{ 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" },
{ 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 },
{ 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" },
{ 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 },
{ 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" },
{ 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" },
{ 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" },
{ 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" },
{ 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" },
// Android Raw dumps id start
// File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb
{ 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" },
{ 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" },
{ 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" },
{ 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" },
{ 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" },
{ 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" },
{ 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" },
{ 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" },
{ 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" },
{ 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" },
{ 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" },
{ 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" },
{ 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" },
{ 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" },
{ 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" },
{ 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" },
{ 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" },
{ 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" },
{ 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" },
{ 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" },
{ 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" },
{ 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" },
{ 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" },
{ 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" },
{ 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" },
{ 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" },
{ 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" },
{ 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" },
{ 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" },
{ 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" },
{ 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" },
{ 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" },
{ 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" },
{ 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" },
{ 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" },
// Android Raw dumps id end
{ 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff },
{ 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 },
{ 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" },
{ 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" },
{ 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" },
{ 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" },
{ 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" },
{ 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" },
{ 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" },
{ 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" },
{ 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" },
{ 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" },
{ 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" },
{ 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" },
{ 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" },
{ 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" },
{ 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" },
{ 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" },
{ 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" },
{ 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" },
{ 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" },
{ 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" },
{ 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" },
{ 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" },
{ 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" },
{ 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" },
{ 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" },
{ 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" },
{ 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" },
{ 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" },
{ 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" },
{ 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" },
{ 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" },
{ 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" },
{ 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" },
{ 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" },
{ 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" },
{ 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" },
{ 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" },
{ 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" },
{ 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" },
{ 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" },
{ 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" },
{ 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" },
{ 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" },
{ 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" },
{ 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" },
{ 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" },
{ 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" },
{ 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" },
{ 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 },
{ 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
{ 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" },
{ 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" },
{ 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 },
{ 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
{ 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" },
{ 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" },
{ 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 },
{ 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" },
{ 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" },
{ 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" },
{ 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 },
{ 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 },
{ 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" },
{ 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" },
{ 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" },
{ 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" },
{ 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" },
{ 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" },
{ 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" },
{ 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" },
{ 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" },
{ 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" },
{ 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" },
{ 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" },
{ 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" },
{ 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" },
{ 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" },
{ 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 },
{ 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" },
{ 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" },
{ 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" },
{ 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" },
{ 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" },
{ 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
{ 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" },
{ 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 },
{ 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" },
{ 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" },
};
#ifdef LIBRAW_LIBRARY_BUILD
libraw_custom_camera_t
table[64 + sizeof(const_table)/sizeof(const_table[0])];
#endif
static const char *corp[] =
{ "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm",
"Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica",
"Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh",
"Samsung", "Sigma", "Sinar", "Sony" };
#ifdef LIBRAW_LIBRARY_BUILD
char head[64], *cp;
#else
char head[32], *cp;
#endif
int hlen, flen, fsize, zero_fsize=1, i, c;
struct jhead jh;
#ifdef LIBRAW_LIBRARY_BUILD
unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings);
for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++)
memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0]));
camera_count += sizeof(const_table)/sizeof(const_table[0]);
#endif
tiff_flip = flip = filters = UINT_MAX; /* unknown */
raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0;
maximum = height = width = top_margin = left_margin = 0;
cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0;
iso_speed = shutter = aperture = focal_len = unique_id = 0;
tiff_nifds = 0;
memset (tiff_ifd, 0, sizeof tiff_ifd);
memset (gpsdata, 0, sizeof gpsdata);
memset (cblack, 0, sizeof cblack);
memset (white, 0, sizeof white);
memset (mask, 0, sizeof mask);
thumb_offset = thumb_length = thumb_width = thumb_height = 0;
load_raw = thumb_load_raw = 0;
write_thumb = &CLASS jpeg_thumb;
data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0;
kodak_cbpp = zero_after_ff = dng_version = load_flags = 0;
timestamp = shot_order = tiff_samples = black = is_foveon = 0;
mix_green = profile_length = data_error = zero_is_bad = 0;
pixel_aspect = is_raw = raw_color = 1;
tile_width = tile_length = 0;
for (i=0; i < 4; i++) {
cam_mul[i] = i == 1;
pre_mul[i] = i < 3;
FORC3 cmatrix[c][i] = 0;
FORC3 rgb_cam[c][i] = c == i;
}
colors = 3;
for (i=0; i < 0x10000; i++) curve[i] = i;
order = get2();
hlen = get4();
fseek (ifp, 0, SEEK_SET);
#ifdef LIBRAW_LIBRARY_BUILD
fread (head, 1, 64, ifp);
libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0;
#else
fread (head, 1, 32, ifp);
#endif
fseek (ifp, 0, SEEK_END);
flen = fsize = ftell(ifp);
if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) ||
(cp = (char *) memmem (head, 32, (char*)"IIII", 4))) {
parse_phase_one (cp-head);
if (cp-head && parse_tiff(0)) apply_tiff();
} else if (order == 0x4949 || order == 0x4d4d) {
if (!memcmp (head+6,"HEAPCCDR",8)) {
data_offset = hlen;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
#endif
parse_ciff (hlen, flen-hlen, 0);
load_raw = &CLASS canon_load_raw;
} else if (parse_tiff(0)) apply_tiff();
} else if (!memcmp (head,"\xff\xd8\xff\xe1",4) &&
!memcmp (head+6,"Exif",4)) {
fseek (ifp, 4, SEEK_SET);
data_offset = 4 + get2();
fseek (ifp, data_offset, SEEK_SET);
if (fgetc(ifp) != 0xff)
parse_tiff(12);
thumb_offset = 0;
} else if (!memcmp (head+25,"ARECOYK",7)) {
strcpy (make, "Contax");
strcpy (model,"N Digital");
fseek (ifp, 33, SEEK_SET);
get_timestamp(1);
fseek (ifp, 52, SEEK_SET);
switch (get4()) {
case 7: iso_speed = 25; break;
case 8: iso_speed = 32; break;
case 9: iso_speed = 40; break;
case 10: iso_speed = 50; break;
case 11: iso_speed = 64; break;
case 12: iso_speed = 80; break;
case 13: iso_speed = 100; break;
case 14: iso_speed = 125; break;
case 15: iso_speed = 160; break;
case 16: iso_speed = 200; break;
case 17: iso_speed = 250; break;
case 18: iso_speed = 320; break;
case 19: iso_speed = 400; break;
}
shutter = powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f;
FORC4 cam_mul[c ^ (c >> 1)] = get4();
fseek (ifp, 88, SEEK_SET);
aperture = powf64(2.0f, ((float)get4())/16.0f);
fseek (ifp, 112, SEEK_SET);
focal_len = get4();
#ifdef LIBRAW_LIBRARY_BUILD
fseek (ifp, 104, SEEK_SET);
imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())/16.0f);
fseek (ifp, 124, SEEK_SET);
stmread(imgdata.lens.makernotes.Lens, 32, ifp);
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N;
if (imgdata.lens.makernotes.Lens[0])
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N;
#endif
} else if (!strcmp (head, "PXN")) {
strcpy (make, "Logitech");
strcpy (model,"Fotoman Pixtura");
} else if (!strcmp (head, "qktk")) {
strcpy (make, "Apple");
strcpy (model,"QuickTake 100");
load_raw = &CLASS quicktake_100_load_raw;
} else if (!strcmp (head, "qktn")) {
strcpy (make, "Apple");
strcpy (model,"QuickTake 150");
load_raw = &CLASS kodak_radc_load_raw;
} else if (!memcmp (head,"FUJIFILM",8)) {
#ifdef LIBRAW_LIBRARY_BUILD
strcpy(model, head+0x1c);
memcpy(model2, head+0x3c, 4);
model2[4]=0;
#endif
fseek (ifp, 84, SEEK_SET);
thumb_offset = get4();
thumb_length = get4();
fseek (ifp, 92, SEEK_SET);
parse_fuji (get4());
if (thumb_offset > 120) {
fseek (ifp, 120, SEEK_SET);
is_raw += (i = get4())?1:0;
if (is_raw == 2 && shot_select)
parse_fuji (i);
}
load_raw = &CLASS unpacked_load_raw;
fseek (ifp, 100+28*(shot_select > 0), SEEK_SET);
parse_tiff (data_offset = get4());
parse_tiff (thumb_offset+12);
apply_tiff();
} else if (!memcmp (head,"RIFF",4)) {
fseek (ifp, 0, SEEK_SET);
parse_riff();
} else if (!memcmp (head+4,"ftypqt ",9)) {
fseek (ifp, 0, SEEK_SET);
parse_qt (fsize);
is_raw = 0;
} else if (!memcmp (head,"\0\001\0\001\0@",6)) {
fseek (ifp, 6, SEEK_SET);
fread (make, 1, 8, ifp);
fread (model, 1, 8, ifp);
fread (model2, 1, 16, ifp);
data_offset = get2();
get2();
raw_width = get2();
raw_height = get2();
load_raw = &CLASS nokia_load_raw;
filters = 0x61616161;
} else if (!memcmp (head,"NOKIARAW",8)) {
strcpy (make, "NOKIA");
order = 0x4949;
fseek (ifp, 300, SEEK_SET);
data_offset = get4();
i = get4();
width = get2();
height = get2();
switch (tiff_bps = i*8 / (width * height)) {
case 8: load_raw = &CLASS eight_bit_load_raw; break;
case 10: load_raw = &CLASS nokia_load_raw;
}
raw_height = height + (top_margin = i / (width * tiff_bps/8) - height);
mask[0][3] = 1;
filters = 0x61616161;
} else if (!memcmp (head,"ARRI",4)) {
order = 0x4949;
fseek (ifp, 20, SEEK_SET);
width = get4();
height = get4();
strcpy (make, "ARRI");
fseek (ifp, 668, SEEK_SET);
fread (model, 1, 64, ifp);
data_offset = 4096;
load_raw = &CLASS packed_load_raw;
load_flags = 88;
filters = 0x61616161;
} else if (!memcmp (head,"XPDS",4)) {
order = 0x4949;
fseek (ifp, 0x800, SEEK_SET);
fread (make, 1, 41, ifp);
raw_height = get2();
raw_width = get2();
fseek (ifp, 56, SEEK_CUR);
fread (model, 1, 30, ifp);
data_offset = 0x10000;
load_raw = &CLASS canon_rmf_load_raw;
gamma_curve (0, 12.25, 1, 1023);
} else if (!memcmp (head+4,"RED1",4)) {
strcpy (make, "Red");
strcpy (model,"One");
parse_redcine();
load_raw = &CLASS redcine_load_raw;
gamma_curve (1/2.4, 12.92, 1, 4095);
filters = 0x49494949;
} else if (!memcmp (head,"DSC-Image",9))
parse_rollei();
else if (!memcmp (head,"PWAD",4))
parse_sinar_ia();
else if (!memcmp (head,"\0MRM",4))
parse_minolta(0);
else if (!memcmp (head,"FOVb",4))
{
#ifdef LIBRAW_LIBRARY_BUILD
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F))
parse_foveon();
else
#endif
parse_x3f();
#else
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
parse_foveon();
#endif
#endif
}
else if (!memcmp (head,"CI",2))
parse_cine();
if(make[0] == 0)
#ifdef LIBRAW_LIBRARY_BUILD
for (zero_fsize=i=0; i < camera_count; i++)
#else
for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++)
#endif
if (fsize == table[i].fsize) {
strcpy (make, table[i].t_make );
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(make, "Canon",5))
{
imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens;
imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens;
}
#endif
strcpy (model, table[i].t_model);
flip = table[i].flags >> 2;
zero_is_bad = table[i].flags & 2;
if (table[i].flags & 1)
parse_external_jpeg();
data_offset = table[i].offset == 0xffff?0:table[i].offset;
raw_width = table[i].rw;
raw_height = table[i].rh;
left_margin = table[i].lm;
top_margin = table[i].tm;
width = raw_width - left_margin - table[i].rm;
height = raw_height - top_margin - table[i].bm;
filters = 0x1010101 * table[i].cf;
colors = 4 - !((filters & filters >> 1) & 0x5555);
load_flags = table[i].lf;
switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) {
case 6:
load_raw = &CLASS minolta_rd175_load_raw; break;
case 8:
load_raw = &CLASS eight_bit_load_raw; break;
case 10:
if ((fsize-data_offset)/raw_height*3 >= raw_width*4) {
load_raw = &CLASS android_loose_load_raw; break;
} else if (load_flags & 1) {
load_raw = &CLASS android_tight_load_raw; break;
}
case 12:
load_flags |= 128;
load_raw = &CLASS packed_load_raw; break;
case 16:
order = 0x4949 | 0x404 * (load_flags & 1);
tiff_bps -= load_flags >> 4;
tiff_bps -= load_flags = load_flags >> 1 & 7;
load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw;
}
maximum = (1 << tiff_bps) - (1 << table[i].max);
}
if (zero_fsize) fsize = 0;
if (make[0] == 0) parse_smal (0, flen);
if (make[0] == 0) {
parse_jpeg(0);
fseek(ifp,0,SEEK_END);
int sz = ftell(ifp);
#ifdef LIBRAW_LIBRARY_BUILD
if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 &&
!fseek (ifp, -0x9cb600, SEEK_END) &&
fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) {
strcpy (make, "Broadcom");
strcpy (model, "RPi IMX219");
if (raw_height > raw_width) flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 66;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x9cb600 - 1;
} else
if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 &&
!fseek (ifp, -0x61b800, SEEK_END) &&
fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) {
strcpy (make, "Broadcom");
if (!strncmp(model,"ov5647",6))
strcpy (model, "RPi OV5647 v.1");
else
strcpy (model, "RPi OV5647 v.2");
if (raw_height > raw_width) flip = 5;
data_offset = ftell(ifp) + 0x8000 - 0x20;
parse_broadcom();
black = 16;
maximum = 0x3ff;
load_raw = &CLASS broadcom_load_raw;
thumb_offset = 0;
thumb_length = sz - 0x61b800 - 1;
#else
if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 &&
!fseek (ifp, -6404096, SEEK_END) &&
fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) {
strcpy (make, "OmniVision");
data_offset = ftell(ifp) + 0x8000-32;
width = raw_width;
raw_width = 2611;
load_raw = &CLASS nokia_load_raw;
filters = 0x16161616;
#endif
} else is_raw = 0;
}
#ifdef LIBRAW_LIBRARY_BUILD
// make sure strings are terminated
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
#endif
for (i=0; i < sizeof corp / sizeof *corp; i++)
if (strcasestr (make, corp[i])) /* Simplify company names */
strcpy (make, corp[i]);
if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) &&
((cp = strcasestr(model," DIGITAL CAMERA")) ||
(cp = strstr(model,"FILE VERSION"))))
*cp = 0;
if (!strncasecmp(model,"PENTAX",6))
strcpy (make, "Pentax");
#ifdef LIBRAW_LIBRARY_BUILD
remove_trailing_spaces(make,sizeof(make));
remove_trailing_spaces(model,sizeof(model));
#else
cp = make + strlen(make); /* Remove trailing spaces */
while (*--cp == ' ') *cp = 0;
cp = model + strlen(model);
while (*--cp == ' ') *cp = 0;
#endif
i = strbuflen(make); /* Remove make from model */
if (!strncasecmp (model, make, i) && model[i++] == ' ')
memmove (model, model+i, 64-i);
if (!strncmp (model,"FinePix ",8))
strcpy (model, model+8);
if (!strncmp (model,"Digital Camera ",15))
strcpy (model, model+15);
desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0;
if (!is_raw) goto notraw;
if (!height) height = raw_height;
if (!width) width = raw_width;
if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */
{ height = 2616; width = 3896; }
if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */
{ height = 3124; width = 4688; filters = 0x16161616; }
if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x")))
{ width = 4309; filters = 0x16161616; }
if (width >= 4960 && !strncmp(model,"K-5",3))
{ left_margin = 10; width = 4950; filters = 0x16161616; }
if (width == 6080 && !strcmp(model,"K-70"))
{ height = 4016; top_margin=32; width=6020; left_margin = 60; }
if (width == 4736 && !strcmp(model,"K-7"))
{ height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; }
if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */
{ left_margin = 4; width = 6040; }
if (width == 6080 && !strcmp(model,"K-3"))
{ left_margin = 4; width = 6040; }
if (width == 7424 && !strcmp(model,"645D"))
{ height = 5502; width = 7328; filters = 0x61616161; top_margin = 29;
left_margin = 48; }
if (height == 3014 && width == 4096) /* Ricoh GX200 */
width = 4014;
if (dng_version) {
if (filters == UINT_MAX) filters = 0;
if (filters) is_raw *= tiff_samples;
else colors = tiff_samples;
switch (tiff_compress) {
case 0: /* Compression not set, assuming uncompressed */
case 1: load_raw = &CLASS packed_dng_load_raw; break;
case 7: load_raw = &CLASS lossless_dng_load_raw; break;
#ifdef LIBRAW_LIBRARY_BUILD
case 8: load_raw = &CLASS deflate_dng_load_raw; break;
#endif
case 34892: load_raw = &CLASS lossy_dng_load_raw; break;
default: load_raw = 0;
}
if (!strncmp(make, "Canon",5) && unique_id)
{
for (i = 0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
strcpy(model, unique[i].t_model);
break;
}
}
if (!strncasecmp(make, "Sony",4) && unique_id)
{
for (i = 0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
strcpy(model, sonique[i].t_model);
break;
}
}
goto dng_skip;
}
if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) {
if (!load_raw)
load_raw = &CLASS lossless_jpeg_load_raw;
for (i=0; i < sizeof canon / sizeof *canon; i++)
if (raw_width == canon[i][0] && raw_height == canon[i][1]) {
width = raw_width - (left_margin = canon[i][2]);
height = raw_height - (top_margin = canon[i][3]);
width -= canon[i][4];
height -= canon[i][5];
mask[0][1] = canon[i][6];
mask[0][3] = -canon[i][7];
mask[1][1] = canon[i][8];
mask[1][3] = -canon[i][9];
if (canon[i][10]) filters = canon[i][10] * 0x01010101;
}
if ((unique_id | 0x20000) == 0x2720000) {
left_margin = 8;
top_margin = 16;
}
}
if (!strncmp(make,"Canon",5) && unique_id)
{
for (i=0; i < sizeof unique / sizeof *unique; i++)
if (unique_id == 0x80000000 + unique[i].id)
{
adobe_coeff ("Canon", unique[i].t_model);
strcpy(model,unique[i].t_model);
}
}
if (!strncasecmp(make,"Sony",4) && unique_id)
{
for (i=0; i < sizeof sonique / sizeof *sonique; i++)
if (unique_id == sonique[i].id)
{
adobe_coeff ("Sony", sonique[i].t_model);
strcpy(model,sonique[i].t_model);
}
}
if (!strncmp(make,"Nikon",5)) {
if (!load_raw)
load_raw = &CLASS packed_load_raw;
if (model[0] == 'E')
load_flags |= !data_offset << 2 | 2;
}
/* Set parameters based on camera name (for non-DNG files). */
if (!strcmp(model,"KAI-0340")
&& find_green (16, 16, 3840, 5120) < 25) {
height = 480;
top_margin = filters = 0;
strcpy (model,"C603");
}
if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0])
black = 128 << (tiff_bps - 12);
if (is_foveon) {
if (height*2 < width) pixel_aspect = 0.5;
if (height > width) pixel_aspect = 2;
filters = 0;
#ifdef LIBRAW_DEMOSAIC_PACK_GPL2
if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F))
simple_coeff(0);
#endif
}
else if(!strncmp(make,"Pentax",6))
{
if(!strncmp(model,"K-1",3))
{
top_margin = 18;
height = raw_height - top_margin;
if(raw_width == 7392)
{
left_margin = 6;
width = 7376;
}
}
}
else if (!strncmp(make,"Canon",5) && tiff_bps == 15) {
switch (width) {
case 3344: width -= 66;
case 3872: width -= 6;
}
if (height > width) {
SWAP(height,width);
SWAP(raw_height,raw_width);
}
if (width == 7200 && height == 3888)
{
raw_width = width = 6480;
raw_height = height = 4320;
}
filters = 0;
tiff_samples = colors = 3;
load_raw = &CLASS canon_sraw_load_raw;
} else if (!strcmp(model,"PowerShot 600")) {
height = 613;
width = 854;
raw_width = 896;
colors = 4;
filters = 0xe1e4e1e4;
load_raw = &CLASS canon_600_load_raw;
} else if (!strcmp(model,"PowerShot A5") ||
!strcmp(model,"PowerShot A5 Zoom")) {
height = 773;
width = 960;
raw_width = 992;
pixel_aspect = 256/235.0;
filters = 0x1e4e1e4e;
goto canon_a5;
} else if (!strcmp(model,"PowerShot A50")) {
height = 968;
width = 1290;
raw_width = 1320;
filters = 0x1b4e4b1e;
goto canon_a5;
} else if (!strcmp(model,"PowerShot Pro70")) {
height = 1024;
width = 1552;
filters = 0x1e4b4e1b;
canon_a5:
colors = 4;
tiff_bps = 10;
load_raw = &CLASS packed_load_raw;
load_flags = 40;
} else if (!strcmp(model,"PowerShot Pro90 IS") ||
!strcmp(model,"PowerShot G1")) {
colors = 4;
filters = 0xb4b4b4b4;
} else if (!strcmp(model,"PowerShot A610")) {
if (canon_s2is()) strcpy (model+10, "S2 IS");
} else if (!strcmp(model,"PowerShot SX220 HS")) {
mask[1][3] = -4;
top_margin=16;
left_margin = 92;
} else if (!strcmp(model,"PowerShot S120")) {
raw_width = 4192;
raw_height = 3062;
width = 4022;
height = 3016;
mask[0][0] = top_margin = 31;
mask[0][2] = top_margin + height;
left_margin = 120;
mask[0][1] = 23;
mask[0][3] = 72;
} else if (!strcmp(model,"PowerShot G16")) {
mask[0][0] = 0;
mask[0][2] = 80;
mask[0][1] = 0;
mask[0][3] = 16;
top_margin = 29;
left_margin = 120;
width = raw_width-left_margin-48;
height = raw_height-top_margin-14;
} else if (!strcmp(model,"PowerShot SX50 HS")) {
top_margin = 17;
} else if (!strcmp(model,"EOS D2000C")) {
filters = 0x61616161;
black = curve[200];
} else if (!strcmp(model,"D1")) {
cam_mul[0] *= 256/527.0;
cam_mul[2] *= 256/317.0;
} else if (!strcmp(model,"D1X")) {
width -= 4;
pixel_aspect = 0.5;
} else if (!strcmp(model,"D40X") ||
!strcmp(model,"D60") ||
!strcmp(model,"D80") ||
!strcmp(model,"D3000")) {
height -= 3;
width -= 4;
} else if (!strcmp(model,"D3") ||
!strcmp(model,"D3S") ||
!strcmp(model,"D700")) {
width -= 4;
left_margin = 2;
} else if (!strcmp(model,"D3100")) {
width -= 28;
left_margin = 6;
} else if (!strcmp(model,"D5000") ||
!strcmp(model,"D90")) {
width -= 42;
} else if (!strcmp(model,"D5100") ||
!strcmp(model,"D7000") ||
!strcmp(model,"COOLPIX A")) {
width -= 44;
} else if (!strcmp(model,"D3200") ||
!strncmp(model,"D6",2) ||
!strncmp(model,"D800",4)) {
width -= 46;
} else if (!strcmp(model,"D4") ||
!strcmp(model,"Df")) {
width -= 52;
left_margin = 2;
} else if (!strncmp(model,"D40",3) ||
!strncmp(model,"D50",3) ||
!strncmp(model,"D70",3)) {
width--;
} else if (!strcmp(model,"D100")) {
if (load_flags)
raw_width = (width += 3) + 3;
} else if (!strcmp(model,"D200")) {
left_margin = 1;
width -= 4;
filters = 0x94949494;
} else if (!strncmp(model,"D2H",3)) {
left_margin = 6;
width -= 14;
} else if (!strncmp(model,"D2X",3)) {
if (width == 3264) width -= 32;
else width -= 8;
} else if (!strncmp(model,"D300",4)) {
width -= 32;
} else if (!strncmp(make,"Nikon",5) && raw_width == 4032) {
if(!strcmp(model,"COOLPIX P7700"))
{
adobe_coeff ("Nikon","COOLPIX P7700");
maximum = 65504;
load_flags = 0;
}
else if(!strcmp(model,"COOLPIX P7800"))
{
adobe_coeff ("Nikon","COOLPIX P7800");
maximum = 65504;
load_flags = 0;
}
else if(!strcmp(model,"COOLPIX P340"))
load_flags=0;
} else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) {
load_flags = 24;
filters = 0x94949494;
if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") )
black = 255;
} else if (!strncmp(model,"1 ",2)) {
height -= 2;
} else if (fsize == 1581060) {
simple_coeff(3);
pre_mul[0] = 1.2085;
pre_mul[1] = 1.0943;
pre_mul[3] = 1.1103;
} else if (fsize == 3178560) {
cam_mul[0] *= 4;
cam_mul[2] *= 4;
} else if (fsize == 4771840) {
if (!timestamp && nikon_e995())
strcpy (model, "E995");
if (strcmp(model,"E995")) {
filters = 0xb4b4b4b4;
simple_coeff(3);
pre_mul[0] = 1.196;
pre_mul[1] = 1.246;
pre_mul[2] = 1.018;
}
} else if (fsize == 2940928) {
if (!timestamp && !nikon_e2100())
strcpy (model,"E2500");
if (!strcmp(model,"E2500")) {
height -= 2;
load_flags = 6;
colors = 4;
filters = 0x4b4b4b4b;
}
} else if (fsize == 4775936) {
if (!timestamp) nikon_3700();
if (model[0] == 'E' && atoi(model+1) < 3700)
filters = 0x49494949;
if (!strcmp(model,"Optio 33WR")) {
flip = 1;
filters = 0x16161616;
}
if (make[0] == 'O') {
i = find_green (12, 32, 1188864, 3576832);
c = find_green (12, 32, 2383920, 2387016);
if (abs(i) < abs(c)) {
SWAP(i,c);
load_flags = 24;
}
if (i < 0) filters = 0x61616161;
}
} else if (fsize == 5869568) {
if (!timestamp && minolta_z2()) {
strcpy (make, "Minolta");
strcpy (model,"DiMAGE Z2");
}
load_flags = 6 + 24*(make[0] == 'M');
} else if (fsize == 6291456) {
fseek (ifp, 0x300000, SEEK_SET);
if ((order = guess_byte_order(0x10000)) == 0x4d4d) {
height -= (top_margin = 16);
width -= (left_margin = 28);
maximum = 0xf5c0;
strcpy (make, "ISG");
model[0] = 0;
}
} else if (!strncmp(make,"Fujifilm",8)) {
if (!strcmp(model+7,"S2Pro")) {
strcpy (model,"S2Pro");
height = 2144;
width = 2880;
flip = 6;
} else if (load_raw != &CLASS packed_load_raw)
maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00;
top_margin = (raw_height - height) >> 2 << 1;
left_margin = (raw_width - width ) >> 2 << 1;
if (width == 2848 || width == 3664) filters = 0x16161616;
if (width == 4032 || width == 4952) left_margin = 0;
if (width == 3328 && (width -= 66)) left_margin = 34;
if (width == 4936) left_margin = 4;
if (width == 6032) left_margin = 0;
if (!strcmp(model,"HS50EXR") ||
!strcmp(model,"F900EXR")) {
width += 2;
left_margin = 0;
filters = 0x16161616;
}
if(!strcmp(model,"S5500"))
{
height -= (top_margin=6);
}
if (fuji_layout) raw_width *= is_raw;
if (filters == 9)
FORC(36) ((char *)xtrans)[c] =
xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6];
} else if (!strcmp(model,"KD-400Z")) {
height = 1712;
width = 2312;
raw_width = 2336;
goto konica_400z;
} else if (!strcmp(model,"KD-510Z")) {
goto konica_510z;
} else if (!strncasecmp(make,"Minolta",7)) {
if (!load_raw && (maximum = 0xfff))
load_raw = &CLASS unpacked_load_raw;
if (!strncmp(model,"DiMAGE A",8)) {
if (!strcmp(model,"DiMAGE A200"))
filters = 0x49494949;
tiff_bps = 12;
load_raw = &CLASS packed_load_raw;
} else if (!strncmp(model,"ALPHA",5) ||
!strncmp(model,"DYNAX",5) ||
!strncmp(model,"MAXXUM",6)) {
sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M'));
adobe_coeff (make, model+20);
load_raw = &CLASS packed_load_raw;
} else if (!strncmp(model,"DiMAGE G",8)) {
if (model[8] == '4') {
height = 1716;
width = 2304;
} else if (model[8] == '5') {
konica_510z:
height = 1956;
width = 2607;
raw_width = 2624;
} else if (model[8] == '6') {
height = 2136;
width = 2848;
}
data_offset += 14;
filters = 0x61616161;
konica_400z:
load_raw = &CLASS unpacked_load_raw;
maximum = 0x3df;
order = 0x4d4d;
}
} else if (!strcmp(model,"*ist D")) {
load_raw = &CLASS unpacked_load_raw;
data_error = -1;
} else if (!strcmp(model,"*ist DS")) {
height -= 2;
} else if (!strncmp(make,"Samsung",7) && raw_width == 4704) {
height -= top_margin = 8;
width -= 2 * (left_margin = 8);
load_flags = 32;
} else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) {
top_margin = 24;
left_margin = 64;
width = 5472;
height = 3648;
filters = 0x61616161;
colors = 3;
} else if (!strncmp(make,"Samsung",7) && raw_height == 3714) {
height -= top_margin = 18;
left_margin = raw_width - (width = 5536);
if (raw_width != 5600)
left_margin = top_margin = 0;
filters = 0x61616161;
colors = 3;
} else if (!strncmp(make,"Samsung",7) && raw_width == 5632) {
order = 0x4949;
height = 3694;
top_margin = 2;
width = 5574 - (left_margin = 32 + tiff_bps);
if (tiff_bps == 12) load_flags = 80;
} else if (!strncmp(make,"Samsung",7) && raw_width == 5664) {
height -= top_margin = 17;
left_margin = 96;
width = 5544;
filters = 0x49494949;
} else if (!strncmp(make,"Samsung",7) && raw_width == 6496) {
filters = 0x61616161;
#ifdef LIBRAW_LIBRARY_BUILD
if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3])
#endif
black = 1 << (tiff_bps - 7);
} else if (!strcmp(model,"EX1")) {
order = 0x4949;
height -= 20;
top_margin = 2;
if ((width -= 6) > 3682) {
height -= 10;
width -= 46;
top_margin = 8;
}
} else if (!strcmp(model,"WB2000")) {
order = 0x4949;
height -= 3;
top_margin = 2;
if ((width -= 10) > 3718) {
height -= 28;
width -= 56;
top_margin = 8;
}
} else if (strstr(model,"WB550")) {
strcpy (model, "WB550");
} else if (!strcmp(model,"EX2F")) {
height = 3030;
width = 4040;
top_margin = 15;
left_margin=24;
order = 0x4949;
filters = 0x49494949;
load_raw = &CLASS unpacked_load_raw;
} else if (!strcmp(model,"STV680 VGA")) {
black = 16;
} else if (!strcmp(model,"N95")) {
height = raw_height - (top_margin = 2);
} else if (!strcmp(model,"640x480")) {
gamma_curve (0.45, 4.5, 1, 255);
} else if (!strncmp(make,"Hasselblad",10)) {
if (load_raw == &CLASS lossless_jpeg_load_raw)
load_raw = &CLASS hasselblad_load_raw;
if (raw_width == 7262) {
height = 5444;
width = 7248;
top_margin = 4;
left_margin = 7;
filters = 0x61616161;
if(!strncasecmp(model,"H3D",3))
{
adobe_coeff("Hasselblad","H3DII-39");
strcpy(model,"H3DII-39");
}
} else if (raw_width == 7410 || raw_width == 8282) {
height -= 84;
width -= 82;
top_margin = 4;
left_margin = 41;
filters = 0x61616161;
adobe_coeff("Hasselblad","H4D-40");
strcpy(model,"H4D-40");
}
else if( raw_width == 8384) // X1D
{
top_margin = 96;
height -= 96;
left_margin = 48;
width -= 106;
adobe_coeff("Hasselblad","X1D");
}
else if (raw_width == 9044) {
if(black > 500)
{
top_margin = 12;
left_margin = 44;
width = 8956;
height = 6708;
memset(cblack,0,sizeof(cblack));
adobe_coeff("Hasselblad","H4D-60");
strcpy(model,"H4D-60");
black = 512;
}
else
{
height = 6716;
width = 8964;
top_margin = 8;
left_margin = 40;
black += load_flags = 256;
maximum = 0x8101;
strcpy(model,"H3DII-60");
}
} else if (raw_width == 4090) {
strcpy (model, "V96C");
height -= (top_margin = 6);
width -= (left_margin = 3) + 7;
filters = 0x61616161;
} else if (raw_width == 8282 && raw_height == 6240) {
if(!strncasecmp(model,"H5D",3))
{
/* H5D 50*/
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
black = 256;
strcpy(model,"H5D-50");
}
else if(!strncasecmp(model,"H3D",3))
{
black=0;
left_margin = 54;
top_margin = 16;
width = 8176;
height = 6132;
memset(cblack,0,sizeof(cblack));
adobe_coeff("Hasselblad","H3D-50");
strcpy(model,"H3D-50");
}
} else if (raw_width == 8374 && raw_height == 6304) {
/* H5D 50c*/
left_margin = 52;
top_margin = 100;
width = 8272;
height = 6200;
black = 256;
strcpy(model,"H5D-50c");
}
if (tiff_samples > 1) {
is_raw = tiff_samples+1;
if (!shot_select && !half_size) filters = 0;
}
} else if (!strncmp(make,"Sinar",5)) {
if (!load_raw) load_raw = &CLASS unpacked_load_raw;
if (is_raw > 1 && !shot_select && !half_size) filters = 0;
maximum = 0x3fff;
} else if (!strncmp(make,"Leaf",4)) {
maximum = 0x3fff;
fseek (ifp, data_offset, SEEK_SET);
if (ljpeg_start (&jh, 1) && jh.bits == 15)
maximum = 0x1fff;
if (tiff_samples > 1) filters = 0;
if (tiff_samples > 1 || tile_length < raw_height) {
load_raw = &CLASS leaf_hdr_load_raw;
raw_width = tile_width;
}
if ((width | height) == 2048) {
if (tiff_samples == 1) {
filters = 1;
strcpy (cdesc, "RBTG");
strcpy (model, "CatchLight");
top_margin = 8; left_margin = 18; height = 2032; width = 2016;
} else {
strcpy (model, "DCB2");
top_margin = 10; left_margin = 16; height = 2028; width = 2022;
}
} else if (width+height == 3144+2060) {
if (!model[0]) strcpy (model, "Cantare");
if (width > height) {
top_margin = 6; left_margin = 32; height = 2048; width = 3072;
filters = 0x61616161;
} else {
left_margin = 6; top_margin = 32; width = 2048; height = 3072;
filters = 0x16161616;
}
if (!cam_mul[0] || model[0] == 'V') filters = 0;
else is_raw = tiff_samples;
} else if (width == 2116) {
strcpy (model, "Valeo 6");
height -= 2 * (top_margin = 30);
width -= 2 * (left_margin = 55);
filters = 0x49494949;
} else if (width == 3171) {
strcpy (model, "Valeo 6");
height -= 2 * (top_margin = 24);
width -= 2 * (left_margin = 24);
filters = 0x16161616;
}
} else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9)
|| !strncasecmp(make,"YUNEEC",6)) {
if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) )
load_raw = &CLASS panasonic_load_raw;
if (!load_raw) {
load_raw = &CLASS unpacked_load_raw;
load_flags = 4;
}
zero_is_bad = 1;
if ((height += 12) > raw_height) height = raw_height;
for (i=0; i < sizeof pana / sizeof *pana; i++)
if (raw_width == pana[i][0] && raw_height == pana[i][1]) {
left_margin = pana[i][2];
top_margin = pana[i][3];
width += pana[i][4];
height += pana[i][5];
}
filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"
[((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3];
} else if (!strcmp(model,"C770UZ")) {
height = 1718;
width = 2304;
filters = 0x16161616;
load_raw = &CLASS packed_load_raw;
load_flags = 30;
} else if (!strncmp(make,"Olympus",7)) {
height += height & 1;
if (exif_cfa) filters = exif_cfa;
if (width == 4100) width -= 4;
if (width == 4080) width -= 24;
if (width == 9280) { width -= 6; height -= 6; }
if (load_raw == &CLASS unpacked_load_raw)
load_flags = 4;
tiff_bps = 12;
if (!strcmp(model,"E-300") ||
!strcmp(model,"E-500")) {
width -= 20;
if (load_raw == &CLASS unpacked_load_raw) {
maximum = 0xfc3;
memset (cblack, 0, sizeof cblack);
}
} else if (!strcmp(model,"STYLUS1")) {
width -= 14;
maximum = 0xfff;
} else if (!strcmp(model,"E-330")) {
width -= 30;
if (load_raw == &CLASS unpacked_load_raw)
maximum = 0xf79;
} else if (!strcmp(model,"SP550UZ")) {
thumb_length = flen - (thumb_offset = 0xa39800);
thumb_height = 480;
thumb_width = 640;
} else if (!strcmp(model,"TG-4")) {
width -= 16;
}
} else if (!strcmp(model,"N Digital")) {
height = 2047;
width = 3072;
filters = 0x61616161;
data_offset = 0x1a00;
load_raw = &CLASS packed_load_raw;
} else if (!strcmp(model,"DSC-F828")) {
width = 3288;
left_margin = 5;
mask[1][3] = -17;
data_offset = 862144;
load_raw = &CLASS sony_load_raw;
filters = 0x9c9c9c9c;
colors = 4;
strcpy (cdesc, "RGBE");
} else if (!strcmp(model,"DSC-V3")) {
width = 3109;
left_margin = 59;
mask[0][1] = 9;
data_offset = 787392;
load_raw = &CLASS sony_load_raw;
} else if (!strncmp(make,"Sony",4) && raw_width == 3984) {
width = 3925;
order = 0x4d4d;
} else if (!strncmp(make,"Sony",4) && raw_width == 4288) {
width -= 32;
} else if (!strcmp(make, "Sony") && raw_width == 4600) {
if (!strcmp(model, "DSLR-A350"))
height -= 4;
black = 0;
} else if (!strncmp(make,"Sony",4) && raw_width == 4928) {
if (height < 3280) width -= 8;
} else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000
width -= height > 3664 ? 8 : 32;
} else if (!strncmp(make,"Sony",4) && raw_width == 6048) {
width -= 24;
if (strstr(model,"RX1") || strstr(model,"A99"))
width -= 6;
} else if (!strncmp(make,"Sony",4) && raw_width == 7392) {
width -= 30;
} else if (!strncmp(make,"Sony",4) && raw_width == 8000) {
width -= 32;
if (!strncmp(model, "DSC", 3)) {
tiff_bps = 14;
load_raw = &CLASS unpacked_load_raw;
}
} else if (!strcmp(model,"DSLR-A100")) {
if (width == 3880) {
height--;
width = ++raw_width;
} else {
height -= 4;
width -= 4;
order = 0x4d4d;
load_flags = 2;
}
filters = 0x61616161;
} else if (!strcmp(model,"PIXL")) {
height -= top_margin = 4;
width -= left_margin = 32;
gamma_curve (0, 7, 1, 255);
} else if (!strcmp(model,"C603") || !strcmp(model,"C330")
|| !strcmp(model,"12MP")) {
order = 0x4949;
if (filters && data_offset) {
fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET);
read_shorts (curve, 256);
} else gamma_curve (0, 3.875, 1, 255);
load_raw = filters ? &CLASS eight_bit_load_raw :
strcmp(model,"C330") ? &CLASS kodak_c603_load_raw :
&CLASS kodak_c330_load_raw;
load_flags = tiff_bps > 16;
tiff_bps = 8;
} else if (!strncasecmp(model,"EasyShare",9)) {
data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000;
load_raw = &CLASS packed_load_raw;
} else if (!strncasecmp(make,"Kodak",5)) {
if (filters == UINT_MAX) filters = 0x61616161;
if (!strncmp(model,"NC2000",6) ||
!strncmp(model,"EOSDCS",6) ||
!strncmp(model,"DCS4",4)) {
width -= 4;
left_margin = 2;
if (model[6] == ' ') model[6] = 0;
if (!strcmp(model,"DCS460A")) goto bw;
} else if (!strcmp(model,"DCS660M")) {
black = 214;
goto bw;
} else if (!strcmp(model,"DCS760M")) {
bw: colors = 1;
filters = 0;
}
if (!strcmp(model+4,"20X"))
strcpy (cdesc, "MYCY");
if (strstr(model,"DC25")) {
strcpy (model, "DC25");
data_offset = 15424;
}
if (!strncmp(model,"DC2",3)) {
raw_height = 2 + (height = 242);
if (!strncmp(model, "DC290", 5))
iso_speed = 100;
if (!strncmp(model, "DC280", 5))
iso_speed = 70;
if (flen < 100000) {
raw_width = 256; width = 249;
pixel_aspect = (4.0*height) / (3.0*width);
} else {
raw_width = 512; width = 501;
pixel_aspect = (493.0*height) / (373.0*width);
}
top_margin = left_margin = 1;
colors = 4;
filters = 0x8d8d8d8d;
simple_coeff(1);
pre_mul[1] = 1.179;
pre_mul[2] = 1.209;
pre_mul[3] = 1.036;
load_raw = &CLASS eight_bit_load_raw;
} else if (!strcmp(model,"40")) {
strcpy (model, "DC40");
height = 512;
width = 768;
data_offset = 1152;
load_raw = &CLASS kodak_radc_load_raw;
tiff_bps = 12;
} else if (strstr(model,"DC50")) {
strcpy (model, "DC50");
height = 512;
width = 768;
iso_speed=84;
data_offset = 19712;
load_raw = &CLASS kodak_radc_load_raw;
} else if (strstr(model,"DC120")) {
strcpy (model, "DC120");
height = 976;
width = 848;
iso_speed=160;
pixel_aspect = height/0.75/width;
load_raw = tiff_compress == 7 ?
&CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw;
} else if (!strcmp(model,"DCS200")) {
thumb_height = 128;
thumb_width = 192;
thumb_offset = 6144;
thumb_misc = 360;
iso_speed=140;
write_thumb = &CLASS layer_thumb;
black = 17;
}
} else if (!strcmp(model,"Fotoman Pixtura")) {
height = 512;
width = 768;
data_offset = 3632;
load_raw = &CLASS kodak_radc_load_raw;
filters = 0x61616161;
simple_coeff(2);
} else if (!strncmp(model,"QuickTake",9)) {
if (head[5]) strcpy (model+10, "200");
fseek (ifp, 544, SEEK_SET);
height = get2();
width = get2();
data_offset = (get4(),get2()) == 30 ? 738:736;
if (height > width) {
SWAP(height,width);
fseek (ifp, data_offset-6, SEEK_SET);
flip = ~get2() & 3 ? 5:6;
}
filters = 0x61616161;
} else if (!strncmp(make,"Rollei",6) && !load_raw) {
switch (raw_width) {
case 1316:
height = 1030;
width = 1300;
top_margin = 1;
left_margin = 6;
break;
case 2568:
height = 1960;
width = 2560;
top_margin = 2;
left_margin = 8;
}
filters = 0x16161616;
load_raw = &CLASS rollei_load_raw;
}
else if (!strcmp(model,"GRAS-50S5C")) {
height = 2048;
width = 2440;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x49494949;
order = 0x4949;
maximum = 0xfffC;
} else if (!strcmp(model,"BB-500CL")) {
height = 2058;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
} else if (!strcmp(model,"BB-500GE")) {
height = 2058;
width = 2456;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x3fff;
} else if (!strcmp(model,"SVS625CL")) {
height = 2050;
width = 2448;
load_raw = &CLASS unpacked_load_raw;
data_offset = 0;
filters = 0x94949494;
order = 0x4949;
maximum = 0x0fff;
}
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2);
#endif
return;
}
if (!model[0])
sprintf (model, "%dx%d", width, height);
if (filters == UINT_MAX) filters = 0x94949494;
if (thumb_offset && !thumb_height) {
fseek (ifp, thumb_offset, SEEK_SET);
if (ljpeg_start (&jh, 1)) {
thumb_width = jh.wide;
thumb_height = jh.high;
}
}
dng_skip:
#ifdef LIBRAW_LIBRARY_BUILD
if(dng_version) /* Override black level by DNG tags */
{
black = imgdata.color.dng_levels.dng_black;
int ll = LIM(0,
(sizeof(cblack)/sizeof(cblack[0])),
(sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0])));
for(int i=0; i < ll; i++)
cblack[i] = imgdata.color.dng_levels.dng_cblack[i];
}
#endif
/* Early reject for damaged images */
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 4 || colors > 4 || colors < 1)
{
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2);
#endif
return;
}
if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) )
&& cmatrix[0][0] > 0.125) {
memcpy (rgb_cam, cmatrix, sizeof cmatrix);
raw_color = 0;
}
if (raw_color) adobe_coeff (make, model);
#ifdef LIBRAW_LIBRARY_BUILD
else if(imgdata.color.cam_xyz[0][0]<0.01)
adobe_coeff (make, model,1);
#endif
if (load_raw == &CLASS kodak_radc_load_raw)
if (raw_color) adobe_coeff ("Apple","Quicktake");
if (fuji_width) {
fuji_width = width >> !fuji_layout;
filters = fuji_width & 1 ? 0x94949494 : 0x49494949;
width = (height >> fuji_layout) + fuji_width;
height = width - 1;
pixel_aspect = 1;
} else {
if (raw_height < height) raw_height = height;
if (raw_width < width ) raw_width = width;
}
if (!tiff_bps) tiff_bps = 12;
if (!maximum)
{
maximum = (1 << tiff_bps) - 1;
if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw)
maximum = curve[maximum];
}
if (!load_raw || height < 22 || width < 22 ||
#ifdef LIBRAW_LIBRARY_BUILD
(tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw)
#else
tiff_bps > 16
#endif
|| tiff_samples > 6 || colors > 4)
is_raw = 0;
if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000)
is_raw = 0;
#ifdef NO_JASPER
if (load_raw == &CLASS redcine_load_raw) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
ifname, "libjasper");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER;
#endif
}
#endif
#ifdef NO_JPEG
if (load_raw == &CLASS kodak_jpeg_load_raw ||
load_raw == &CLASS lossy_dng_load_raw) {
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s: You must link dcraw with %s!!\n"),
ifname, "libjpeg");
#endif
is_raw = 0;
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB;
#endif
}
#endif
if (!cdesc[0])
strcpy (cdesc, colors == 3 ? "RGBG":"GMCY");
if (!raw_height) raw_height = height;
if (!raw_width ) raw_width = width;
if (filters > 999 && colors == 3)
filters |= ((filters >> 2 & 0x22222222) |
(filters << 2 & 0x88888888)) & filters << 1;
notraw:
if (flip == UINT_MAX) flip = tiff_flip;
if (flip == UINT_MAX) flip = 0;
// Convert from degrees to bit-field if needed
if(flip > 89 || flip < -89)
{
switch ((flip+3600) % 360)
{
case 270: flip = 5; break;
case 180: flip = 3; break;
case 90: flip = 6; break;
}
}
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2);
#endif
}
//@end COMMON
//@out FILEIO
#ifndef NO_LCMS
void CLASS apply_profile (const char *input, const char *output)
{
char *prof;
cmsHPROFILE hInProfile=0, hOutProfile=0;
cmsHTRANSFORM hTransform;
FILE *fp;
unsigned size;
if (strcmp (input, "embed"))
hInProfile = cmsOpenProfileFromFile (input, "r");
else if (profile_length) {
#ifndef LIBRAW_LIBRARY_BUILD
prof = (char *) malloc (profile_length);
merror (prof, "apply_profile()");
fseek (ifp, profile_offset, SEEK_SET);
fread (prof, 1, profile_length, ifp);
hInProfile = cmsOpenProfileFromMem (prof, profile_length);
free (prof);
#else
hInProfile = cmsOpenProfileFromMem (imgdata.color.profile, profile_length);
#endif
} else
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_EMBEDDED_PROFILE;
#endif
#ifdef DCRAW_VERBOSE
fprintf (stderr,_("%s has no embedded profile.\n"), ifname);
#endif
}
if (!hInProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_NO_INPUT_PROFILE;
#endif
return;
}
if (!output)
hOutProfile = cmsCreate_sRGBProfile();
else if ((fp = fopen (output, "rb"))) {
fread (&size, 4, 1, fp);
fseek (fp, 0, SEEK_SET);
oprof = (unsigned *) malloc (size = ntohl(size));
merror (oprof, "apply_profile()");
fread (oprof, 1, size, fp);
fclose (fp);
if (!(hOutProfile = cmsOpenProfileFromMem (oprof, size))) {
free (oprof);
oprof = 0;
}
}
#ifdef DCRAW_VERBOSE
else
fprintf (stderr,_("Cannot open file %s!\n"), output);
#endif
if (!hOutProfile)
{
#ifdef LIBRAW_LIBRARY_BUILD
imgdata.process_warnings |= LIBRAW_WARN_BAD_OUTPUT_PROFILE;
#endif
goto quit;
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Applying color profile...\n"));
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,0,2);
#endif
hTransform = cmsCreateTransform (hInProfile, TYPE_RGBA_16,
hOutProfile, TYPE_RGBA_16, INTENT_PERCEPTUAL, 0);
cmsDoTransform (hTransform, image, image, width*height);
raw_color = 1; /* Don't use rgb_cam with a profile */
cmsDeleteTransform (hTransform);
cmsCloseProfile (hOutProfile);
quit:
cmsCloseProfile (hInProfile);
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_APPLY_PROFILE,1,2);
#endif
}
#endif
//@end FILEIO
//@out COMMON
void CLASS convert_to_rgb()
{
#ifndef LIBRAW_LIBRARY_BUILD
int row, col, c;
#endif
int i, j, k;
#ifndef LIBRAW_LIBRARY_BUILD
ushort *img;
float out[3];
#endif
float out_cam[3][4];
double num, inverse[3][3];
static const double xyzd50_srgb[3][3] =
{ { 0.436083, 0.385083, 0.143055 },
{ 0.222507, 0.716888, 0.060608 },
{ 0.013930, 0.097097, 0.714022 } };
static const double rgb_rgb[3][3] =
{ { 1,0,0 }, { 0,1,0 }, { 0,0,1 } };
static const double adobe_rgb[3][3] =
{ { 0.715146, 0.284856, 0.000000 },
{ 0.000000, 1.000000, 0.000000 },
{ 0.000000, 0.041166, 0.958839 } };
static const double wide_rgb[3][3] =
{ { 0.593087, 0.404710, 0.002206 },
{ 0.095413, 0.843149, 0.061439 },
{ 0.011621, 0.069091, 0.919288 } };
static const double prophoto_rgb[3][3] =
{ { 0.529317, 0.330092, 0.140588 },
{ 0.098368, 0.873465, 0.028169 },
{ 0.016879, 0.117663, 0.865457 } };
static const double aces_rgb[3][3] =
{ { 0.432996, 0.375380, 0.189317 },
{ 0.089427, 0.816523, 0.102989 },
{ 0.019165, 0.118150, 0.941914 } };
static const double (*out_rgb[])[3] =
{ rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb };
static const char *name[] =
{ "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" };
static const unsigned phead[] =
{ 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0,
0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d };
unsigned pbody[] =
{ 10, 0x63707274, 0, 36, /* cprt */
0x64657363, 0, 40, /* desc */
0x77747074, 0, 20, /* wtpt */
0x626b7074, 0, 20, /* bkpt */
0x72545243, 0, 14, /* rTRC */
0x67545243, 0, 14, /* gTRC */
0x62545243, 0, 14, /* bTRC */
0x7258595a, 0, 20, /* rXYZ */
0x6758595a, 0, 20, /* gXYZ */
0x6258595a, 0, 20 }; /* bXYZ */
static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc };
unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 };
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2);
#endif
gamma_curve (gamm[0], gamm[1], 0, 0);
memcpy (out_cam, rgb_cam, sizeof out_cam);
#ifndef LIBRAW_LIBRARY_BUILD
raw_color |= colors == 1 || document_mode ||
output_color < 1 || output_color > 6;
#else
raw_color |= colors == 1 ||
output_color < 1 || output_color > 6;
#endif
if (!raw_color) {
oprof = (unsigned *) calloc (phead[0], 1);
merror (oprof, "convert_to_rgb()");
memcpy (oprof, phead, sizeof phead);
if (output_color == 5) oprof[4] = oprof[5];
oprof[0] = 132 + 12*pbody[0];
for (i=0; i < pbody[0]; i++) {
oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874;
pbody[i*3+2] = oprof[0];
oprof[0] += (pbody[i*3+3] + 3) & -4;
}
memcpy (oprof+32, pbody, sizeof pbody);
oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1;
memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite);
pcurve[3] = (short)(256/gamm[5]+0.5) << 16;
for (i=4; i < 7; i++)
memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve);
pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3);
for (i=0; i < 3; i++)
for (j=0; j < 3; j++) {
for (num = k=0; k < 3; k++)
num += xyzd50_srgb[i][k] * inverse[j][k];
oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5;
}
for (i=0; i < phead[0]/4; i++)
oprof[i] = htonl(oprof[i]);
strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw");
strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]);
for (i=0; i < 3; i++)
for (j=0; j < colors; j++)
for (out_cam[i][j] = k=0; k < 3; k++)
out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j];
}
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr, raw_color ? _("Building histograms...\n") :
_("Converting to %s colorspace...\n"), name[output_color-1]);
#endif
#ifdef LIBRAW_LIBRARY_BUILD
convert_to_rgb_loop(out_cam);
#else
memset (histogram, 0, sizeof histogram);
for (img=image[0], row=0; row < height; row++)
for (col=0; col < width; col++, img+=4) {
if (!raw_color) {
out[0] = out[1] = out[2] = 0;
FORCC {
out[0] += out_cam[0][c] * img[c];
out[1] += out_cam[1][c] * img[c];
out[2] += out_cam[2][c] * img[c];
}
FORC3 img[c] = CLIP((int) out[c]);
}
else if (document_mode)
img[0] = img[fcol(row,col)];
FORCC histogram[c][img[c] >> 3]++;
}
#endif
if (colors == 4 && output_color) colors = 3;
#ifndef LIBRAW_LIBRARY_BUILD
if (document_mode && filters) colors = 1;
#endif
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2);
#endif
}
void CLASS fuji_rotate()
{
int i, row, col;
double step;
float r, c, fr, fc;
unsigned ur, uc;
ushort wide, high, (*img)[4], (*pix)[4];
if (!fuji_width) return;
#ifdef DCRAW_VERBOSE
if (verbose)
fprintf (stderr,_("Rotating image 45 degrees...\n"));
#endif
fuji_width = (fuji_width - 1 + shrink) >> shrink;
step = sqrt(0.5);
wide = fuji_width / step;
high = (height - fuji_width) / step;
img = (ushort (*)[4]) calloc (high, wide*sizeof *img);
merror (img, "fuji_rotate()");
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2);
#endif
for (row=0; row < high; row++)
for (col=0; col < wide; col++) {
ur = r = fuji_width + (row-col)*step;
uc = c = (row+col)*step;
if (ur > height-2 || uc > width-2) continue;
fr = r - ur;
fc = c - uc;
pix = image + ur*width + uc;
for (i=0; i < colors; i++)
img[row*wide+col][i] =
(pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) +
(pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr;
}
free (image);
width = wide;
height = high;
image = img;
fuji_width = 0;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2);
#endif
}
void CLASS stretch()
{
ushort newdim, (*img)[4], *pix0, *pix1;
int row, col, c;
double rc, frac;
if (pixel_aspect == 1) return;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2);
#endif
#ifdef DCRAW_VERBOSE
if (verbose) fprintf (stderr,_("Stretching the image...\n"));
#endif
if (pixel_aspect < 1) {
newdim = height / pixel_aspect + 0.5;
img = (ushort (*)[4]) calloc (width, newdim*sizeof *img);
merror (img, "stretch()");
for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) {
frac = rc - (c = rc);
pix0 = pix1 = image[c*width];
if (c+1 < height) pix1 += width*4;
for (col=0; col < width; col++, pix0+=4, pix1+=4)
FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
}
height = newdim;
} else {
newdim = width * pixel_aspect + 0.5;
img = (ushort (*)[4]) calloc (height, newdim*sizeof *img);
merror (img, "stretch()");
for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) {
frac = rc - (c = rc);
pix0 = pix1 = image[c];
if (c+1 < width) pix1 += 4;
for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4)
FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5;
}
width = newdim;
}
free (image);
image = img;
#ifdef LIBRAW_LIBRARY_BUILD
RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2);
#endif
}
int CLASS flip_index (int row, int col)
{
if (flip & 4) SWAP(row,col);
if (flip & 2) row = iheight - 1 - row;
if (flip & 1) col = iwidth - 1 - col;
return row * iwidth + col;
}
//@end COMMON
struct tiff_tag {
ushort tag, type;
int count;
union { char c[4]; short s[2]; int i; } val;
};
struct tiff_hdr {
ushort t_order, magic;
int ifd;
ushort pad, ntag;
struct tiff_tag tag[23];
int nextifd;
ushort pad2, nexif;
struct tiff_tag exif[4];
ushort pad3, ngps;
struct tiff_tag gpst[10];
short bps[4];
int rat[10];
unsigned gps[26];
char t_desc[512], t_make[64], t_model[64], soft[32], date[20], t_artist[64];
};
//@out COMMON
void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag,
ushort tag, ushort type, int count, int val)
{
struct tiff_tag *tt;
int c;
tt = (struct tiff_tag *)(ntag+1) + (*ntag)++;
tt->val.i = val;
if (type == 1 && count <= 4)
FORC(4) tt->val.c[c] = val >> (c << 3);
else if (type == 2) {
count = strnlen((char *)th + val, count-1) + 1;
if (count <= 4)
FORC(4) tt->val.c[c] = ((char *)th)[val+c];
} else if (type == 3 && count <= 2)
FORC(2) tt->val.s[c] = val >> (c << 4);
tt->count = count;
tt->type = type;
tt->tag = tag;
}
#define TOFF(ptr) ((char *)(&(ptr)) - (char *)th)
void CLASS tiff_head (struct tiff_hdr *th, int full)
{
int c, psize=0;
struct tm *t;
memset (th, 0, sizeof *th);
th->t_order = htonl(0x4d4d4949) >> 16;
th->magic = 42;
th->ifd = 10;
th->rat[0] = th->rat[2] = 300;
th->rat[1] = th->rat[3] = 1;
FORC(6) th->rat[4+c] = 1000000;
th->rat[4] *= shutter;
th->rat[6] *= aperture;
th->rat[8] *= focal_len;
strncpy (th->t_desc, desc, 512);
strncpy (th->t_make, make, 64);
strncpy (th->t_model, model, 64);
strcpy (th->soft, "dcraw v" DCRAW_VERSION);
t = localtime (×tamp);
sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d",
t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec);
strncpy (th->t_artist, artist, 64);
if (full) {
tiff_set (th, &th->ntag, 254, 4, 1, 0);
tiff_set (th, &th->ntag, 256, 4, 1, width);
tiff_set (th, &th->ntag, 257, 4, 1, height);
tiff_set (th, &th->ntag, 258, 3, colors, output_bps);
if (colors > 2)
th->tag[th->ntag-1].val.i = TOFF(th->bps);
FORC4 th->bps[c] = output_bps;
tiff_set (th, &th->ntag, 259, 3, 1, 1);
tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1));
}
tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc));
tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make));
tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model));
if (full) {
if (oprof) psize = ntohl(oprof[0]);
tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize);
tiff_set (th, &th->ntag, 277, 3, 1, colors);
tiff_set (th, &th->ntag, 278, 4, 1, height);
tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8);
} else
tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0');
tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0]));
tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2]));
tiff_set (th, &th->ntag, 284, 3, 1, 1);
tiff_set (th, &th->ntag, 296, 3, 1, 2);
tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft));
tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date));
tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist));
tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif));
if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th);
tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4]));
tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6]));
tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed);
tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8]));
if (gpsdata[1]) {
tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps));
tiff_set (th, &th->ngps, 0, 1, 4, 0x202);
tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]);
tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0]));
tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]);
tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6]));
tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]);
tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18]));
tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12]));
tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20]));
tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23]));
memcpy (th->gps, gpsdata, sizeof th->gps);
}
}
#ifdef LIBRAW_LIBRARY_BUILD
void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length)
{
ushort exif[5];
struct tiff_hdr th;
fputc (0xff, tfp);
fputc (0xd8, tfp);
if (strcmp (t_humb+6, "Exif")) {
memcpy (exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons (8 + sizeof th);
fwrite (exif, 1, sizeof exif, tfp);
tiff_head (&th, 0);
fwrite (&th, 1, sizeof th, tfp);
}
fwrite (t_humb+2, 1, t_humb_length-2, tfp);
}
void CLASS jpeg_thumb()
{
char *thumb;
thumb = (char *) malloc (thumb_length);
merror (thumb, "jpeg_thumb()");
fread (thumb, 1, thumb_length, ifp);
jpeg_thumb_writer(ofp,thumb,thumb_length);
free (thumb);
}
#else
void CLASS jpeg_thumb()
{
char *thumb;
ushort exif[5];
struct tiff_hdr th;
thumb = (char *) malloc (thumb_length);
merror (thumb, "jpeg_thumb()");
fread (thumb, 1, thumb_length, ifp);
fputc (0xff, ofp);
fputc (0xd8, ofp);
if (strcmp (thumb+6, "Exif")) {
memcpy (exif, "\xff\xe1 Exif\0\0", 10);
exif[1] = htons (8 + sizeof th);
fwrite (exif, 1, sizeof exif, ofp);
tiff_head (&th, 0);
fwrite (&th, 1, sizeof th, ofp);
}
fwrite (thumb+2, 1, thumb_length-2, ofp);
free (thumb);
}
#endif
void CLASS write_ppm_tiff()
{
struct tiff_hdr th;
uchar *ppm;
ushort *ppm2;
int c, row, col, soff, rstep, cstep;
int perc, val, total, t_white=0x2000;
#ifdef LIBRAW_LIBRARY_BUILD
perc = width * height * auto_bright_thr;
#else
perc = width * height * 0.01; /* 99th percentile white level */
#endif
if (fuji_width) perc /= 2;
if (!((highlight & ~2) || no_auto_bright))
for (t_white=c=0; c < colors; c++) {
for (val=0x2000, total=0; --val > 32; )
if ((total += histogram[c][val]) > perc) break;
if (t_white < val) t_white = val;
}
gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright);
iheight = height;
iwidth = width;
if (flip & 4) SWAP(height,width);
ppm = (uchar *) calloc (width, colors*output_bps/8);
ppm2 = (ushort *) ppm;
merror (ppm, "write_ppm_tiff()");
if (output_tiff) {
tiff_head (&th, 1);
fwrite (&th, sizeof th, 1, ofp);
if (oprof)
fwrite (oprof, ntohl(oprof[0]), 1, ofp);
} else if (colors > 3)
fprintf (ofp,
"P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
width, height, colors, (1 << output_bps)-1, cdesc);
else
fprintf (ofp, "P%d\n%d %d\n%d\n",
colors/2+5, width, height, (1 << output_bps)-1);
soff = flip_index (0, 0);
cstep = flip_index (0, 1) - soff;
rstep = flip_index (1, 0) - flip_index (0, width);
for (row=0; row < height; row++, soff += rstep) {
for (col=0; col < width; col++, soff += cstep)
if (output_bps == 8)
FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8;
else FORCC ppm2[col*colors+c] = curve[image[soff][c]];
if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa)
swab ((char*)ppm2, (char*)ppm2, width*colors*2);
fwrite (ppm, colors*output_bps/8, width, ofp);
}
free (ppm);
}
//@end COMMON
int CLASS main (int argc, const char **argv)
{
int arg, status=0, quality, i, c;
int timestamp_only=0, thumbnail_only=0, identify_only=0;
int user_qual=-1, user_black=-1, user_sat=-1, user_flip=-1;
int use_fuji_rotate=1, write_to_stdout=0, read_from_stdin=0;
const char *sp, *bpfile=0, *dark_frame=0, *write_ext;
char opm, opt, *ofname, *cp;
struct utimbuf ut;
#ifndef NO_LCMS
const char *cam_profile=0, *out_profile=0;
#endif
#ifndef LOCALTIME
putenv ((char *) "TZ=UTC");
#endif
#ifdef LOCALEDIR
setlocale (LC_CTYPE, "");
setlocale (LC_MESSAGES, "");
bindtextdomain ("dcraw", LOCALEDIR);
textdomain ("dcraw");
#endif
if (argc == 1) {
printf(_("\nRaw photo decoder \"dcraw\" v%s"), DCRAW_VERSION);
printf(_("\nby Dave Coffin, dcoffin a cybercom o net\n"));
printf(_("\nUsage: %s [OPTION]... [FILE]...\n\n"), argv[0]);
puts(_("-v Print verbose messages"));
puts(_("-c Write image data to standard output"));
puts(_("-e Extract embedded thumbnail image"));
puts(_("-i Identify files without decoding them"));
puts(_("-i -v Identify files and show metadata"));
puts(_("-z Change file dates to camera timestamp"));
puts(_("-w Use camera white balance, if possible"));
puts(_("-a Average the whole image for white balance"));
puts(_("-A <x y w h> Average a grey box for white balance"));
puts(_("-r <r g b g> Set custom white balance"));
puts(_("+M/-M Use/don't use an embedded color matrix"));
puts(_("-C <r b> Correct chromatic aberration"));
puts(_("-P <file> Fix the dead pixels listed in this file"));
puts(_("-K <file> Subtract dark frame (16-bit raw PGM)"));
puts(_("-k <num> Set the darkness level"));
puts(_("-S <num> Set the saturation level"));
puts(_("-n <num> Set threshold for wavelet denoising"));
puts(_("-H [0-9] Highlight mode (0=clip, 1=unclip, 2=blend, 3+=rebuild)"));
puts(_("-t [0-7] Flip image (0=none, 3=180, 5=90CCW, 6=90CW)"));
puts(_("-o [0-5] Output colorspace (raw,sRGB,Adobe,Wide,ProPhoto,XYZ)"));
#ifndef NO_LCMS
puts(_("-o <file> Apply output ICC profile from file"));
puts(_("-p <file> Apply camera ICC profile from file or \"embed\""));
#endif
puts(_("-d Document mode (no color, no interpolation)"));
puts(_("-D Document mode without scaling (totally raw)"));
puts(_("-j Don't stretch or rotate raw pixels"));
puts(_("-W Don't automatically brighten the image"));
puts(_("-b <num> Adjust brightness (default = 1.0)"));
puts(_("-g <p ts> Set custom gamma curve (default = 2.222 4.5)"));
puts(_("-q [0-3] Set the interpolation quality"));
puts(_("-h Half-size color image (twice as fast as \"-q 0\")"));
puts(_("-f Interpolate RGGB as four colors"));
puts(_("-m <num> Apply a 3x3 median filter to R-G and B-G"));
puts(_("-s [0..N-1] Select one raw image or \"all\" from each file"));
puts(_("-6 Write 16-bit instead of 8-bit"));
puts(_("-4 Linear 16-bit, same as \"-6 -W -g 1 1\""));
puts(_("-T Write TIFF instead of PPM"));
puts("");
return 1;
}
argv[argc] = "";
for (arg=1; (((opm = argv[arg][0]) - 2) | 2) == '+'; ) {
opt = argv[arg++][1];
if ((cp = (char *) strchr (sp="nbrkStqmHACg", opt)))
for (i=0; i < "114111111422"[cp-sp]-'0'; i++)
if (!isdigit(argv[arg+i][0])) {
fprintf (stderr,_("Non-numeric argument to \"-%c\"\n"), opt);
return 1;
}
switch (opt) {
case 'n': threshold = atof(argv[arg++]); break;
case 'b': bright = atof(argv[arg++]); break;
case 'r':
FORC4 user_mul[c] = atof(argv[arg++]); break;
case 'C': aber[0] = 1 / atof(argv[arg++]);
aber[2] = 1 / atof(argv[arg++]); break;
case 'g': gamm[0] = atof(argv[arg++]);
gamm[1] = atof(argv[arg++]);
if (gamm[0]) gamm[0] = 1/gamm[0]; break;
case 'k': user_black = atoi(argv[arg++]); break;
case 'S': user_sat = atoi(argv[arg++]); break;
case 't': user_flip = atoi(argv[arg++]); break;
case 'q': user_qual = atoi(argv[arg++]); break;
case 'm': med_passes = atoi(argv[arg++]); break;
case 'H': highlight = atoi(argv[arg++]); break;
case 's':
shot_select = abs(atoi(argv[arg]));
multi_out = !strcmp(argv[arg++],"all");
break;
case 'o':
if (isdigit(argv[arg][0]) && !argv[arg][1])
output_color = atoi(argv[arg++]);
#ifndef NO_LCMS
else out_profile = argv[arg++];
break;
case 'p': cam_profile = argv[arg++];
#endif
break;
case 'P': bpfile = argv[arg++]; break;
case 'K': dark_frame = argv[arg++]; break;
case 'z': timestamp_only = 1; break;
case 'e': thumbnail_only = 1; break;
case 'i': identify_only = 1; break;
case 'c': write_to_stdout = 1; break;
case 'v': verbose = 1; break;
case 'h': half_size = 1; break;
case 'f': four_color_rgb = 1; break;
case 'A': FORC4 greybox[c] = atoi(argv[arg++]);
case 'a': use_auto_wb = 1; break;
case 'w': use_camera_wb = 1; break;
case 'M': use_camera_matrix = 3 * (opm == '+'); break;
case 'I': read_from_stdin = 1; break;
case 'E': document_mode++;
case 'D': document_mode++;
case 'd': document_mode++;
case 'j': use_fuji_rotate = 0; break;
case 'W': no_auto_bright = 1; break;
case 'T': output_tiff = 1; break;
case '4': gamm[0] = gamm[1] =
no_auto_bright = 1;
case '6': output_bps = 16; break;
default:
fprintf (stderr,_("Unknown option \"-%c\".\n"), opt);
return 1;
}
}
if (arg == argc) {
fprintf (stderr,_("No files to process.\n"));
return 1;
}
if (write_to_stdout) {
if (isatty(1)) {
fprintf (stderr,_("Will not write an image to the terminal!\n"));
return 1;
}
#if defined(WIN32) || defined(DJGPP) || defined(__CYGWIN__)
if (setmode(1,O_BINARY) < 0) {
perror ("setmode()");
return 1;
}
#endif
}
for ( ; arg < argc; arg++) {
status = 1;
raw_image = 0;
image = 0;
oprof = 0;
meta_data = ofname = 0;
ofp = stdout;
if (setjmp (failure)) {
if (fileno(ifp) > 2) fclose(ifp);
if (fileno(ofp) > 2) fclose(ofp);
status = 1;
goto cleanup;
}
ifname = argv[arg];
if (!(ifp = fopen (ifname, "rb"))) {
perror (ifname);
continue;
}
status = (identify(),!is_raw);
if (user_flip >= 0)
flip = user_flip;
switch ((flip+3600) % 360) {
case 270: flip = 5; break;
case 180: flip = 3; break;
case 90: flip = 6;
}
if (timestamp_only) {
if ((status = !timestamp))
fprintf (stderr,_("%s has no timestamp.\n"), ifname);
else if (identify_only)
printf ("%10ld%10d %s\n", (long) timestamp, shot_order, ifname);
else {
if (verbose)
fprintf (stderr,_("%s time set to %d.\n"), ifname, (int) timestamp);
ut.actime = ut.modtime = timestamp;
utime (ifname, &ut);
}
goto next;
}
write_fun = &CLASS write_ppm_tiff;
if (thumbnail_only) {
if ((status = !thumb_offset)) {
fprintf (stderr,_("%s has no thumbnail.\n"), ifname);
goto next;
} else if (thumb_load_raw) {
load_raw = thumb_load_raw;
data_offset = thumb_offset;
height = thumb_height;
width = thumb_width;
filters = 0;
colors = 3;
} else {
fseek (ifp, thumb_offset, SEEK_SET);
write_fun = write_thumb;
goto thumbnail;
}
}
if (load_raw == &CLASS kodak_ycbcr_load_raw) {
height += height & 1;
width += width & 1;
}
if (identify_only && verbose && make[0]) {
printf (_("\nFilename: %s\n"), ifname);
printf (_("Timestamp: %s"), ctime(×tamp));
printf (_("Camera: %s %s\n"), make, model);
if (artist[0])
printf (_("Owner: %s\n"), artist);
if (dng_version) {
printf (_("DNG Version: "));
for (i=24; i >= 0; i -= 8)
printf ("%d%c", dng_version >> i & 255, i ? '.':'\n');
}
printf (_("ISO speed: %d\n"), (int) iso_speed);
printf (_("Shutter: "));
if (shutter > 0 && shutter < 1)
shutter = (printf ("1/"), 1 / shutter);
printf (_("%0.1f sec\n"), shutter);
printf (_("Aperture: f/%0.1f\n"), aperture);
printf (_("Focal length: %0.1f mm\n"), focal_len);
printf (_("Embedded ICC profile: %s\n"), profile_length ? _("yes"):_("no"));
printf (_("Number of raw images: %d\n"), is_raw);
if (pixel_aspect != 1)
printf (_("Pixel Aspect Ratio: %0.6f\n"), pixel_aspect);
if (thumb_offset)
printf (_("Thumb size: %4d x %d\n"), thumb_width, thumb_height);
printf (_("Full size: %4d x %d\n"), raw_width, raw_height);
} else if (!is_raw)
fprintf (stderr,_("Cannot decode file %s\n"), ifname);
if (!is_raw) goto next;
shrink = filters && (half_size || (!identify_only &&
(threshold || aber[0] != 1 || aber[2] != 1)));
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (identify_only) {
if (verbose) {
if (document_mode == 3) {
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (use_fuji_rotate) {
if (fuji_width) {
fuji_width = (fuji_width - 1 + shrink) >> shrink;
iwidth = fuji_width / sqrt(0.5);
iheight = (iheight - fuji_width) / sqrt(0.5);
} else {
if (pixel_aspect < 1) iheight = iheight / pixel_aspect + 0.5;
if (pixel_aspect > 1) iwidth = iwidth * pixel_aspect + 0.5;
}
}
if (flip & 4)
SWAP(iheight,iwidth);
printf (_("Image size: %4d x %d\n"), width, height);
printf (_("Output size: %4d x %d\n"), iwidth, iheight);
printf (_("Raw colors: %d"), colors);
if (filters) {
int fhigh = 2, fwide = 2;
if ((filters ^ (filters >> 8)) & 0xff) fhigh = 4;
if ((filters ^ (filters >> 16)) & 0xffff) fhigh = 8;
if (filters == 1) fhigh = fwide = 16;
if (filters == 9) fhigh = fwide = 6;
printf (_("\nFilter pattern: "));
for (i=0; i < fhigh; i++)
for (c = i && putchar('/') && 0; c < fwide; c++)
putchar (cdesc[fcol(i,c)]);
}
printf (_("\nDaylight multipliers:"));
FORCC printf (" %f", pre_mul[c]);
if (cam_mul[0] > 0) {
printf (_("\nCamera multipliers:"));
FORC4 printf (" %f", cam_mul[c]);
}
putchar ('\n');
} else
printf (_("%s is a %s %s image.\n"), ifname, make, model);
next:
fclose(ifp);
continue;
}
if (meta_length) {
meta_data = (char *) malloc (meta_length);
merror (meta_data, "main()");
}
if (filters || colors == 1) {
raw_image = (ushort *) calloc ((raw_height+7), raw_width*2);
merror (raw_image, "main()");
} else {
image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image);
merror (image, "main()");
}
if (verbose)
fprintf (stderr,_("Loading %s %s image from %s ...\n"),
make, model, ifname);
if (shot_select >= is_raw)
fprintf (stderr,_("%s: \"-s %d\" requests a nonexistent image!\n"),
ifname, shot_select);
fseeko (ifp, data_offset, SEEK_SET);
if (raw_image && read_from_stdin)
fread (raw_image, 2, raw_height*raw_width, stdin);
else (*load_raw)();
if (document_mode == 3) {
top_margin = left_margin = fuji_width = 0;
height = raw_height;
width = raw_width;
}
iheight = (height + shrink) >> shrink;
iwidth = (width + shrink) >> shrink;
if (raw_image) {
image = (ushort (*)[4]) calloc (iheight, iwidth*sizeof *image);
merror (image, "main()");
crop_masked_pixels();
free (raw_image);
}
if (zero_is_bad) remove_zeroes();
bad_pixels (bpfile);
if (dark_frame) subtract (dark_frame);
quality = 2 + !fuji_width;
if (user_qual >= 0) quality = user_qual;
i = cblack[3];
FORC3 if (i > cblack[c]) i = cblack[c];
FORC4 cblack[c] -= i;
black += i;
i = cblack[6];
FORC (cblack[4] * cblack[5])
if (i > cblack[6+c]) i = cblack[6+c];
FORC (cblack[4] * cblack[5])
cblack[6+c] -= i;
black += i;
if (user_black >= 0) black = user_black;
FORC4 cblack[c] += black;
if (user_sat > 0) maximum = user_sat;
#ifdef COLORCHECK
colorcheck();
#endif
if (is_foveon) {
if (document_mode || load_raw == &CLASS foveon_dp_load_raw) {
for (i=0; i < height*width*4; i++)
if ((short) image[0][i] < 0) image[0][i] = 0;
} else foveon_interpolate();
} else if (document_mode < 2)
scale_colors();
pre_interpolate();
if (filters && !document_mode) {
if (quality == 0)
lin_interpolate();
else if (quality == 1 || colors > 3)
vng_interpolate();
else if (quality == 2 && filters > 1000)
ppg_interpolate();
else if (filters == 9)
xtrans_interpolate (quality*2-3);
else
ahd_interpolate();
}
if (mix_green)
for (colors=3, i=0; i < height*width; i++)
image[i][1] = (image[i][1] + image[i][3]) >> 1;
if (!is_foveon && colors == 3) median_filter();
if (!is_foveon && highlight == 2) blend_highlights();
if (!is_foveon && highlight > 2) recover_highlights();
if (use_fuji_rotate) fuji_rotate();
#ifndef NO_LCMS
if (cam_profile) apply_profile (cam_profile, out_profile);
#endif
convert_to_rgb();
if (use_fuji_rotate) stretch();
thumbnail:
if (write_fun == &CLASS jpeg_thumb)
write_ext = ".jpg";
else if (output_tiff && write_fun == &CLASS write_ppm_tiff)
write_ext = ".tiff";
else
write_ext = ".pgm\0.ppm\0.ppm\0.pam" + colors*5-5;
ofname = (char *) malloc (strlen(ifname) + 64);
merror (ofname, "main()");
if (write_to_stdout)
strcpy (ofname,_("standard output"));
else {
strcpy (ofname, ifname);
if ((cp = strrchr (ofname, '.'))) *cp = 0;
if (multi_out)
sprintf (ofname+strlen(ofname), "_%0*d",
snprintf(0,0,"%d",is_raw-1), shot_select);
if (thumbnail_only)
strcat (ofname, ".thumb");
strcat (ofname, write_ext);
ofp = fopen (ofname, "wb");
if (!ofp) {
status = 1;
perror (ofname);
goto cleanup;
}
}
if (verbose)
fprintf (stderr,_("Writing data to %s ...\n"), ofname);
(*write_fun)();
fclose(ifp);
if (ofp != stdout) fclose(ofp);
cleanup:
if (meta_data) free (meta_data);
if (ofname) free (ofname);
if (oprof) free (oprof);
if (image) free (image);
if (multi_out) {
if (++shot_select < is_raw) arg--;
else shot_select = 0;
}
}
return status;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2804_1 |
crossvul-cpp_data_good_766_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L OOO CCCC AAA L EEEEE %
% L O O C A A L E %
% L O O C AAAAA L EEE %
% L O O C A A L E %
% LLLLL OOO CCCC A A LLLLL EEEEE %
% %
% %
% MagickCore Image Locale Methods %
% %
% Software Design %
% Cristy %
% July 2003 %
% %
% %
% Copyright 1999-2019 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 %
% %
% https://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 "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/client.h"
#include "MagickCore/configure.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image-private.h"
#include "MagickCore/linked-list.h"
#include "MagickCore/locale_.h"
#include "MagickCore/locale-private.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/nt-base-private.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/token.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
Define declarations.
*/
#if defined(MAGICKCORE_HAVE_NEWLOCALE) || defined(MAGICKCORE_WINDOWS_SUPPORT)
# define MAGICKCORE_LOCALE_SUPPORT
#endif
#define LocaleFilename "locale.xml"
/*
Static declarations.
*/
static const char
*LocaleMap =
"<?xml version=\"1.0\"?>"
"<localemap>"
" <locale name=\"C\">"
" <Exception>"
" <Message name=\"\">"
" </Message>"
" </Exception>"
" </locale>"
"</localemap>";
#ifdef __VMS
#define asciimap AsciiMap
#endif
#if !defined(MAGICKCORE_HAVE_STRCASECMP) || !defined(MAGICKCORE_HAVE_STRNCASECMP)
static const unsigned char
AsciiMap[] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73,
0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b,
0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83,
0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b,
0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3,
0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xe1, 0xe2, 0xe3, 0xe4, 0xc5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb,
0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3,
0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb,
0xfc, 0xfd, 0xfe, 0xff,
};
#endif
static SemaphoreInfo
*locale_semaphore = (SemaphoreInfo *) NULL;
static SplayTreeInfo
*locale_cache = (SplayTreeInfo *) NULL;
#if defined(MAGICKCORE_LOCALE_SUPPORT)
static volatile locale_t
c_locale = (locale_t) NULL;
#endif
/*
Forward declarations.
*/
static MagickBooleanType
IsLocaleTreeInstantiated(ExceptionInfo *),
LoadLocaleCache(SplayTreeInfo *,const char *,const char *,const char *,
const size_t,ExceptionInfo *);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e C L o c a l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireCLocale() allocates the C locale object, or (locale_t) 0 with
% errno set if it cannot be acquired.
%
% The format of the AcquireCLocale method is:
%
% locale_t AcquireCLocale(void)
%
*/
static locale_t AcquireCLocale(void)
{
#if defined(MAGICKCORE_HAVE_NEWLOCALE)
if (c_locale == (locale_t) NULL)
c_locale=newlocale(LC_ALL_MASK,"C",(locale_t) 0);
#elif defined(MAGICKCORE_WINDOWS_SUPPORT) && !defined(__MINGW32__)
if (c_locale == (locale_t) NULL)
c_locale=_create_locale(LC_ALL,"C");
#endif
return(c_locale);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e L o c a l e S p l a y T r e e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireLocaleSplayTree() caches one or more locale configurations which
% provides a mapping between locale attributes and a locale tag.
%
% The format of the AcquireLocaleSplayTree method is:
%
% SplayTreeInfo *AcquireLocaleSplayTree(const char *filename,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o filename: the font file tag.
%
% o locale: the actual locale.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void *DestroyLocaleNode(void *locale_info)
{
register LocaleInfo
*p;
p=(LocaleInfo *) locale_info;
if (p->path != (char *) NULL)
p->path=DestroyString(p->path);
if (p->tag != (char *) NULL)
p->tag=DestroyString(p->tag);
if (p->message != (char *) NULL)
p->message=DestroyString(p->message);
return(RelinquishMagickMemory(p));
}
static SplayTreeInfo *AcquireLocaleSplayTree(const char *filename,
const char *locale,ExceptionInfo *exception)
{
MagickStatusType
status;
SplayTreeInfo
*cache;
cache=NewSplayTree(CompareSplayTreeString,(void *(*)(void *)) NULL,
DestroyLocaleNode);
status=MagickTrue;
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
{
const StringInfo
*option;
LinkedListInfo
*options;
options=GetLocaleOptions(filename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
status&=LoadLocaleCache(cache,(const char *)
GetStringInfoDatum(option),GetStringInfoPath(option),locale,0,
exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyLocaleOptions(options);
if (GetNumberOfNodesInSplayTree(cache) == 0)
{
options=GetLocaleOptions("english.xml",exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
status&=LoadLocaleCache(cache,(const char *)
GetStringInfoDatum(option),GetStringInfoPath(option),locale,0,
exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyLocaleOptions(options);
}
}
#endif
if (GetNumberOfNodesInSplayTree(cache) == 0)
status&=LoadLocaleCache(cache,LocaleMap,"built-in",locale,0,
exception);
return(cache);
}
#if defined(MAGICKCORE_LOCALE_SUPPORT)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y C L o c a l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyCLocale() releases the resources allocated for a locale object
% returned by a call to the AcquireCLocale() method.
%
% The format of the DestroyCLocale method is:
%
% void DestroyCLocale(void)
%
*/
static void DestroyCLocale(void)
{
if (c_locale != (locale_t) NULL)
freelocale(c_locale);
c_locale=(locale_t) NULL;
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y L o c a l e O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyLocaleOptions() releases memory associated with an locale
% messages.
%
% The format of the DestroyProfiles method is:
%
% LinkedListInfo *DestroyLocaleOptions(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
static void *DestroyOptions(void *message)
{
return(DestroyStringInfo((StringInfo *) message));
}
MagickExport LinkedListInfo *DestroyLocaleOptions(LinkedListInfo *messages)
{
assert(messages != (LinkedListInfo *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
return(DestroyLinkedList(messages,DestroyOptions));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F o r m a t L o c a l e F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatLocaleFile() prints formatted output of a variable argument list to a
% file in the "C" locale.
%
% The format of the FormatLocaleFile method is:
%
% ssize_t FormatLocaleFile(FILE *file,const char *format,...)
%
% A description of each parameter follows.
%
% o file: the file.
%
% o format: A file describing the format to use to write the remaining
% arguments.
%
*/
MagickPrivate ssize_t FormatLocaleFileList(FILE *file,
const char *magick_restrict format,va_list operands)
{
ssize_t
n;
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VFPRINTF_L)
{
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vfprintf(file,format,operands);
else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
n=(ssize_t) vfprintf_l(file,format,locale,operands);
#else
n=(ssize_t) vfprintf_l(file,locale,format,operands);
#endif
}
#else
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE)
{
locale_t
locale,
previous_locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vfprintf(file,format,operands);
else
{
previous_locale=uselocale(locale);
n=(ssize_t) vfprintf(file,format,operands);
uselocale(previous_locale);
}
}
#else
n=(ssize_t) vfprintf(file,format,operands);
#endif
#endif
return(n);
}
MagickExport ssize_t FormatLocaleFile(FILE *file,
const char *magick_restrict format,...)
{
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleFileList(file,format,operands);
va_end(operands);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F o r m a t L o c a l e S t r i n g %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FormatLocaleString() prints formatted output of a variable argument list to
% a string buffer in the "C" locale.
%
% The format of the FormatLocaleString method is:
%
% ssize_t FormatLocaleString(char *string,const size_t length,
% const char *format,...)
%
% A description of each parameter follows.
%
% o string: FormatLocaleString() returns the formatted string in this
% character buffer.
%
% o length: the maximum length of the string.
%
% o format: A string describing the format to use to write the remaining
% arguments.
%
*/
MagickPrivate ssize_t FormatLocaleStringList(char *magick_restrict string,
const size_t length,const char *magick_restrict format,va_list operands)
{
ssize_t
n;
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_VSNPRINTF_L)
{
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vsnprintf(string,length,format,operands);
else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
n=(ssize_t) vsnprintf_l(string,length,format,locale,operands);
#else
n=(ssize_t) vsnprintf_l(string,length,locale,format,operands);
#endif
}
#elif defined(MAGICKCORE_HAVE_VSNPRINTF)
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_USELOCALE)
{
locale_t
locale,
previous_locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
n=(ssize_t) vsnprintf(string,length,format,operands);
else
{
previous_locale=uselocale(locale);
n=(ssize_t) vsnprintf(string,length,format,operands);
uselocale(previous_locale);
}
}
#else
n=(ssize_t) vsnprintf(string,length,format,operands);
#endif
#else
n=(ssize_t) vsprintf(string,format,operands);
#endif
if (n < 0)
string[length-1]='\0';
return(n);
}
MagickExport ssize_t FormatLocaleString(char *magick_restrict string,
const size_t length,const char *magick_restrict format,...)
{
ssize_t
n;
va_list
operands;
va_start(operands,format);
n=FormatLocaleStringList(string,length,format,operands);
va_end(operands);
return(n);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t L o c a l e I n f o _ %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleInfo_() searches the locale list for the specified tag and if
% found returns attributes for that element.
%
% The format of the GetLocaleInfo method is:
%
% const LocaleInfo *GetLocaleInfo_(const char *tag,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o tag: the locale tag.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport const LocaleInfo *GetLocaleInfo_(const char *tag,
ExceptionInfo *exception)
{
const LocaleInfo
*locale_info;
assert(exception != (ExceptionInfo *) NULL);
if (IsLocaleTreeInstantiated(exception) == MagickFalse)
return((const LocaleInfo *) NULL);
LockSemaphoreInfo(locale_semaphore);
if ((tag == (const char *) NULL) || (LocaleCompare(tag,"*") == 0))
{
ResetSplayTreeIterator(locale_cache);
locale_info=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
UnlockSemaphoreInfo(locale_semaphore);
return(locale_info);
}
locale_info=(const LocaleInfo *) GetValueFromSplayTree(locale_cache,tag);
UnlockSemaphoreInfo(locale_semaphore);
return(locale_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e I n f o L i s t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleInfoList() returns any locale messages that match the
% specified pattern.
%
% The format of the GetLocaleInfoList function is:
%
% const LocaleInfo **GetLocaleInfoList(const char *pattern,
% size_t *number_messages,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o pattern: Specifies a pointer to a text string containing a pattern.
%
% o number_messages: This integer returns the number of locale messages in
% the list.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int LocaleInfoCompare(const void *x,const void *y)
{
const LocaleInfo
**p,
**q;
p=(const LocaleInfo **) x,
q=(const LocaleInfo **) y;
if (LocaleCompare((*p)->path,(*q)->path) == 0)
return(LocaleCompare((*p)->tag,(*q)->tag));
return(LocaleCompare((*p)->path,(*q)->path));
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport const LocaleInfo **GetLocaleInfoList(const char *pattern,
size_t *number_messages,ExceptionInfo *exception)
{
const LocaleInfo
**messages;
register const LocaleInfo
*p;
register ssize_t
i;
/*
Allocate locale list.
*/
assert(pattern != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
assert(number_messages != (size_t *) NULL);
*number_messages=0;
p=GetLocaleInfo_("*",exception);
if (p == (const LocaleInfo *) NULL)
return((const LocaleInfo **) NULL);
messages=(const LocaleInfo **) AcquireQuantumMemory((size_t)
GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages));
if (messages == (const LocaleInfo **) NULL)
return((const LocaleInfo **) NULL);
/*
Generate locale list.
*/
LockSemaphoreInfo(locale_semaphore);
ResetSplayTreeIterator(locale_cache);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
for (i=0; p != (const LocaleInfo *) NULL; )
{
if ((p->stealth == MagickFalse) &&
(GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse))
messages[i++]=p;
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
}
UnlockSemaphoreInfo(locale_semaphore);
qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleInfoCompare);
messages[i]=(LocaleInfo *) NULL;
*number_messages=(size_t) i;
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e L i s t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleList() returns any locale messages that match the specified
% pattern.
%
% The format of the GetLocaleList function is:
%
% char **GetLocaleList(const char *pattern,size_t *number_messages,
% Exceptioninfo *exception)
%
% A description of each parameter follows:
%
% o pattern: Specifies a pointer to a text string containing a pattern.
%
% o number_messages: This integer returns the number of messages in the
% list.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int LocaleTagCompare(const void *x,const void *y)
{
register char
**p,
**q;
p=(char **) x;
q=(char **) y;
return(LocaleCompare(*p,*q));
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickExport char **GetLocaleList(const char *pattern,size_t *number_messages,
ExceptionInfo *exception)
{
char
**messages;
register const LocaleInfo
*p;
register ssize_t
i;
/*
Allocate locale list.
*/
assert(pattern != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
assert(number_messages != (size_t *) NULL);
*number_messages=0;
p=GetLocaleInfo_("*",exception);
if (p == (const LocaleInfo *) NULL)
return((char **) NULL);
messages=(char **) AcquireQuantumMemory((size_t)
GetNumberOfNodesInSplayTree(locale_cache)+1UL,sizeof(*messages));
if (messages == (char **) NULL)
return((char **) NULL);
LockSemaphoreInfo(locale_semaphore);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
for (i=0; p != (const LocaleInfo *) NULL; )
{
if ((p->stealth == MagickFalse) &&
(GlobExpression(p->tag,pattern,MagickTrue) != MagickFalse))
messages[i++]=ConstantString(p->tag);
p=(const LocaleInfo *) GetNextValueInSplayTree(locale_cache);
}
UnlockSemaphoreInfo(locale_semaphore);
qsort((void *) messages,(size_t) i,sizeof(*messages),LocaleTagCompare);
messages[i]=(char *) NULL;
*number_messages=(size_t) i;
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e M e s s a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleMessage() returns a message in the current locale that matches the
% supplied tag.
%
% The format of the GetLocaleMessage method is:
%
% const char *GetLocaleMessage(const char *tag)
%
% A description of each parameter follows:
%
% o tag: Return a message that matches this tag in the current locale.
%
*/
MagickExport const char *GetLocaleMessage(const char *tag)
{
char
name[MagickLocaleExtent];
const LocaleInfo
*locale_info;
ExceptionInfo
*exception;
if ((tag == (const char *) NULL) || (*tag == '\0'))
return(tag);
exception=AcquireExceptionInfo();
(void) FormatLocaleString(name,MagickLocaleExtent,"%s/",tag);
locale_info=GetLocaleInfo_(name,exception);
exception=DestroyExceptionInfo(exception);
if (locale_info != (const LocaleInfo *) NULL)
return(locale_info->message);
return(tag);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e O p t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleOptions() returns any Magick configuration messages associated
% with the specified filename.
%
% The format of the GetLocaleOptions method is:
%
% LinkedListInfo *GetLocaleOptions(const char *filename,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o filename: the locale file tag.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport LinkedListInfo *GetLocaleOptions(const char *filename,
ExceptionInfo *exception)
{
char
path[MagickPathExtent];
const char
*element;
LinkedListInfo
*messages,
*paths;
StringInfo
*xml;
assert(filename != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
assert(exception != (ExceptionInfo *) NULL);
(void) CopyMagickString(path,filename,MagickPathExtent);
/*
Load XML from configuration files to linked-list.
*/
messages=NewLinkedList(0);
paths=GetConfigurePaths(filename,exception);
if (paths != (LinkedListInfo *) NULL)
{
ResetLinkedListIterator(paths);
element=(const char *) GetNextValueInLinkedList(paths);
while (element != (const char *) NULL)
{
(void) FormatLocaleString(path,MagickPathExtent,"%s%s",element,
filename);
(void) LogMagickEvent(LocaleEvent,GetMagickModule(),
"Searching for locale file: \"%s\"",path);
xml=ConfigureFileToStringInfo(path);
if (xml != (StringInfo *) NULL)
(void) AppendValueToLinkedList(messages,xml);
element=(const char *) GetNextValueInLinkedList(paths);
}
paths=DestroyLinkedList(paths,RelinquishMagickMemory);
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
char
*blob;
blob=(char *) NTResourceToBlob(filename);
if (blob != (char *) NULL)
{
xml=AcquireStringInfo(0);
SetStringInfoLength(xml,strlen(blob)+1);
SetStringInfoDatum(xml,(const unsigned char *) blob);
blob=(char *) RelinquishMagickMemory(blob);
SetStringInfoPath(xml,filename);
(void) AppendValueToLinkedList(messages,xml);
}
}
#endif
ResetLinkedListIterator(messages);
return(messages);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t L o c a l e V a l u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetLocaleValue() returns the message associated with the locale info.
%
% The format of the GetLocaleValue method is:
%
% const char *GetLocaleValue(const LocaleInfo *locale_info)
%
% A description of each parameter follows:
%
% o locale_info: The locale info.
%
*/
MagickExport const char *GetLocaleValue(const LocaleInfo *locale_info)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(locale_info != (LocaleInfo *) NULL);
assert(locale_info->signature == MagickCoreSignature);
return(locale_info->message);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I s L o c a l e T r e e I n s t a n t i a t e d %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsLocaleTreeInstantiated() determines if the locale tree is instantiated.
% If not, it instantiates the tree and returns it.
%
% The format of the IsLocaleInstantiated method is:
%
% MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType IsLocaleTreeInstantiated(ExceptionInfo *exception)
{
if (locale_cache == (SplayTreeInfo *) NULL)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&locale_semaphore);
LockSemaphoreInfo(locale_semaphore);
if (locale_cache == (SplayTreeInfo *) NULL)
{
char
*locale;
register const char
*p;
locale=(char *) NULL;
p=setlocale(LC_CTYPE,(const char *) NULL);
if (p != (const char *) NULL)
locale=ConstantString(p);
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_ALL");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_MESSAGES");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LC_CTYPE");
if (locale == (char *) NULL)
locale=GetEnvironmentValue("LANG");
if (locale == (char *) NULL)
locale=ConstantString("C");
locale_cache=AcquireLocaleSplayTree(LocaleFilename,locale,exception);
locale=DestroyString(locale);
}
UnlockSemaphoreInfo(locale_semaphore);
}
return(locale_cache != (SplayTreeInfo *) NULL ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n t e r p r e t L o c a l e V a l u e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpretLocaleValue() interprets the string as a floating point number in
% the "C" locale and returns its value as a double. If sentinal is not a null
% pointer, the method also sets the value pointed by sentinal to point to the
% first character after the number.
%
% The format of the InterpretLocaleValue method is:
%
% double InterpretLocaleValue(const char *value,char **sentinal)
%
% A description of each parameter follows:
%
% o value: the string value.
%
% o sentinal: if sentinal is not NULL, a pointer to the character after the
% last character used in the conversion is stored in the location
% referenced by sentinal.
%
*/
MagickExport double InterpretLocaleValue(const char *magick_restrict string,
char **magick_restrict sentinal)
{
char
*q;
double
value;
if ((*string == '0') && ((string[1] | 0x20)=='x'))
value=(double) strtoul(string,&q,16);
else
{
#if defined(MAGICKCORE_LOCALE_SUPPORT) && defined(MAGICKCORE_HAVE_STRTOD_L)
locale_t
locale;
locale=AcquireCLocale();
if (locale == (locale_t) NULL)
value=strtod(string,&q);
else
value=strtod_l(string,&q,locale);
#else
value=strtod(string,&q);
#endif
}
if (sentinal != (char **) NULL)
*sentinal=q;
return(value);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t L o c a l e I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListLocaleInfo() lists the locale info to a file.
%
% The format of the ListLocaleInfo method is:
%
% MagickBooleanType ListLocaleInfo(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to a FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListLocaleInfo(FILE *file,
ExceptionInfo *exception)
{
const char
*path;
const LocaleInfo
**locale_info;
register ssize_t
i;
size_t
number_messages;
if (file == (const FILE *) NULL)
file=stdout;
number_messages=0;
locale_info=GetLocaleInfoList("*",&number_messages,exception);
if (locale_info == (const LocaleInfo **) NULL)
return(MagickFalse);
path=(const char *) NULL;
for (i=0; i < (ssize_t) number_messages; i++)
{
if (locale_info[i]->stealth != MagickFalse)
continue;
if ((path == (const char *) NULL) ||
(LocaleCompare(path,locale_info[i]->path) != 0))
{
if (locale_info[i]->path != (char *) NULL)
(void) FormatLocaleFile(file,"\nPath: %s\n\n",locale_info[i]->path);
(void) FormatLocaleFile(file,"Tag/Message\n");
(void) FormatLocaleFile(file,
"-------------------------------------------------"
"------------------------------\n");
}
path=locale_info[i]->path;
(void) FormatLocaleFile(file,"%s\n",locale_info[i]->tag);
if (locale_info[i]->message != (char *) NULL)
(void) FormatLocaleFile(file," %s",locale_info[i]->message);
(void) FormatLocaleFile(file,"\n");
}
(void) fflush(file);
locale_info=(const LocaleInfo **)
RelinquishMagickMemory((void *) locale_info);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o a d L o c a l e C a c h e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LoadLocaleCache() loads the locale configurations which provides a mapping
% between locale attributes and a locale name.
%
% The format of the LoadLocaleCache method is:
%
% MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml,
% const char *filename,const size_t depth,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o xml: The locale list in XML format.
%
% o filename: The locale list filename.
%
% o depth: depth of <include /> statements.
%
% o exception: return any errors or warnings in this structure.
%
*/
static void ChopLocaleComponents(char *path,const size_t components)
{
register char
*p;
ssize_t
count;
if (*path == '\0')
return;
p=path+strlen(path)-1;
if (*p == '/')
*p='\0';
for (count=0; (count < (ssize_t) components) && (p > path); p--)
if (*p == '/')
{
*p='\0';
count++;
}
if (count < (ssize_t) components)
*path='\0';
}
static void LocaleFatalErrorHandler(
const ExceptionType magick_unused(severity),
const char *reason,const char *description)
{
magick_unreferenced(severity);
if (reason == (char *) NULL)
return;
(void) FormatLocaleFile(stderr,"%s: %s",GetClientName(),reason);
if (description != (char *) NULL)
(void) FormatLocaleFile(stderr," (%s)",description);
(void) FormatLocaleFile(stderr,".\n");
(void) fflush(stderr);
exit(1);
}
static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml,
const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception)
{
char
keyword[MagickLocaleExtent],
message[MagickLocaleExtent],
tag[MagickLocaleExtent],
*token;
const char
*q;
FatalErrorHandler
fatal_handler;
LocaleInfo
*locale_info;
MagickStatusType
status;
register char
*p;
size_t
extent;
/*
Read the locale configure file.
*/
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading locale configure file \"%s\" ...",filename);
if (xml == (const char *) NULL)
return(MagickFalse);
status=MagickTrue;
locale_info=(LocaleInfo *) NULL;
*tag='\0';
*message='\0';
*keyword='\0';
fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler);
token=AcquireString(xml);
extent=strlen(token)+MagickPathExtent;
for (q=(char *) xml; *q != '\0'; )
{
/*
Interpret XML.
*/
GetNextToken(q,&q,extent,token);
if (*token == '\0')
break;
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0)
{
/*
Doctype element.
*/
while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0'))
{
GetNextToken(q,&q,extent,token);
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
}
continue;
}
if (LocaleNCompare(keyword,"<!--",4) == 0)
{
/*
Comment element.
*/
while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0'))
{
GetNextToken(q,&q,extent,token);
while (isspace((int) ((unsigned char) *q)) != 0)
q++;
}
continue;
}
if (LocaleCompare(keyword,"<include") == 0)
{
/*
Include element.
*/
while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
if (LocaleCompare(keyword,"locale") == 0)
{
if (LocaleCompare(locale,token) != 0)
break;
continue;
}
if (LocaleCompare(keyword,"file") == 0)
{
if (depth > MagickMaxRecursionDepth)
(void) ThrowMagickException(exception,GetMagickModule(),
ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token);
else
{
char
path[MagickPathExtent],
*file_xml;
*path='\0';
GetPathComponent(filename,HeadPath,path);
if (*path != '\0')
(void) ConcatenateMagickString(path,DirectorySeparator,
MagickPathExtent);
if (*token == *DirectorySeparator)
(void) CopyMagickString(path,token,MagickPathExtent);
else
(void) ConcatenateMagickString(path,token,MagickPathExtent);
file_xml=FileToXML(path,~0UL);
if (file_xml != (char *) NULL)
{
status&=LoadLocaleCache(cache,file_xml,path,locale,
depth+1,exception);
file_xml=DestroyString(file_xml);
}
}
}
}
continue;
}
if (LocaleCompare(keyword,"<locale") == 0)
{
/*
Locale element.
*/
while ((*token != '>') && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
}
continue;
}
if (LocaleCompare(keyword,"</locale>") == 0)
{
ChopLocaleComponents(tag,1);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
if (LocaleCompare(keyword,"<localemap>") == 0)
continue;
if (LocaleCompare(keyword,"</localemap>") == 0)
continue;
if (LocaleCompare(keyword,"<message") == 0)
{
/*
Message element.
*/
while ((*token != '>') && (*q != '\0'))
{
(void) CopyMagickString(keyword,token,MagickLocaleExtent);
GetNextToken(q,&q,extent,token);
if (*token != '=')
continue;
GetNextToken(q,&q,extent,token);
if (LocaleCompare(keyword,"name") == 0)
{
(void) ConcatenateMagickString(tag,token,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
}
}
for (p=(char *) q; (*q != '<') && (*q != '\0'); q++) ;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
q--;
while ((isspace((int) ((unsigned char) *q)) != 0) && (q > p))
q--;
(void) CopyMagickString(message,p,MagickMin((size_t) (q-p+2),
MagickLocaleExtent));
locale_info=(LocaleInfo *) AcquireCriticalMemory(sizeof(*locale_info));
(void) memset(locale_info,0,sizeof(*locale_info));
locale_info->path=ConstantString(filename);
locale_info->tag=ConstantString(tag);
locale_info->message=ConstantString(message);
locale_info->signature=MagickCoreSignature;
status=AddValueToSplayTree(cache,locale_info->tag,locale_info);
if (status == MagickFalse)
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
locale_info->tag);
(void) ConcatenateMagickString(tag,message,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"\n",MagickLocaleExtent);
q++;
continue;
}
if (LocaleCompare(keyword,"</message>") == 0)
{
ChopLocaleComponents(tag,2);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
if (*keyword == '<')
{
/*
Subpath element.
*/
if (*(keyword+1) == '?')
continue;
if (*(keyword+1) == '/')
{
ChopLocaleComponents(tag,1);
if (*tag != '\0')
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
token[strlen(token)-1]='\0';
(void) CopyMagickString(token,token+1,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,token,MagickLocaleExtent);
(void) ConcatenateMagickString(tag,"/",MagickLocaleExtent);
continue;
}
GetNextToken(q,(const char **) NULL,extent,token);
if (*token != '=')
continue;
}
token=(char *) RelinquishMagickMemory(token);
(void) SetFatalErrorHandler(fatal_handler);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e C o m p a r e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleCompare() performs a case-insensitive comparison of two strings
% byte-by-byte, according to the ordering of the current locale encoding.
% LocaleCompare returns an integer greater than, equal to, or less than 0,
% if the string pointed to by p is greater than, equal to, or less than the
% string pointed to by q respectively. The sign of a non-zero return value
% is determined by the sign of the difference between the values of the first
% pair of bytes that differ in the strings being compared.
%
% The format of the LocaleCompare method is:
%
% int LocaleCompare(const char *p,const char *q)
%
% A description of each parameter follows:
%
% o p: A pointer to a character string.
%
% o q: A pointer to a character string to compare to p.
%
*/
MagickExport int LocaleCompare(const char *p,const char *q)
{
if (p == (char *) NULL)
{
if (q == (char *) NULL)
return(0);
return(-1);
}
if (q == (char *) NULL)
return(1);
#if defined(MAGICKCORE_HAVE_STRCASECMP)
return(strcasecmp(p,q));
#else
{
register int
c,
d;
for ( ; ; )
{
c=(int) *((unsigned char *) p);
d=(int) *((unsigned char *) q);
if ((c == 0) || (AsciiMap[c] != AsciiMap[d]))
break;
p++;
q++;
}
return(AsciiMap[c]-(int) AsciiMap[d]);
}
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e L o w e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleLower() transforms all of the characters in the supplied
% null-terminated string, changing all uppercase letters to lowercase.
%
% The format of the LocaleLower method is:
%
% void LocaleLower(char *string)
%
% A description of each parameter follows:
%
% o string: A pointer to the string to convert to lower-case Locale.
%
*/
MagickExport void LocaleLower(char *string)
{
register char
*q;
assert(string != (char *) NULL);
for (q=string; *q != '\0'; q++)
*q=(char) LocaleLowercase((int) *q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e L o w e r c a s e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleLowercase() convert to lowercase.
%
% The format of the LocaleLowercase method is:
%
% void LocaleLowercase(const int c)
%
% A description of each parameter follows:
%
% o If c is a uppercase letter, return its lowercase equivalent.
%
*/
MagickExport int LocaleLowercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(tolower_l((int) ((unsigned char) c),c_locale));
#endif
return(tolower((int) ((unsigned char) c)));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e N C o m p a r e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleNCompare() performs a case-insensitive comparison of two strings
% byte-by-byte, according to the ordering of the current locale encoding.
%
% LocaleNCompare returns an integer greater than, equal to, or less than 0,
% if the string pointed to by p is greater than, equal to, or less than the
% string pointed to by q respectively. The sign of a non-zero return value
% is determined by the sign of the difference between the values of the first
% pair of bytes that differ in the strings being compared.
%
% The LocaleNCompare method makes the same comparison as LocaleCompare but
% looks at a maximum of n bytes. Bytes following a null byte are not
% compared.
%
% The format of the LocaleNCompare method is:
%
% int LocaleNCompare(const char *p,const char *q,const size_t n)
%
% A description of each parameter follows:
%
% o p: A pointer to a character string.
%
% o q: A pointer to a character string to compare to p.
%
% o length: the number of characters to compare in strings p and q.
%
*/
MagickExport int LocaleNCompare(const char *p,const char *q,const size_t length)
{
if (p == (char *) NULL)
{
if (q == (char *) NULL)
return(0);
return(-1);
}
if (q == (char *) NULL)
return(1);
#if defined(MAGICKCORE_HAVE_STRNCASECMP)
return(strncasecmp(p,q,length));
#else
{
register int
c,
d;
register size_t
i;
for (i=length; i != 0; i--)
{
c=(int) *((unsigned char *) p);
d=(int) *((unsigned char *) q);
if (AsciiMap[c] != AsciiMap[d])
return(AsciiMap[c]-(int) AsciiMap[d]);
if (c == 0)
return(0);
p++;
q++;
}
return(0);
}
#endif
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e U p p e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleUpper() transforms all of the characters in the supplied
% null-terminated string, changing all lowercase letters to uppercase.
%
% The format of the LocaleUpper method is:
%
% void LocaleUpper(char *string)
%
% A description of each parameter follows:
%
% o string: A pointer to the string to convert to upper-case Locale.
%
*/
MagickExport void LocaleUpper(char *string)
{
register char
*q;
assert(string != (char *) NULL);
for (q=string; *q != '\0'; q++)
*q=(char) LocaleUppercase((int) *q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L o c a l e U p p e r c a s e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleUppercase() convert to uppercase.
%
% The format of the LocaleUppercase method is:
%
% void LocaleUppercase(const int c)
%
% A description of each parameter follows:
%
% o If c is a lowercase letter, return its uppercase equivalent.
%
*/
MagickExport int LocaleUppercase(const int c)
{
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o c a l e C o m p o n e n t G e n e s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleComponentGenesis() instantiates the locale component.
%
% The format of the LocaleComponentGenesis method is:
%
% MagickBooleanType LocaleComponentGenesis(void)
%
*/
MagickPrivate MagickBooleanType LocaleComponentGenesis(void)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
locale_semaphore=AcquireSemaphoreInfo();
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L o c a l e C o m p o n e n t T e r m i n u s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LocaleComponentTerminus() destroys the locale component.
%
% The format of the LocaleComponentTerminus method is:
%
% LocaleComponentTerminus(void)
%
*/
MagickPrivate void LocaleComponentTerminus(void)
{
if (locale_semaphore == (SemaphoreInfo *) NULL)
ActivateSemaphoreInfo(&locale_semaphore);
LockSemaphoreInfo(locale_semaphore);
if (locale_cache != (SplayTreeInfo *) NULL)
locale_cache=DestroySplayTree(locale_cache);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
DestroyCLocale();
#endif
UnlockSemaphoreInfo(locale_semaphore);
RelinquishSemaphoreInfo(&locale_semaphore);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_766_0 |
crossvul-cpp_data_bad_4493_1 | /*************************************************************************
*
* $Id: triostr.c,v 1.36 2010/01/26 13:02:02 breese Exp $
*
* Copyright (C) 2001 Bjorn Reese and Daniel Stenberg.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
* CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
*
************************************************************************/
/*************************************************************************
* Include files
*/
#if defined(HAVE_CONFIG_H)
#include <config.h>
#endif
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "triodef.h"
#include "triostr.h"
#if defined(TRIO_FUNC_TO_LONG_DOUBLE)
#define USE_MATH
#endif
#if defined(USE_MATH)
#include <math.h>
#endif
/*************************************************************************
* Definitions
*/
#if !defined(TRIO_PUBLIC_STRING)
#define TRIO_PUBLIC_STRING TRIO_PUBLIC
#endif
#if !defined(TRIO_PRIVATE_STRING)
#define TRIO_PRIVATE_STRING TRIO_PRIVATE
#endif
#if !defined(NULL)
#define NULL 0
#endif
#if !defined(NIL)
#define NIL ((char)0)
#endif
#if !defined(FALSE)
#define FALSE (1 == 0)
#define TRUE (!FALSE)
#endif
#if !defined(BOOLEAN_T)
#define BOOLEAN_T int
#endif
#if defined(USE_MATH)
#if defined(PREDEF_STANDARD_C99)
#if defined(TRIO_COMPILER_DECC)
#if (TRIO_COMPILER_DECC - 0 > 80000000)
/*
* The OSF/1 runtime that comes with the DECC compiler does not support
* hexfloats conversion.
*/
#define USE_STRTOD
#define USE_STRTOF
#endif
#else
#define USE_STRTOD
#define USE_STRTOF
#endif
#else
#if defined(TRIO_COMPILER_VISUALC)
#define USE_STRTOD
#endif
#endif
#endif
#if defined(TRIO_PLATFORM_UNIX)
#if defined(PREDEF_STANDARD_UNIX95)
#define USE_STRCASECMP
#define USE_STRNCASECMP
#endif
#if defined(TRIO_PLATFORM_SUNOS)
#define USE_SYS_ERRLIST
#else
#define USE_STRERROR
#endif
#if defined(TRIO_PLATFORM_QNX)
#define strcasecmp(x, y) stricmp(x, y)
#define strncasecmp(x, y, n) strnicmp(x, y, n)
#endif
#endif
#if defined(TRIO_PLATFORM_WIN32)
#define USE_STRCASECMP
#if defined(TRIO_PLATFORM_WINCE)
#define strcasecmp(x, y) _stricmp(x, y)
#else
#define strcasecmp(x, y) _stricmp(x, y)
#endif
#endif
#if !defined(HAVE_CONFIG_H)
#if !(defined(TRIO_PLATFORM_SUNOS))
#define HAVE_TOLOWER
#define HAVE_TOUPPER
#endif
#endif
#if defined(USE_MATH) && !defined(TRIO_NO_POWL)
#if !defined(HAVE_POWL)
#if defined(PREDEF_STANDARD_C99) || defined(PREDEF_STANDARD_UNIX03)
#define HAVE_POWL
#else
#if defined(TRIO_COMPILER_VISUALC)
#if defined(powl)
#define HAVE_POWL
#endif
#endif
#endif
#endif
#endif
#if defined(HAVE_POWL)
#define trio_powl(x, y) powl((x), (y))
#else
#define trio_powl(x, y) pow((double)(x), (double)(y))
#endif
#if defined(TRIO_FUNC_TO_UPPER) || (defined(TRIO_FUNC_EQUAL) && !defined(USE_STRCASECMP)) || \
(defined(TRIO_FUNC_EQUAL_MAX) && !defined(USE_STRNCASECMP)) || defined(TRIO_FUNC_MATCH) || \
defined(TRIO_FUNC_TO_LONG_DOUBLE) || defined(TRIO_FUNC_UPPER)
#define TRIO_FUNC_INTERNAL_TO_UPPER
#endif
/*************************************************************************
* Structures
*/
struct _trio_string_t
{
char* content;
size_t length;
size_t allocated;
};
/*************************************************************************
* Constants
*/
#if !defined(TRIO_EMBED_STRING)
/* Unused but kept for reference */
/* static TRIO_CONST char rcsid[] = "@(#)$Id: triostr.c,v 1.36 2010/01/26 13:02:02 breese Exp $"; */
#endif
/*************************************************************************
* Static String Functions
*/
#if defined(TRIO_DOCUMENTATION)
#include "doc/doc_static.h"
#endif
/** @addtogroup StaticStrings
@{
*/
/*
* internal_duplicate_max
*/
#if defined(TRIO_FUNC_DUPLICATE) || defined(TRIO_FUNC_DUPLICATE_MAX) || \
defined(TRIO_FUNC_STRING_DUPLICATE) || defined(TRIO_FUNC_XSTRING_DUPLICATE)
TRIO_PRIVATE_STRING char* internal_duplicate_max TRIO_ARGS2((source, size), TRIO_CONST char* source,
size_t size)
{
char* target;
assert(source);
/* Make room for string plus a terminating zero */
size++;
target = trio_create(size);
if (target)
{
trio_copy_max(target, size, source);
}
return target;
}
#endif
/*
* internal_string_alloc
*/
#if defined(TRIO_FUNC_STRING_CREATE) || defined(TRIO_FUNC_STRING_DUPLICATE) || \
defined(TRIO_FUNC_XSTRING_DUPLICATE)
TRIO_PRIVATE_STRING trio_string_t* internal_string_alloc(TRIO_NOARGS)
{
trio_string_t* self;
self = (trio_string_t*)TRIO_MALLOC(sizeof(trio_string_t));
if (self)
{
self->content = NULL;
self->length = 0;
self->allocated = 0;
}
return self;
}
#endif
/*
* internal_string_grow
*
* The size of the string will be increased by 'delta' characters. If
* 'delta' is zero, the size will be doubled.
*/
#if defined(TRIO_FUNC_STRING_CREATE) || defined(TRIO_FUNC_STRING_APPEND) || \
defined(TRIO_FUNC_XSTRING_APPEND) || defined(TRIO_FUNC_XSTRING_APPEND_CHAR)
TRIO_PRIVATE_STRING BOOLEAN_T internal_string_grow TRIO_ARGS2((self, delta), trio_string_t* self,
size_t delta)
{
BOOLEAN_T status = FALSE;
char* new_content;
size_t new_size;
new_size =
(delta == 0) ? ((self->allocated == 0) ? 1 : self->allocated * 2) : self->allocated + delta;
new_content = (char*)TRIO_REALLOC(self->content, new_size);
if (new_content)
{
self->content = new_content;
self->allocated = new_size;
status = TRUE;
}
return status;
}
#endif
/*
* internal_string_grow_to
*
* The size of the string will be increased to 'length' plus one characters.
* If 'length' is less than the original size, the original size will be
* used (that is, the size of the string is never decreased).
*/
#if defined(TRIO_FUNC_STRING_APPEND) || defined(TRIO_FUNC_XSTRING_APPEND) || \
defined(TRIO_FUNC_XSTRING_APPEND_MAX)
TRIO_PRIVATE_STRING BOOLEAN_T internal_string_grow_to TRIO_ARGS2((self, length),
trio_string_t* self, size_t length)
{
length++; /* Room for terminating zero */
return (self->allocated < length) ? internal_string_grow(self, length - self->allocated) : TRUE;
}
#endif
#if defined(TRIO_FUNC_INTERNAL_TO_UPPER)
TRIO_PRIVATE_STRING TRIO_INLINE int internal_to_upper TRIO_ARGS1((source), int source)
{
#if defined(HAVE_TOUPPER)
return toupper(source);
#else
/* Does not handle locales or non-contiguous alphabetic characters */
return ((source >= (int)'a') && (source <= (int)'z')) ? source - 'a' + 'A' : source;
#endif
}
#endif
/**
Create new string.
@param size Size of new string.
@return Pointer to string, or NULL if allocation failed.
*/
#if defined(TRIO_FUNC_CREATE)
TRIO_PUBLIC_STRING char* trio_create TRIO_ARGS1((size), size_t size)
{
return (char*)TRIO_MALLOC(size);
}
#endif
/**
Destroy string.
@param string String to be freed.
*/
#if defined(TRIO_FUNC_DESTROY)
TRIO_PUBLIC_STRING void trio_destroy TRIO_ARGS1((string), char* string)
{
if (string)
{
TRIO_FREE(string);
}
}
#endif
/**
Count the number of characters in a string.
@param string String to measure.
@return Number of characters in @p string.
*/
#if defined(TRIO_FUNC_LENGTH)
TRIO_PUBLIC_STRING size_t trio_length TRIO_ARGS1((string), TRIO_CONST char* string)
{
return strlen(string);
}
#endif
/**
Count at most @p max characters in a string.
@param string String to measure.
@param max Maximum number of characters to count.
@return The maximum value of @p max and number of characters in @p string.
*/
#if defined(TRIO_FUNC_LENGTH_MAX)
TRIO_PUBLIC_STRING size_t trio_length_max TRIO_ARGS2((string, max), TRIO_CONST char* string,
size_t max)
{
size_t i;
for (i = 0; i < max; ++i)
{
if (string[i] == 0)
break;
}
return i;
}
#endif
/**
Append @p source at the end of @p target.
@param target Target string.
@param source Source string.
@return Boolean value indicating success or failure.
@pre @p target must point to a memory chunk with sufficient room to
contain the @p target string and @p source string.
@pre No boundary checking is performed, so insufficient memory will
result in a buffer overrun.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_APPEND)
TRIO_PUBLIC_STRING int trio_append TRIO_ARGS2((target, source), char* target,
TRIO_CONST char* source)
{
assert(target);
assert(source);
return (strcat(target, source) != NULL);
}
#endif
/**
Append at most @p max characters from @p source to @p target.
@param target Target string.
@param max Maximum number of characters to append.
@param source Source string.
@return Boolean value indicating success or failure.
@pre @p target must point to a memory chuck with sufficient room to
contain the @p target string and the @p source string (at most @p max
characters).
@pre No boundary checking is performed, so insufficient memory will
result in a buffer overrun.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_APPEND_MAX)
TRIO_PUBLIC_STRING int trio_append_max TRIO_ARGS3((target, max, source), char* target, size_t max,
TRIO_CONST char* source)
{
size_t length;
assert(target);
assert(source);
length = trio_length(target);
if (max > length)
{
strncat(target, source, max - length - 1);
}
return TRUE;
}
#endif
/**
Determine if a string contains a substring.
@param string String to be searched.
@param substring String to be found.
@return Boolean value indicating success or failure.
*/
#if defined(TRIO_FUNC_CONTAINS)
TRIO_PUBLIC_STRING int trio_contains TRIO_ARGS2((string, substring), TRIO_CONST char* string,
TRIO_CONST char* substring)
{
assert(string);
assert(substring);
return (0 != strstr(string, substring));
}
#endif
/**
Copy @p source to @p target.
@param target Target string.
@param source Source string.
@return Boolean value indicating success or failure.
@pre @p target must point to a memory chunk with sufficient room to
contain the @p source string.
@pre No boundary checking is performed, so insufficient memory will
result in a buffer overrun.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_COPY)
TRIO_PUBLIC_STRING int trio_copy TRIO_ARGS2((target, source), char* target, TRIO_CONST char* source)
{
assert(target);
assert(source);
(void)strcpy(target, source);
return TRUE;
}
#endif
/**
Copy at most @p max - 1 characters from @p source to @p target.
@param target Target string.
@param max Maximum number of characters to append (one of which is
a NUL terminator). In other words @p source must point to at least
@p max - 1 bytes, but @p target must point to at least @p max
bytes.
@param source Source string.
@return Boolean value indicating success or failure.
@pre @p target must point to a memory chunk with sufficient room to
contain the @p source string and a NUL terminator (at most @p max
bytes total).
@pre No boundary checking is performed, so insufficient memory will
result in a buffer overrun.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_COPY_MAX)
TRIO_PUBLIC_STRING int trio_copy_max TRIO_ARGS3((target, max, source), char* target, size_t max,
TRIO_CONST char* source)
{
assert(target);
assert(source);
assert(max > 0); /* Includes != 0 */
(void)strncpy(target, source, max - 1);
target[max - 1] = (char)0;
return TRUE;
}
#endif
/**
Duplicate @p source.
@param source Source string.
@return A copy of the @p source string.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_DUPLICATE)
TRIO_PUBLIC_STRING char* trio_duplicate TRIO_ARGS1((source), TRIO_CONST char* source)
{
return internal_duplicate_max(source, trio_length(source));
}
#endif
/**
Duplicate at most @p max characters of @p source.
@param source Source string.
@param max Maximum number of characters to duplicate.
@return A copy of the @p source string.
@post @p target will be zero terminated.
*/
#if defined(TRIO_FUNC_DUPLICATE_MAX)
TRIO_PUBLIC_STRING char* trio_duplicate_max TRIO_ARGS2((source, max), TRIO_CONST char* source,
size_t max)
{
size_t length;
assert(source);
assert(max > 0);
length = trio_length(source);
if (length > max)
{
length = max;
}
return internal_duplicate_max(source, length);
}
#endif
/**
Compare if two strings are equal.
@param first First string.
@param second Second string.
@return Boolean indicating whether the two strings are equal or not.
Case-insensitive comparison.
*/
#if defined(TRIO_FUNC_EQUAL)
TRIO_PUBLIC_STRING int trio_equal TRIO_ARGS2((first, second), TRIO_CONST char* first,
TRIO_CONST char* second)
{
assert(first);
assert(second);
if ((first != NULL) && (second != NULL))
{
#if defined(USE_STRCASECMP)
return (0 == strcasecmp(first, second));
#else
while ((*first != NIL) && (*second != NIL))
{
if (internal_to_upper(*first) != internal_to_upper(*second))
{
break;
}
first++;
second++;
}
return ((*first == NIL) && (*second == NIL));
#endif
}
return FALSE;
}
#endif
/**
Compare if two strings are equal.
@param first First string.
@param second Second string.
@return Boolean indicating whether the two strings are equal or not.
Case-sensitive comparison.
*/
#if defined(TRIO_FUNC_EQUAL_CASE)
TRIO_PUBLIC_STRING int trio_equal_case TRIO_ARGS2((first, second), TRIO_CONST char* first,
TRIO_CONST char* second)
{
assert(first);
assert(second);
if ((first != NULL) && (second != NULL))
{
return (0 == strcmp(first, second));
}
return FALSE;
}
#endif
/**
Compare if two strings up until the first @p max characters are equal.
@param first First string.
@param max Maximum number of characters to compare.
@param second Second string.
@return Boolean indicating whether the two strings are equal or not.
Case-sensitive comparison.
*/
#if defined(TRIO_FUNC_EQUAL_CASE_MAX)
TRIO_PUBLIC_STRING int trio_equal_case_max TRIO_ARGS3((first, max, second), TRIO_CONST char* first,
size_t max, TRIO_CONST char* second)
{
assert(first);
assert(second);
if ((first != NULL) && (second != NULL))
{
return (0 == strncmp(first, second, max));
}
return FALSE;
}
#endif
/**
Compare if two strings are equal.
@param first First string.
@param second Second string.
@return Boolean indicating whether the two strings are equal or not.
Collating characters are considered equal.
*/
#if defined(TRIO_FUNC_EQUAL_LOCALE)
TRIO_PUBLIC_STRING int trio_equal_locale TRIO_ARGS2((first, second), TRIO_CONST char* first,
TRIO_CONST char* second)
{
assert(first);
assert(second);
#if defined(LC_COLLATE)
return (strcoll(first, second) == 0);
#else
return trio_equal(first, second);
#endif
}
#endif
/**
Compare if two strings up until the first @p max characters are equal.
@param first First string.
@param max Maximum number of characters to compare.
@param second Second string.
@return Boolean indicating whether the two strings are equal or not.
Case-insensitive comparison.
*/
#if defined(TRIO_FUNC_EQUAL_MAX)
TRIO_PUBLIC_STRING int trio_equal_max TRIO_ARGS3((first, max, second), TRIO_CONST char* first,
size_t max, TRIO_CONST char* second)
{
assert(first);
assert(second);
if ((first != NULL) && (second != NULL))
{
#if defined(USE_STRNCASECMP)
return (0 == strncasecmp(first, second, max));
#else
/* Not adequately tested yet */
size_t cnt = 0;
while ((*first != NIL) && (*second != NIL) && (cnt <= max))
{
if (internal_to_upper(*first) != internal_to_upper(*second))
{
break;
}
first++;
second++;
cnt++;
}
return ((cnt == max) || ((*first == NIL) && (*second == NIL)));
#endif
}
return FALSE;
}
#endif
/**
Provide a textual description of an error code (errno).
@param error_number Error number.
@return Textual description of @p error_number.
*/
#if defined(TRIO_FUNC_ERROR)
TRIO_PUBLIC_STRING TRIO_CONST char* trio_error TRIO_ARGS1((error_number), int error_number)
{
#if defined(USE_STRERROR)
return strerror(error_number);
#else
#if defined(USE_SYS_ERRLIST)
extern char* sys_errlist[];
extern int sys_nerr;
return ((error_number < 0) || (error_number >= sys_nerr)) ? "unknown"
: sys_errlist[error_number];
#else
return "unknown";
#endif
#endif
}
#endif
/**
Format the date/time according to @p format.
@param target Target string.
@param max Maximum number of characters to format.
@param format Formatting string.
@param datetime Date/time structure.
@return Number of formatted characters.
The formatting string accepts the same specifiers as the standard C
function strftime.
*/
#if defined(TRIO_FUNC_FORMAT_DATE_MAX)
TRIO_PUBLIC_STRING size_t trio_format_date_max TRIO_ARGS4((target, max, format, datetime),
char* target, size_t max,
TRIO_CONST char* format,
TRIO_CONST struct tm* datetime)
{
assert(target);
assert(format);
assert(datetime);
assert(max > 0);
return strftime(target, max, format, datetime);
}
#endif
/**
Calculate a hash value for a string.
@param string String to be calculated on.
@param type Hash function.
@return Calculated hash value.
@p type can be one of the following
@li @c TRIO_HASH_PLAIN Plain hash function.
*/
#if defined(TRIO_FUNC_HASH)
TRIO_PUBLIC_STRING unsigned long trio_hash TRIO_ARGS2((string, type), TRIO_CONST char* string,
int type)
{
unsigned long value = 0L;
char ch;
assert(string);
switch (type)
{
case TRIO_HASH_PLAIN:
while ((ch = *string++) != NIL)
{
value *= 31;
value += (unsigned long)ch;
}
break;
default:
assert(FALSE);
break;
}
return value;
}
#endif
/**
Find first occurrence of a character in a string.
@param string String to be searched.
@param character Character to be found.
@return A pointer to the found character, or NULL if character was not found.
*/
#if defined(TRIO_FUNC_INDEX)
TRIO_PUBLIC_STRING char* trio_index TRIO_ARGS2((string, character), TRIO_CONST char* string,
int character)
{
assert(string);
return strchr(string, character);
}
#endif
/**
Find last occurrence of a character in a string.
@param string String to be searched.
@param character Character to be found.
@return A pointer to the found character, or NULL if character was not found.
*/
#if defined(TRIO_FUNC_INDEX_LAST)
TRIO_PUBLIC_STRING char* trio_index_last TRIO_ARGS2((string, character), TRIO_CONST char* string,
int character)
{
assert(string);
return strchr(string, character);
}
#endif
/**
Convert the alphabetic letters in the string to lower-case.
@param target String to be converted.
@return Number of processed characters (converted or not).
*/
#if defined(TRIO_FUNC_LOWER)
TRIO_PUBLIC_STRING int trio_lower TRIO_ARGS1((target), char* target)
{
assert(target);
return trio_span_function(target, target, trio_to_lower);
}
#endif
/**
Compare two strings using wildcards.
@param string String to be searched.
@param pattern Pattern, including wildcards, to search for.
@return Boolean value indicating success or failure.
Case-insensitive comparison.
The following wildcards can be used
@li @c * Match any number of characters.
@li @c ? Match a single character.
*/
#if defined(TRIO_FUNC_MATCH)
TRIO_PUBLIC_STRING int trio_match TRIO_ARGS2((string, pattern), TRIO_CONST char* string,
TRIO_CONST char* pattern)
{
assert(string);
assert(pattern);
for (; ('*' != *pattern); ++pattern, ++string)
{
if (NIL == *string)
{
return (NIL == *pattern);
}
if ((internal_to_upper((int)*string) != internal_to_upper((int)*pattern)) &&
('?' != *pattern))
{
return FALSE;
}
}
/* two-line patch to prevent *too* much recursiveness: */
while ('*' == pattern[1])
pattern++;
do
{
if (trio_match(string, &pattern[1]))
{
return TRUE;
}
} while (*string++);
return FALSE;
}
#endif
/**
Compare two strings using wildcards.
@param string String to be searched.
@param pattern Pattern, including wildcards, to search for.
@return Boolean value indicating success or failure.
Case-sensitive comparison.
The following wildcards can be used
@li @c * Match any number of characters.
@li @c ? Match a single character.
*/
#if defined(TRIO_FUNC_MATCH_CASE)
TRIO_PUBLIC_STRING int trio_match_case TRIO_ARGS2((string, pattern), TRIO_CONST char* string,
TRIO_CONST char* pattern)
{
assert(string);
assert(pattern);
for (; ('*' != *pattern); ++pattern, ++string)
{
if (NIL == *string)
{
return (NIL == *pattern);
}
if ((*string != *pattern) && ('?' != *pattern))
{
return FALSE;
}
}
/* two-line patch to prevent *too* much recursiveness: */
while ('*' == pattern[1])
pattern++;
do
{
if (trio_match_case(string, &pattern[1]))
{
return TRUE;
}
} while (*string++);
return FALSE;
}
#endif
/**
Execute a function on each character in string.
@param target Target string.
@param source Source string.
@param Function Function to be executed.
@return Number of processed characters.
*/
#if defined(TRIO_FUNC_SPAN_FUNCTION)
TRIO_PUBLIC_STRING size_t trio_span_function TRIO_ARGS3((target, source, Function), char* target,
TRIO_CONST char* source,
int(*Function) TRIO_PROTO((int)))
{
size_t count = 0;
assert(target);
assert(source);
assert(Function);
while (*source != NIL)
{
*target++ = Function(*source++);
count++;
}
return count;
}
#endif
/**
Search for a substring in a string.
@param string String to be searched.
@param substring String to be found.
@return Pointer to first occurrence of @p substring in @p string, or NULL
if no match was found.
*/
#if defined(TRIO_FUNC_SUBSTRING)
TRIO_PUBLIC_STRING char* trio_substring TRIO_ARGS2((string, substring), TRIO_CONST char* string,
TRIO_CONST char* substring)
{
assert(string);
assert(substring);
return strstr(string, substring);
}
#endif
/**
Search for a substring in the first @p max characters of a string.
@param string String to be searched.
@param max Maximum characters to be searched.
@param substring String to be found.
@return Pointer to first occurrence of @p substring in @p string, or NULL
if no match was found.
*/
#if defined(TRIO_FUNC_SUBSTRING_MAX)
TRIO_PUBLIC_STRING char* trio_substring_max TRIO_ARGS3((string, max, substring),
TRIO_CONST char* string, size_t max,
TRIO_CONST char* substring)
{
size_t count;
size_t size;
char* result = NULL;
assert(string);
assert(substring);
size = trio_length(substring);
if (size <= max)
{
for (count = 0; count <= max - size; count++)
{
if (trio_equal_max(substring, size, &string[count]))
{
result = (char*)&string[count];
break;
}
}
}
return result;
}
#endif
/**
Tokenize string.
@param string String to be tokenized.
@param delimiters String containing list of delimiting characters.
@return Start of new token.
@warning @p string will be destroyed.
*/
#if defined(TRIO_FUNC_TOKENIZE)
TRIO_PUBLIC_STRING char* trio_tokenize TRIO_ARGS2((string, delimiters), char* string,
TRIO_CONST char* delimiters)
{
assert(delimiters);
return strtok(string, delimiters);
}
#endif
/**
Convert string to floating-point number.
@param source String to be converted.
@param endp Pointer to end of the converted string.
@return A floating-point number.
The following Extended Backus-Naur form is used
@verbatim
double ::= [ <sign> ]
( <number> |
<number> <decimal_point> <number> |
<decimal_point> <number> )
[ <exponential> [ <sign> ] <number> ]
number ::= 1*( <digit> )
digit ::= ( '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' )
exponential ::= ( 'e' | 'E' )
sign ::= ( '-' | '+' )
decimal_point ::= '.'
@endverbatim
*/
#if defined(TRIO_FUNC_TO_LONG_DOUBLE)
/* FIXME: Add EBNF for hex-floats */
TRIO_PUBLIC_STRING trio_long_double_t trio_to_long_double TRIO_ARGS2((source, endp),
TRIO_CONST char* source,
char** endp)
{
#if defined(USE_STRTOLD)
return strtold(source, endp);
#else
int isNegative = FALSE;
int isExponentNegative = FALSE;
trio_long_double_t integer = 0.0;
trio_long_double_t fraction = 0.0;
unsigned long exponent = 0;
trio_long_double_t base;
trio_long_double_t fracdiv = 1.0;
trio_long_double_t value = 0.0;
/* First try hex-floats */
if ((source[0] == '0') && ((source[1] == 'x') || (source[1] == 'X')))
{
base = 16.0;
source += 2;
while (isxdigit((int)*source))
{
integer *= base;
integer += (isdigit((int)*source) ? (*source - '0')
: 10 + (internal_to_upper((int)*source) - 'A'));
source++;
}
if (*source == '.')
{
source++;
while (isxdigit((int)*source))
{
fracdiv /= base;
fraction += fracdiv * (isdigit((int)*source)
? (*source - '0')
: 10 + (internal_to_upper((int)*source) - 'A'));
source++;
}
if ((*source == 'p') || (*source == 'P'))
{
source++;
if ((*source == '+') || (*source == '-'))
{
isExponentNegative = (*source == '-');
source++;
}
while (isdigit((int)*source))
{
exponent *= 10;
exponent += (*source - '0');
source++;
}
}
}
/* For later use with exponent */
base = 2.0;
}
else /* Then try normal decimal floats */
{
base = 10.0;
isNegative = (*source == '-');
/* Skip sign */
if ((*source == '+') || (*source == '-'))
source++;
/* Integer part */
while (isdigit((int)*source))
{
integer *= base;
integer += (*source - '0');
source++;
}
if (*source == '.')
{
source++; /* skip decimal point */
while (isdigit((int)*source))
{
fracdiv /= base;
fraction += (*source - '0') * fracdiv;
source++;
}
}
if ((*source == 'e') || (*source == 'E')
#if TRIO_MICROSOFT
|| (*source == 'd') || (*source == 'D')
#endif
)
{
source++; /* Skip exponential indicator */
isExponentNegative = (*source == '-');
if ((*source == '+') || (*source == '-'))
source++;
while (isdigit((int)*source))
{
exponent *= (int)base;
exponent += (*source - '0');
source++;
}
}
}
value = integer + fraction;
if (exponent != 0)
{
if (isExponentNegative)
value /= trio_powl(base, (trio_long_double_t)exponent);
else
value *= trio_powl(base, (trio_long_double_t)exponent);
}
if (isNegative)
value = -value;
if (endp)
*endp = (char*)source;
return value;
#endif
}
#endif
/**
Convert string to floating-point number.
@param source String to be converted.
@param endp Pointer to end of the converted string.
@return A floating-point number.
See @ref trio_to_long_double.
*/
#if defined(TRIO_FUNC_TO_DOUBLE)
TRIO_PUBLIC_STRING double trio_to_double TRIO_ARGS2((source, endp), TRIO_CONST char* source,
char** endp)
{
#if defined(USE_STRTOD)
return strtod(source, endp);
#else
return (double)trio_to_long_double(source, endp);
#endif
}
#endif
/**
Convert string to floating-point number.
@param source String to be converted.
@param endp Pointer to end of the converted string.
@return A floating-point number.
See @ref trio_to_long_double.
*/
#if defined(TRIO_FUNC_TO_FLOAT)
TRIO_PUBLIC_STRING float trio_to_float TRIO_ARGS2((source, endp), TRIO_CONST char* source,
char** endp)
{
#if defined(USE_STRTOF)
return strtof(source, endp);
#else
return (float)trio_to_long_double(source, endp);
#endif
}
#endif
/**
Convert string to signed integer.
@param string String to be converted.
@param endp Pointer to end of converted string.
@param base Radix number of number.
*/
#if defined(TRIO_FUNC_TO_LONG)
TRIO_PUBLIC_STRING long trio_to_long TRIO_ARGS3((string, endp, base), TRIO_CONST char* string,
char** endp, int base)
{
assert(string);
assert((base >= 2) && (base <= 36));
return strtol(string, endp, base);
}
#endif
/**
Convert one alphabetic letter to lower-case.
@param source The letter to be converted.
@return The converted letter.
*/
#if defined(TRIO_FUNC_TO_LOWER)
TRIO_PUBLIC_STRING int trio_to_lower TRIO_ARGS1((source), int source)
{
#if defined(HAVE_TOLOWER)
return tolower(source);
#else
/* Does not handle locales or non-contiguous alphabetic characters */
return ((source >= (int)'A') && (source <= (int)'Z')) ? source - 'A' + 'a' : source;
#endif
}
#endif
/**
Convert string to unsigned integer.
@param string String to be converted.
@param endp Pointer to end of converted string.
@param base Radix number of number.
*/
#if defined(TRIO_FUNC_TO_UNSIGNED_LONG)
TRIO_PUBLIC_STRING unsigned long trio_to_unsigned_long TRIO_ARGS3((string, endp, base),
TRIO_CONST char* string,
char** endp, int base)
{
assert(string);
assert((base >= 2) && (base <= 36));
return strtoul(string, endp, base);
}
#endif
/**
Convert one alphabetic letter to upper-case.
@param source The letter to be converted.
@return The converted letter.
*/
#if defined(TRIO_FUNC_TO_UPPER)
TRIO_PUBLIC_STRING int trio_to_upper TRIO_ARGS1((source), int source)
{
return internal_to_upper(source);
}
#endif
/**
Convert the alphabetic letters in the string to upper-case.
@param target The string to be converted.
@return The number of processed characters (converted or not).
*/
#if defined(TRIO_FUNC_UPPER)
TRIO_PUBLIC_STRING int trio_upper TRIO_ARGS1((target), char* target)
{
assert(target);
return trio_span_function(target, target, internal_to_upper);
}
#endif
/** @} End of StaticStrings */
/*************************************************************************
* Dynamic String Functions
*/
#if defined(TRIO_DOCUMENTATION)
#include "doc/doc_dynamic.h"
#endif
/** @addtogroup DynamicStrings
@{
*/
/**
Create a new dynamic string.
@param initial_size Initial size of the buffer.
@return Newly allocated dynamic string, or NULL if memory allocation failed.
*/
#if defined(TRIO_FUNC_STRING_CREATE)
TRIO_PUBLIC_STRING trio_string_t* trio_string_create TRIO_ARGS1((initial_size), int initial_size)
{
trio_string_t* self;
self = internal_string_alloc();
if (self)
{
if (internal_string_grow(self, (size_t)((initial_size > 0) ? initial_size : 1)))
{
self->content[0] = (char)0;
self->allocated = initial_size;
}
else
{
trio_string_destroy(self);
self = NULL;
}
}
return self;
}
#endif
/**
Deallocate the dynamic string and its contents.
@param self Dynamic string
*/
#if defined(TRIO_FUNC_STRING_DESTROY)
TRIO_PUBLIC_STRING void trio_string_destroy TRIO_ARGS1((self), trio_string_t* self)
{
assert(self);
if (self)
{
trio_destroy(self->content);
TRIO_FREE(self);
}
}
#endif
/**
Get a pointer to the content.
@param self Dynamic string.
@param offset Offset into content.
@return Pointer to the content.
@p Offset can be zero, positive, or negative. If @p offset is zero,
then the start of the content will be returned. If @p offset is positive,
then a pointer to @p offset number of characters from the beginning of the
content is returned. If @p offset is negative, then a pointer to @p offset
number of characters from the ending of the string, starting at the
terminating zero, is returned.
*/
#if defined(TRIO_FUNC_STRING_GET)
TRIO_PUBLIC_STRING char* trio_string_get TRIO_ARGS2((self, offset), trio_string_t* self, int offset)
{
char* result = NULL;
assert(self);
if (self->content != NULL)
{
if (self->length == 0)
{
(void)trio_string_length(self);
}
if (offset >= 0)
{
if (offset > (int)self->length)
{
offset = self->length;
}
}
else
{
offset += self->length + 1;
if (offset < 0)
{
offset = 0;
}
}
result = &(self->content[offset]);
}
return result;
}
#endif
/**
Extract the content.
@param self Dynamic String
@return Content of dynamic string.
The content is removed from the dynamic string. This enables destruction
of the dynamic string without deallocation of the content.
*/
#if defined(TRIO_FUNC_STRING_EXTRACT)
TRIO_PUBLIC_STRING char* trio_string_extract TRIO_ARGS1((self), trio_string_t* self)
{
char* result;
assert(self);
result = self->content;
/* FIXME: Allocate new empty buffer? */
self->content = NULL;
self->length = self->allocated = 0;
return result;
}
#endif
/**
Set the content of the dynamic string.
@param self Dynamic String
@param buffer The new content.
Sets the content of the dynamic string to a copy @p buffer.
An existing content will be deallocated first, if necessary.
@remark
This function will make a copy of @p buffer.
You are responsible for deallocating @p buffer yourself.
*/
#if defined(TRIO_FUNC_XSTRING_SET)
TRIO_PUBLIC_STRING void trio_xstring_set TRIO_ARGS2((self, buffer), trio_string_t* self,
char* buffer)
{
assert(self);
trio_destroy(self->content);
self->content = trio_duplicate(buffer);
}
#endif
/*
* trio_string_size
*/
#if defined(TRIO_FUNC_STRING_SIZE)
TRIO_PUBLIC_STRING int trio_string_size TRIO_ARGS1((self), trio_string_t* self)
{
assert(self);
return self->allocated;
}
#endif
/*
* trio_string_terminate
*/
#if defined(TRIO_FUNC_STRING_TERMINATE)
TRIO_PUBLIC_STRING void trio_string_terminate TRIO_ARGS1((self), trio_string_t* self)
{
trio_xstring_append_char(self, 0);
}
#endif
/**
Append the second string to the first.
@param self Dynamic string to be modified.
@param other Dynamic string to copy from.
@return Boolean value indicating success or failure.
*/
#if defined(TRIO_FUNC_STRING_APPEND)
TRIO_PUBLIC_STRING int trio_string_append TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
size_t length;
assert(self);
assert(other);
length = self->length + other->length;
if (!internal_string_grow_to(self, length))
goto error;
trio_copy(&self->content[self->length], other->content);
self->length = length;
return TRUE;
error:
return FALSE;
}
#endif
/*
* trio_xstring_append
*/
#if defined(TRIO_FUNC_XSTRING_APPEND)
TRIO_PUBLIC_STRING int trio_xstring_append TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
size_t length;
assert(self);
assert(other);
length = self->length + trio_length(other);
if (!internal_string_grow_to(self, length))
goto error;
trio_copy(&self->content[self->length], other);
self->length = length;
return TRUE;
error:
return FALSE;
}
#endif
/*
* trio_xstring_append_char
*/
#if defined(TRIO_FUNC_XSTRING_APPEND_CHAR)
TRIO_PUBLIC_STRING int trio_xstring_append_char TRIO_ARGS2((self, character), trio_string_t* self,
char character)
{
assert(self);
if ((int)self->length >= trio_string_size(self))
{
if (!internal_string_grow(self, 0))
goto error;
}
self->content[self->length] = character;
self->length++;
return TRUE;
error:
return FALSE;
}
#endif
/*
* trio_xstring_append_max
*/
#if defined(TRIO_FUNC_XSTRING_APPEND_MAX)
TRIO_PUBLIC_STRING int trio_xstring_append_max TRIO_ARGS3((self, other, max), trio_string_t* self,
TRIO_CONST char* other, size_t max)
{
size_t length;
assert(self);
assert(other);
length = self->length + trio_length_max(other, max);
if (!internal_string_grow_to(self, length))
goto error;
/*
* Pass max + 1 since trio_copy_max copies one character less than
* this from the source to make room for a terminating zero.
*/
trio_copy_max(&self->content[self->length], max + 1, other);
self->length = length;
return TRUE;
error:
return FALSE;
}
#endif
/**
Search for the first occurrence of second parameter in the first.
@param self Dynamic string to be modified.
@param other Dynamic string to copy from.
@return Boolean value indicating success or failure.
*/
#if defined(TRIO_FUNC_STRING_CONTAINS)
TRIO_PUBLIC_STRING int trio_string_contains TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_contains(self->content, other->content);
}
#endif
/*
* trio_xstring_contains
*/
#if defined(TRIO_FUNC_XSTRING_CONTAINS)
TRIO_PUBLIC_STRING int trio_xstring_contains TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_contains(self->content, other);
}
#endif
/*
* trio_string_copy
*/
#if defined(TRIO_FUNC_STRING_COPY)
TRIO_PUBLIC_STRING int trio_string_copy TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
self->length = 0;
return trio_string_append(self, other);
}
#endif
/*
* trio_xstring_copy
*/
#if defined(TRIO_FUNC_XSTRING_COPY)
TRIO_PUBLIC_STRING int trio_xstring_copy TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
self->length = 0;
return trio_xstring_append(self, other);
}
#endif
/*
* trio_string_duplicate
*/
#if defined(TRIO_FUNC_STRING_DUPLICATE)
TRIO_PUBLIC_STRING trio_string_t* trio_string_duplicate TRIO_ARGS1((other), trio_string_t* other)
{
trio_string_t* self;
assert(other);
self = internal_string_alloc();
if (self)
{
self->content = internal_duplicate_max(other->content, other->length);
if (self->content)
{
self->length = other->length;
self->allocated = self->length + 1;
}
else
{
self->length = self->allocated = 0;
}
}
return self;
}
#endif
/*
* trio_xstring_duplicate
*/
#if defined(TRIO_FUNC_XSTRING_DUPLICATE)
TRIO_PUBLIC_STRING trio_string_t* trio_xstring_duplicate TRIO_ARGS1((other), TRIO_CONST char* other)
{
trio_string_t* self;
assert(other);
self = internal_string_alloc();
if (self)
{
self->content = internal_duplicate_max(other, trio_length(other));
if (self->content)
{
self->length = trio_length(self->content);
self->allocated = self->length + 1;
}
else
{
self->length = self->allocated = 0;
}
}
return self;
}
#endif
/*
* trio_string_equal
*/
#if defined(TRIO_FUNC_STRING_EQUAL)
TRIO_PUBLIC_STRING int trio_string_equal TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_equal(self->content, other->content);
}
#endif
/*
* trio_xstring_equal
*/
#if defined(TRIO_FUNC_XSTRING_EQUAL)
TRIO_PUBLIC_STRING int trio_xstring_equal TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_equal(self->content, other);
}
#endif
/*
* trio_string_equal_max
*/
#if defined(TRIO_FUNC_STRING_EQUAL_MAX)
TRIO_PUBLIC_STRING int trio_string_equal_max TRIO_ARGS3((self, max, other), trio_string_t* self,
size_t max, trio_string_t* other)
{
assert(self);
assert(other);
return trio_equal_max(self->content, max, other->content);
}
#endif
/*
* trio_xstring_equal_max
*/
#if defined(TRIO_FUNC_XSTRING_EQUAL_MAX)
TRIO_PUBLIC_STRING int trio_xstring_equal_max TRIO_ARGS3((self, max, other), trio_string_t* self,
size_t max, TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_equal_max(self->content, max, other);
}
#endif
/*
* trio_string_equal_case
*/
#if defined(TRIO_FUNC_STRING_EQUAL_CASE)
TRIO_PUBLIC_STRING int trio_string_equal_case TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_equal_case(self->content, other->content);
}
#endif
/*
* trio_xstring_equal_case
*/
#if defined(TRIO_FUNC_XSTRING_EQUAL_CASE)
TRIO_PUBLIC_STRING int trio_xstring_equal_case TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_equal_case(self->content, other);
}
#endif
/*
* trio_string_equal_case_max
*/
#if defined(TRIO_FUNC_STRING_EQUAL_CASE_MAX)
TRIO_PUBLIC_STRING int trio_string_equal_case_max TRIO_ARGS3((self, max, other),
trio_string_t* self, size_t max,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_equal_case_max(self->content, max, other->content);
}
#endif
/*
* trio_xstring_equal_case_max
*/
#if defined(TRIO_FUNC_XSTRING_EQUAL_CASE_MAX)
TRIO_PUBLIC_STRING int trio_xstring_equal_case_max TRIO_ARGS3((self, max, other),
trio_string_t* self, size_t max,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_equal_case_max(self->content, max, other);
}
#endif
/*
* trio_string_format_data_max
*/
#if defined(TRIO_FUNC_STRING_FORMAT_DATE_MAX)
TRIO_PUBLIC_STRING size_t trio_string_format_date_max TRIO_ARGS4((self, max, format, datetime),
trio_string_t* self, size_t max,
TRIO_CONST char* format,
TRIO_CONST struct tm* datetime)
{
assert(self);
return trio_format_date_max(self->content, max, format, datetime);
}
#endif
/*
* trio_string_index
*/
#if defined(TRIO_FUNC_STRING_INDEX)
TRIO_PUBLIC_STRING char* trio_string_index TRIO_ARGS2((self, character), trio_string_t* self,
int character)
{
assert(self);
return trio_index(self->content, character);
}
#endif
/*
* trio_string_index_last
*/
#if defined(TRIO_FUNC_STRING_INDEX_LAST)
TRIO_PUBLIC_STRING char* trio_string_index_last TRIO_ARGS2((self, character), trio_string_t* self,
int character)
{
assert(self);
return trio_index_last(self->content, character);
}
#endif
/*
* trio_string_length
*/
#if defined(TRIO_FUNC_STRING_LENGTH)
TRIO_PUBLIC_STRING int trio_string_length TRIO_ARGS1((self), trio_string_t* self)
{
assert(self);
if (self->length == 0)
{
self->length = trio_length(self->content);
}
return self->length;
}
#endif
/*
* trio_string_lower
*/
#if defined(TRIO_FUNC_STRING_LOWER)
TRIO_PUBLIC_STRING int trio_string_lower TRIO_ARGS1((self), trio_string_t* self)
{
assert(self);
return trio_lower(self->content);
}
#endif
/*
* trio_string_match
*/
#if defined(TRIO_FUNC_STRING_MATCH)
TRIO_PUBLIC_STRING int trio_string_match TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_match(self->content, other->content);
}
#endif
/*
* trio_xstring_match
*/
#if defined(TRIO_FUNC_XSTRING_MATCH)
TRIO_PUBLIC_STRING int trio_xstring_match TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_match(self->content, other);
}
#endif
/*
* trio_string_match_case
*/
#if defined(TRIO_FUNC_STRING_MATCH_CASE)
TRIO_PUBLIC_STRING int trio_string_match_case TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_match_case(self->content, other->content);
}
#endif
/*
* trio_xstring_match_case
*/
#if defined(TRIO_FUNC_XSTRING_MATCH_CASE)
TRIO_PUBLIC_STRING int trio_xstring_match_case TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_match_case(self->content, other);
}
#endif
/*
* trio_string_substring
*/
#if defined(TRIO_FUNC_STRING_SUBSTRING)
TRIO_PUBLIC_STRING char* trio_string_substring TRIO_ARGS2((self, other), trio_string_t* self,
trio_string_t* other)
{
assert(self);
assert(other);
return trio_substring(self->content, other->content);
}
#endif
/*
* trio_xstring_substring
*/
#if defined(TRIO_FUNC_XSTRING_SUBSTRING)
TRIO_PUBLIC_STRING char* trio_xstring_substring TRIO_ARGS2((self, other), trio_string_t* self,
TRIO_CONST char* other)
{
assert(self);
assert(other);
return trio_substring(self->content, other);
}
#endif
/*
* trio_string_upper
*/
#if defined(TRIO_FUNC_STRING_UPPER)
TRIO_PUBLIC_STRING int trio_string_upper TRIO_ARGS1((self), trio_string_t* self)
{
assert(self);
return trio_upper(self->content);
}
#endif
/** @} End of DynamicStrings */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4493_1 |
crossvul-cpp_data_bad_4686_0 |
#include <config.h>
#include "ftpd.h"
#include "utils.h"
#ifdef WITH_DMALLOC
# include <dmalloc.h>
#endif
#ifdef HAVE_LIBSODIUM
# if !defined(pure_memzero) || !defined(pure_memcmp)
# error pure_memzero/pure_memcmp not defined
# endif
#else
void pure_memzero(void * const pnt, const size_t len)
{
# ifdef HAVE_EXPLICIT_BZERO
explicit_bzero(pnt, len);
# else
volatile unsigned char *pnt_ = (volatile unsigned char *) pnt;
size_t i = (size_t) 0U;
while (i < len) {
pnt_[i++] = 0U;
}
# endif
}
int pure_memcmp(const void * const b1_, const void * const b2_, size_t len)
{
const unsigned char *b1 = (const unsigned char *) b1_;
const unsigned char *b2 = (const unsigned char *) b2_;
size_t i;
unsigned char d = (unsigned char) 0U;
for (i = 0U; i < len; i++) {
d |= b1[i] ^ b2[i];
}
return (int) ((1 & ((d - 1) >> 8)) - 1);
}
#endif
int pure_strcmp(const char * const s1, const char * const s2)
{
return pure_memcmp(s1, s2, strlen(s1) + 1U);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4686_0 |
crossvul-cpp_data_good_949_1 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% FFFFF OOO U U RRRR IIIII EEEEE RRRR %
% F O O U U R R I E R R %
% FFF O O U U RRRR I EEE RRRR %
% F O O U U R R I E R R %
% F OOO UUU R R IIIII EEEEE R R %
% %
% %
% MagickCore Discrete Fourier Transform Methods %
% %
% Software Design %
% Sean Burke %
% Fred Weinhaus %
% Cristy %
% July 2009 %
% %
% %
% Copyright 1999-2019 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 %
% %
% https://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 "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/fourier.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#if defined(MAGICKCORE_FFTW_DELEGATE)
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
#include <complex.h>
#endif
#include <fftw3.h>
#if !defined(MAGICKCORE_HAVE_CABS)
#define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1]))
#endif
#if !defined(MAGICKCORE_HAVE_CARG)
#define carg(z) (atan2(cimag(z),creal(z)))
#endif
#if !defined(MAGICKCORE_HAVE_CIMAG)
#define cimag(z) (z[1])
#endif
#if !defined(MAGICKCORE_HAVE_CREAL)
#define creal(z) (z[0])
#endif
#endif
/*
Typedef declarations.
*/
typedef struct _FourierInfo
{
PixelChannel
channel;
MagickBooleanType
modulus;
size_t
width,
height;
ssize_t
center;
} FourierInfo;
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C o m p l e x I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ComplexImages() performs complex mathematics on an image sequence.
%
% The format of the ComplexImages method is:
%
% MagickBooleanType ComplexImages(Image *images,const ComplexOperator op,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o op: A complex operator.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op,
ExceptionInfo *exception)
{
#define ComplexImageTag "Complex/Image"
CacheView
*Ai_view,
*Ar_view,
*Bi_view,
*Br_view,
*Ci_view,
*Cr_view;
const char
*artifact;
const Image
*Ai_image,
*Ar_image,
*Bi_image,
*Br_image;
double
snr;
Image
*Ci_image,
*complex_images,
*Cr_image,
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (images->next == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",images->filename);
return((Image *) NULL);
}
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
{
image=DestroyImageList(image);
return(image);
}
image->depth=32UL;
complex_images=NewImageList();
AppendImageToList(&complex_images,image);
image=CloneImage(images,0,0,MagickTrue,exception);
if (image == (Image *) NULL)
{
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
AppendImageToList(&complex_images,image);
/*
Apply complex mathematics to image pixels.
*/
artifact=GetImageArtifact(image,"complex:snr");
snr=0.0;
if (artifact != (const char *) NULL)
snr=StringToDouble(artifact,(char **) NULL);
Ar_image=images;
Ai_image=images->next;
Br_image=images;
Bi_image=images->next;
if ((images->next->next != (Image *) NULL) &&
(images->next->next->next != (Image *) NULL))
{
Br_image=images->next->next;
Bi_image=images->next->next->next;
}
Cr_image=complex_images;
Ci_image=complex_images->next;
Ar_view=AcquireVirtualCacheView(Ar_image,exception);
Ai_view=AcquireVirtualCacheView(Ai_image,exception);
Br_view=AcquireVirtualCacheView(Br_image,exception);
Bi_view=AcquireVirtualCacheView(Bi_image,exception);
Cr_view=AcquireAuthenticCacheView(Cr_image,exception);
Ci_view=AcquireAuthenticCacheView(Ci_image,exception);
status=MagickTrue;
progress=0;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(images,complex_images,images->rows,1L)
#endif
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*magick_restrict Ai,
*magick_restrict Ar,
*magick_restrict Bi,
*magick_restrict Br;
register Quantum
*magick_restrict Ci,
*magick_restrict Cr;
register ssize_t
x;
if (status == MagickFalse)
continue;
Ar=GetCacheViewVirtualPixels(Ar_view,0,y,
MagickMax(Ar_image->columns,Cr_image->columns),1,exception);
Ai=GetCacheViewVirtualPixels(Ai_view,0,y,
MagickMax(Ai_image->columns,Ci_image->columns),1,exception);
Br=GetCacheViewVirtualPixels(Br_view,0,y,
MagickMax(Br_image->columns,Cr_image->columns),1,exception);
Bi=GetCacheViewVirtualPixels(Bi_view,0,y,
MagickMax(Bi_image->columns,Ci_image->columns),1,exception);
Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception);
Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception);
if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) ||
(Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) ||
(Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) images->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(images); i++)
{
switch (op)
{
case AddComplexOperator:
{
Cr[i]=Ar[i]+Br[i];
Ci[i]=Ai[i]+Bi[i];
break;
}
case ConjugateComplexOperator:
default:
{
Cr[i]=Ar[i];
Ci[i]=(-Bi[i]);
break;
}
case DivideComplexOperator:
{
double
gamma;
gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr);
Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]);
Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]);
break;
}
case MagnitudePhaseComplexOperator:
{
Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]);
Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5;
break;
}
case MultiplyComplexOperator:
{
Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]);
Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]);
break;
}
case RealImaginaryComplexOperator:
{
Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5));
Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5));
break;
}
case SubtractComplexOperator:
{
Cr[i]=Ar[i]-Br[i];
Ci[i]=Ai[i]-Bi[i];
break;
}
}
}
Ar+=GetPixelChannels(Ar_image);
Ai+=GetPixelChannels(Ai_image);
Br+=GetPixelChannels(Br_image);
Bi+=GetPixelChannels(Bi_image);
Cr+=GetPixelChannels(Cr_image);
Ci+=GetPixelChannels(Ci_image);
}
if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse)
status=MagickFalse;
if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(images,ComplexImageTag,progress,images->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
Cr_view=DestroyCacheView(Cr_view);
Ci_view=DestroyCacheView(Ci_view);
Br_view=DestroyCacheView(Br_view);
Bi_view=DestroyCacheView(Bi_view);
Ar_view=DestroyCacheView(Ar_view);
Ai_view=DestroyCacheView(Ai_view);
if (status == MagickFalse)
complex_images=DestroyImageList(complex_images);
return(complex_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F o r w a r d F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ForwardFourierTransformImage() implements the discrete Fourier transform
% (DFT) of the image either as a magnitude / phase or real / imaginary image
% pair.
%
% The format of the ForwadFourierTransformImage method is:
%
% Image *ForwardFourierTransformImage(const Image *image,
% const MagickBooleanType modulus,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o modulus: if true, return as transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType RollFourier(const size_t width,const size_t height,
const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels)
{
double
*source_pixels;
MemoryInfo
*source_info;
register ssize_t
i,
x;
ssize_t
u,
v,
y;
/*
Move zero frequency (DC, average color) from (0,0) to (width/2,height/2).
*/
source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
return(MagickFalse);
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
i=0L;
for (y=0L; y < (ssize_t) height; y++)
{
if (y_offset < 0L)
v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset;
else
v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height :
y+y_offset;
for (x=0L; x < (ssize_t) width; x++)
{
if (x_offset < 0L)
u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset;
else
u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width :
x+x_offset;
source_pixels[v*width+u]=roll_pixels[i++];
}
}
(void) memcpy(roll_pixels,source_pixels,height*width*
sizeof(*source_pixels));
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType ForwardQuadrantSwap(const size_t width,
const size_t height,double *source_pixels,double *forward_pixels)
{
MagickBooleanType
status;
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L,
source_pixels);
if (status == MagickFalse)
return(MagickFalse);
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x];
for (y=1; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[(height-y)*width+width/2L-x-1L]=
source_pixels[y*center+x+1L];
for (x=0L; x < (ssize_t) (width/2L); x++)
forward_pixels[width/2L-x-1L]=source_pixels[x+1L];
return(MagickTrue);
}
static void CorrectPhaseLHS(const size_t width,const size_t height,
double *fourier_pixels)
{
register ssize_t
x;
ssize_t
y;
for (y=0L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L); x++)
fourier_pixels[y*width+x]*=(-1.0);
}
static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info,
Image *image,double *magnitude,double *phase,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*magnitude_pixels,
*phase_pixels;
Image
*magnitude_image,
*phase_image;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
register Quantum
*q;
register ssize_t
x;
ssize_t
i,
y;
magnitude_image=GetFirstImageInList(image);
phase_image=GetNextImageInList(image);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",image->filename);
return(MagickFalse);
}
/*
Create "Fourier Transform" image from constituent arrays.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
(void) memset(magnitude_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*magnitude_pixels));
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
(void) memset(phase_pixels,0,fourier_info->width*
fourier_info->height*sizeof(*phase_pixels));
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude,magnitude_pixels);
if (status != MagickFalse)
status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase,
phase_pixels);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]/=(2.0*MagickPI);
phase_pixels[i]+=0.5;
i++;
}
}
magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception);
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange*
magnitude_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(magnitude_image);
}
status=SyncCacheViewAuthenticPixels(magnitude_view,exception);
if (status == MagickFalse)
break;
}
magnitude_view=DestroyCacheView(magnitude_view);
i=0L;
phase_view=AcquireAuthenticCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange*
phase_pixels[i]),q);
break;
}
}
i++;
q+=GetPixelChannels(phase_image);
}
status=SyncCacheViewAuthenticPixels(phase_view,exception);
if (status == MagickFalse)
break;
}
phase_view=DestroyCacheView(phase_view);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info,
const Image *image,double *magnitude_pixels,double *phase_pixels,
ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_complex
*forward_pixels;
fftw_plan
fftw_r2c_plan;
MemoryInfo
*forward_info,
*source_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Generate the forward Fourier transform.
*/
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
memset(source_pixels,0,fourier_info->width*fourier_info->height*
sizeof(*source_pixels));
i=0L;
image_view=AcquireVirtualCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
source_pixels[i]=QuantumScale*GetPixelRed(image,p);
break;
}
case GreenPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelGreen(image,p);
break;
}
case BluePixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlue(image,p);
break;
}
case BlackPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelBlack(image,p);
break;
}
case AlphaPixelChannel:
{
source_pixels[i]=QuantumScale*GetPixelAlpha(image,p);
break;
}
}
i++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
forward_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*forward_pixels));
if (forward_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
return(MagickFalse);
}
forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ForwardFourierTransform)
#endif
fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height,
source_pixels,forward_pixels,FFTW_ESTIMATE);
fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels);
fftw_destroy_plan(fftw_r2c_plan);
source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0))
{
double
gamma;
/*
Normalize fourier transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
forward_pixels[i]*=gamma;
#else
forward_pixels[i][0]*=gamma;
forward_pixels[i][1]*=gamma;
#endif
i++;
}
}
/*
Generate magnitude and phase (or real and imaginary).
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=cabs(forward_pixels[i]);
phase_pixels[i]=carg(forward_pixels[i]);
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
magnitude_pixels[i]=creal(forward_pixels[i]);
phase_pixels[i]=cimag(forward_pixels[i]);
i++;
}
forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info);
return(MagickTrue);
}
static MagickBooleanType ForwardFourierTransformChannel(const Image *image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
double
*magnitude_pixels,
*phase_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*magnitude_info,
*phase_info;
fourier_info.width=image->columns;
fourier_info.height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows : image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*phase_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL))
{
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (magnitude_info == (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels,
phase_pixels,exception);
if (status != MagickFalse)
status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels,
phase_pixels,exception);
phase_info=RelinquishVirtualMemory(phase_info);
magnitude_info=RelinquishVirtualMemory(magnitude_info);
return(status);
}
#endif
MagickExport Image *ForwardFourierTransformImage(const Image *image,
const MagickBooleanType modulus,ExceptionInfo *exception)
{
Image
*fourier_image;
fourier_image=NewImageList();
#if !defined(MAGICKCORE_FFTW_DELEGATE)
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
image->filename);
#else
{
Image
*magnitude_image;
size_t
height,
width;
width=image->columns;
height=image->rows;
if ((image->columns != image->rows) || ((image->columns % 2) != 0) ||
((image->rows % 2) != 0))
{
size_t extent=image->columns < image->rows ? image->rows :
image->columns;
width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
height=width;
magnitude_image=CloneImage(image,width,height,MagickTrue,exception);
if (magnitude_image != (Image *) NULL)
{
Image
*phase_image;
magnitude_image->storage_class=DirectClass;
magnitude_image->depth=32UL;
phase_image=CloneImage(image,width,height,MagickTrue,exception);
if (phase_image == (Image *) NULL)
magnitude_image=DestroyImage(magnitude_image);
else
{
MagickBooleanType
is_gray,
status;
phase_image->storage_class=DirectClass;
phase_image->depth=32UL;
AppendImageToList(&fourier_image,magnitude_image);
AppendImageToList(&fourier_image,phase_image);
status=MagickTrue;
is_gray=IsImageGray(image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=ForwardFourierTransformChannel(image,
RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=ForwardFourierTransformChannel(image,
BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->colorspace == CMYKColorspace)
thread_status=ForwardFourierTransformChannel(image,
BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (image->alpha_trait != UndefinedPixelTrait)
thread_status=ForwardFourierTransformChannel(image,
AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImageList(fourier_image);
fftw_cleanup();
}
}
}
#endif
return(fourier_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n v e r s e F o u r i e r T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InverseFourierTransformImage() implements the inverse discrete Fourier
% transform (DFT) of the image either as a magnitude / phase or real /
% imaginary image pair.
%
% The format of the InverseFourierTransformImage method is:
%
% Image *InverseFourierTransformImage(const Image *magnitude_image,
% const Image *phase_image,const MagickBooleanType modulus,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o magnitude_image: the magnitude or real image.
%
% o phase_image: the phase or imaginary image.
%
% o modulus: if true, return transform as a magnitude / phase pair
% otherwise a real / imaginary image pair.
%
% o exception: return any errors or warnings in this structure.
%
*/
#if defined(MAGICKCORE_FFTW_DELEGATE)
static MagickBooleanType InverseQuadrantSwap(const size_t width,
const size_t height,const double *source,double *destination)
{
register ssize_t
x;
ssize_t
center,
y;
/*
Swap quadrants.
*/
center=(ssize_t) (width/2L)+1L;
for (y=1L; y < (ssize_t) height; y++)
for (x=0L; x < (ssize_t) (width/2L+1L); x++)
destination[(height-y)*center-x+width/2L]=source[y*width+x];
for (y=0L; y < (ssize_t) height; y++)
destination[y*center]=source[y*width+width/2L];
for (x=0L; x < center; x++)
destination[x]=source[center-x-1L];
return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination));
}
static MagickBooleanType InverseFourier(FourierInfo *fourier_info,
const Image *magnitude_image,const Image *phase_image,
fftw_complex *fourier_pixels,ExceptionInfo *exception)
{
CacheView
*magnitude_view,
*phase_view;
double
*inverse_pixels,
*magnitude_pixels,
*phase_pixels;
MagickBooleanType
status;
MemoryInfo
*inverse_info,
*magnitude_info,
*phase_info;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
/*
Inverse fourier - read image and break down into a double array.
*/
magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*magnitude_pixels));
phase_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*phase_pixels));
inverse_info=AcquireVirtualMemory((size_t) fourier_info->width,
(fourier_info->height/2+1)*sizeof(*inverse_pixels));
if ((magnitude_info == (MemoryInfo *) NULL) ||
(phase_info == (MemoryInfo *) NULL) ||
(inverse_info == (MemoryInfo *) NULL))
{
if (magnitude_info != (MemoryInfo *) NULL)
magnitude_info=RelinquishVirtualMemory(magnitude_info);
if (phase_info != (MemoryInfo *) NULL)
phase_info=RelinquishVirtualMemory(phase_info);
if (inverse_info != (MemoryInfo *) NULL)
inverse_info=RelinquishVirtualMemory(inverse_info);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info);
phase_pixels=(double *) GetVirtualMemoryBlob(phase_info);
inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info);
i=0L;
magnitude_view=AcquireVirtualCacheView(magnitude_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p);
break;
}
case GreenPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p);
break;
}
case BluePixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p);
break;
}
case BlackPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p);
break;
}
case AlphaPixelChannel:
{
magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p);
break;
}
}
i++;
p+=GetPixelChannels(magnitude_image);
}
}
magnitude_view=DestroyCacheView(magnitude_view);
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
magnitude_pixels,inverse_pixels);
(void) memcpy(magnitude_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*magnitude_pixels));
i=0L;
phase_view=AcquireVirtualCacheView(phase_image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1,
exception);
if (p == (const Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p);
break;
}
case GreenPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p);
break;
}
case BluePixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p);
break;
}
case BlackPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p);
break;
}
case AlphaPixelChannel:
{
phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p);
break;
}
}
i++;
p+=GetPixelChannels(phase_image);
}
}
if (fourier_info->modulus != MagickFalse)
{
i=0L;
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
phase_pixels[i]-=0.5;
phase_pixels[i]*=(2.0*MagickPI);
i++;
}
}
phase_view=DestroyCacheView(phase_view);
CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels);
if (status != MagickFalse)
status=InverseQuadrantSwap(fourier_info->width,fourier_info->height,
phase_pixels,inverse_pixels);
(void) memcpy(phase_pixels,inverse_pixels,fourier_info->height*
fourier_info->center*sizeof(*phase_pixels));
inverse_info=RelinquishVirtualMemory(inverse_info);
/*
Merge two sets.
*/
i=0L;
if (fourier_info->modulus != MagickFalse)
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I*
magnitude_pixels[i]*sin(phase_pixels[i]);
#else
fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]);
fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]);
#endif
i++;
}
else
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i];
#else
fourier_pixels[i][0]=magnitude_pixels[i];
fourier_pixels[i][1]=phase_pixels[i];
#endif
i++;
}
magnitude_info=RelinquishVirtualMemory(magnitude_info);
phase_info=RelinquishVirtualMemory(phase_info);
return(status);
}
static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info,
fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception)
{
CacheView
*image_view;
const char
*value;
double
*source_pixels;
fftw_plan
fftw_c2r_plan;
MemoryInfo
*source_info;
register Quantum
*q;
register ssize_t
i,
x;
ssize_t
y;
source_info=AcquireVirtualMemory((size_t) fourier_info->width,
fourier_info->height*sizeof(*source_pixels));
if (source_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
source_pixels=(double *) GetVirtualMemoryBlob(source_info);
value=GetImageArtifact(image,"fourier:normalize");
if (LocaleCompare(value,"inverse") == 0)
{
double
gamma;
/*
Normalize inverse transform.
*/
i=0L;
gamma=PerceptibleReciprocal((double) fourier_info->width*
fourier_info->height);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
for (x=0L; x < (ssize_t) fourier_info->center; x++)
{
#if defined(MAGICKCORE_HAVE_COMPLEX_H)
fourier_pixels[i]*=gamma;
#else
fourier_pixels[i][0]*=gamma;
fourier_pixels[i][1]*=gamma;
#endif
i++;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_InverseFourierTransform)
#endif
fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height,
fourier_pixels,source_pixels,FFTW_ESTIMATE);
fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels);
fftw_destroy_plan(fftw_c2r_plan);
i=0L;
image_view=AcquireAuthenticCacheView(image,exception);
for (y=0L; y < (ssize_t) fourier_info->height; y++)
{
if (y >= (ssize_t) image->rows)
break;
q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width >
image->columns ? image->columns : fourier_info->width,1UL,exception);
if (q == (Quantum *) NULL)
break;
for (x=0L; x < (ssize_t) fourier_info->width; x++)
{
if (x < (ssize_t) image->columns)
switch (fourier_info->channel)
{
case RedPixelChannel:
default:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q);
break;
}
case GreenPixelChannel:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BluePixelChannel:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case BlackPixelChannel:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
case AlphaPixelChannel:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]),
q);
break;
}
}
i++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
break;
}
image_view=DestroyCacheView(image_view);
source_info=RelinquishVirtualMemory(source_info);
return(MagickTrue);
}
static MagickBooleanType InverseFourierTransformChannel(
const Image *magnitude_image,const Image *phase_image,
const PixelChannel channel,const MagickBooleanType modulus,
Image *fourier_image,ExceptionInfo *exception)
{
fftw_complex
*inverse_pixels;
FourierInfo
fourier_info;
MagickBooleanType
status;
MemoryInfo
*inverse_info;
fourier_info.width=magnitude_image->columns;
fourier_info.height=magnitude_image->rows;
if ((magnitude_image->columns != magnitude_image->rows) ||
((magnitude_image->columns % 2) != 0) ||
((magnitude_image->rows % 2) != 0))
{
size_t extent=magnitude_image->columns < magnitude_image->rows ?
magnitude_image->rows : magnitude_image->columns;
fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent;
}
fourier_info.height=fourier_info.width;
fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L;
fourier_info.channel=channel;
fourier_info.modulus=modulus;
inverse_info=AcquireVirtualMemory((size_t) fourier_info.width,
(fourier_info.height/2+1)*sizeof(*inverse_pixels));
if (inverse_info == (MemoryInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
magnitude_image->filename);
return(MagickFalse);
}
inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info);
status=InverseFourier(&fourier_info,magnitude_image,phase_image,
inverse_pixels,exception);
if (status != MagickFalse)
status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image,
exception);
inverse_info=RelinquishVirtualMemory(inverse_info);
return(status);
}
#endif
MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image,
const Image *phase_image,const MagickBooleanType modulus,
ExceptionInfo *exception)
{
Image
*fourier_image;
assert(magnitude_image != (Image *) NULL);
assert(magnitude_image->signature == MagickCoreSignature);
if (magnitude_image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
magnitude_image->filename);
if (phase_image == (Image *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ImageSequenceRequired","`%s'",magnitude_image->filename);
return((Image *) NULL);
}
#if !defined(MAGICKCORE_FFTW_DELEGATE)
fourier_image=(Image *) NULL;
(void) modulus;
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)",
magnitude_image->filename);
#else
{
fourier_image=CloneImage(magnitude_image,magnitude_image->columns,
magnitude_image->rows,MagickTrue,exception);
if (fourier_image != (Image *) NULL)
{
MagickBooleanType
is_gray,
status;
status=MagickTrue;
is_gray=IsImageGray(magnitude_image);
if (is_gray != MagickFalse)
is_gray=IsImageGray(phase_image);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel sections
#endif
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
if (is_gray != MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GrayPixelChannel,modulus,fourier_image,exception);
else
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,RedPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,GreenPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (is_gray == MagickFalse)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BluePixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->colorspace == CMYKColorspace)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,BlackPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp section
#endif
{
MagickBooleanType
thread_status;
thread_status=MagickTrue;
if (magnitude_image->alpha_trait != UndefinedPixelTrait)
thread_status=InverseFourierTransformChannel(magnitude_image,
phase_image,AlphaPixelChannel,modulus,fourier_image,exception);
if (thread_status == MagickFalse)
status=thread_status;
}
}
if (status == MagickFalse)
fourier_image=DestroyImage(fourier_image);
}
fftw_cleanup();
}
#endif
return(fourier_image);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_949_1 |
crossvul-cpp_data_bad_3369_0 | // imagew-jpeg.c
// Part of ImageWorsener, Copyright (c) 2011 by Jason Summers.
// For more information, see the readme.txt file.
#include "imagew-config.h"
#if IW_SUPPORT_JPEG == 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <setjmp.h>
#include <jpeglib.h>
#include <jerror.h>
#define IW_INCLUDE_UTIL_FUNCTIONS
#include "imagew.h"
#if BITS_IN_JSAMPLE != 8
#error "Wrong JSAMPLE size"
#endif
struct my_error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
static void my_error_exit(j_common_ptr cinfo)
{
struct my_error_mgr* myerr = (struct my_error_mgr*)cinfo->err;
longjmp(myerr->setjmp_buffer, 1);
}
// If we don't make our own output_message function, libjpeg will
// print warnings to stderr.
static void my_output_message(j_common_ptr cinfo)
{
return;
}
struct iwjpegrcontext {
struct jpeg_source_mgr pub; // This field must be first.
struct iw_context *ctx;
struct iw_iodescr *iodescr;
JOCTET *buffer;
size_t buffer_len;
int is_jfif;
unsigned int exif_orientation; // 0 means not set
double exif_density_x, exif_density_y; // -1.0 means not set.
unsigned int exif_density_unit; // 0 means not set
};
struct iw_exif_state {
int endian;
const iw_byte *d;
size_t d_len;
};
// Try to read an Exif tag into an integer.
// Returns zero on failure.
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);
value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);
if(value_count!=1) return 0;
if(field_type==3) { // SHORT (uint16)
*pv = iw_get_ui16_e(&e->d[tag_pos+8],e->endian);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
return 1;
}
return 0;
}
// Read an Exif tag into a double.
// This only supports the case where the tag contains exactly one Rational value.
static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,
double *pv)
{
unsigned int field_type;
unsigned int value_count;
unsigned int value_pos;
unsigned int numer, denom;
field_type = iw_get_ui16_e(&e->d[tag_pos+2],e->endian);
value_count = iw_get_ui32_e(&e->d[tag_pos+4],e->endian);
if(value_count!=1) return 0;
if(field_type!=5) return 0; // 5=Rational (two uint32's)
// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read
// the location where it is stored.
value_pos = iw_get_ui32_e(&e->d[tag_pos+8],e->endian);
if(value_pos > e->d_len-8) return 0;
// Read the actual value.
numer = iw_get_ui32_e(&e->d[value_pos ],e->endian);
denom = iw_get_ui32_e(&e->d[value_pos+4],e->endian);
if(denom==0) return 0;
*pv = ((double)numer)/denom;
return 1;
}
static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,
struct iw_exif_state *e, iw_uint32 ifd)
{
unsigned int tag_count;
unsigned int i;
unsigned int tag_pos;
unsigned int tag_id;
unsigned int v;
double v_dbl;
if(ifd<8 || ifd>e->d_len-18) return;
tag_count = iw_get_ui16_e(&e->d[ifd],e->endian);
if(tag_count>1000) return; // Sanity check.
for(i=0;i<tag_count;i++) {
tag_pos = ifd+2+i*12;
if(tag_pos+12 > e->d_len) return; // Avoid overruns.
tag_id = iw_get_ui16_e(&e->d[tag_pos],e->endian);
switch(tag_id) {
case 274: // 274 = Orientation
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_orientation = v;
}
break;
case 296: // 296 = ResolutionUnit
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_density_unit = v;
}
break;
case 282: // 282 = XResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_x = v_dbl;
}
break;
case 283: // 283 = YResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_y = v_dbl;
}
break;
}
}
}
static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,
const iw_byte *d, size_t d_len)
{
struct iw_exif_state e;
iw_uint32 ifd;
if(d_len<8) return;
iw_zeromem(&e,sizeof(struct iw_exif_state));
e.d = d;
e.d_len = d_len;
e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;
ifd = iw_get_ui32_e(&d[4],e.endian);
iwjpeg_scan_exif_ifd(rctx,&e,ifd);
}
// Look at the saved JPEG markers.
// The only one we care about is Exif.
static void iwjpeg_read_saved_markers(struct iwjpegrcontext *rctx,
struct jpeg_decompress_struct *cinfo)
{
struct jpeg_marker_struct *mk;
const iw_byte *d;
mk = cinfo->marker_list;
// Walk the list of saved markers.
while(mk) {
d = (const iw_byte*)mk->data;
if(mk->marker==0xe1) {
if(mk->data_length>=6 && d[0]=='E' && d[1]=='x' &&
d[2]=='i' && d[3]=='f' && d[4]==0)
{
// I don't know what the d[5] byte is for, but Exif
// data always starts with d[6].
iwjpeg_scan_exif(rctx, &d[6], mk->data_length-6);
}
}
mk = mk->next;
}
}
static void iwjpeg_read_density(struct iw_context *ctx, struct iw_image *img,
struct jpeg_decompress_struct *cinfo)
{
switch(cinfo->density_unit) {
case 1: // pixels/inch
img->density_x = ((double)cinfo->X_density)/0.0254;
img->density_y = ((double)cinfo->Y_density)/0.0254;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
case 2: // pixels/cm
img->density_x = ((double)cinfo->X_density)*100.0;
img->density_y = ((double)cinfo->Y_density)*100.0;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
default: // unknown units
// If we have square pixels with unknown units, we might be looking at
// libjpeg's default (i.e. no JFIF segment), or the density might have
// been read from the file. In either case, leave the density set to
// "unknown", which allows it to be overridden later by Exif data.
if(cinfo->X_density!=cinfo->Y_density) {
img->density_x = (double)cinfo->X_density;
img->density_y = (double)cinfo->Y_density;
img->density_code = IW_DENSITY_UNITS_UNKNOWN;
}
}
}
// Look at the Exif density setting that we may have recorded, and copy
// it to the image, if appropriate.
static void handle_exif_density(struct iwjpegrcontext *rctx, struct iw_image *img)
{
if(img->density_code!=IW_DENSITY_UNKNOWN) {
// We already have a density, presumably from the JFIF segment.
// TODO: In principle, Exif should not be allowed to overrule JFIF.
// But Exif density can be more precise than JFIF density, so it might
// be better to respect Exif.
// (On the other other hand, files with Exif data are usually from
// digital cameras, which means the density information is unlikely
// to be meaningful anyway.)
return;
}
if(rctx->exif_density_x<=0.0 || rctx->exif_density_y<=0.0) return;
switch(rctx->exif_density_unit) {
case 1: // No units
if(fabs(rctx->exif_density_x-rctx->exif_density_y)<0.00001)
return; // Square, unitless pixels = no meaningful information.
img->density_x = rctx->exif_density_x;
img->density_y = rctx->exif_density_y;
img->density_code = IW_DENSITY_UNITS_UNKNOWN;
break;
case 2: // Inches
img->density_x = rctx->exif_density_x/0.0254;
img->density_y = rctx->exif_density_y/0.0254;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
case 3: // Centimeters
img->density_x = rctx->exif_density_x*100.0;
img->density_y = rctx->exif_density_y*100.0;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
}
}
static void my_init_source_fn(j_decompress_ptr cinfo)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = 0;
}
static boolean my_fill_input_buffer_fn(j_decompress_ptr cinfo)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
size_t bytesread = 0;
int ret;
ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr,
rctx->buffer,rctx->buffer_len,&bytesread);
if(!ret) return FALSE;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = bytesread;
if(bytesread<1) return FALSE;
return TRUE;
}
static void my_skip_input_data_fn(j_decompress_ptr cinfo, long num_bytes)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
size_t bytes_still_to_skip;
size_t nbytes;
int ret;
size_t bytesread;
if(num_bytes<=0) return;
bytes_still_to_skip = (size_t)num_bytes;
while(bytes_still_to_skip>0) {
if(rctx->pub.bytes_in_buffer>0) {
// There are some bytes in the buffer. Skip up to
// 'bytes_still_to_skip' of them.
nbytes = rctx->pub.bytes_in_buffer;
if(nbytes>bytes_still_to_skip)
nbytes = bytes_still_to_skip;
rctx->pub.bytes_in_buffer -= nbytes;
rctx->pub.next_input_byte += nbytes;
bytes_still_to_skip -= nbytes;
}
if(bytes_still_to_skip<1) return;
// Need to read from the file (or do a seek, but we currently don't
// support seeking).
ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr,
rctx->buffer,rctx->buffer_len,&bytesread);
if(!ret) bytesread=0;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = bytesread;
}
}
static void my_term_source_fn(j_decompress_ptr cinfo)
{
}
static void convert_cmyk_to_rbg(struct iw_context *ctx, const JSAMPLE *src,
JSAMPLE *dst, int npixels)
{
int i;
double c, m, y, k, r, g, b;
for(i=0;i<npixels;i++) {
c = 1.0 - ((double)src[4*i+0])/255.0;
m = 1.0 - ((double)src[4*i+1])/255.0;
y = 1.0 - ((double)src[4*i+2])/255.0;
k = 1.0 - ((double)src[4*i+3])/255.0;
r = 1.0 - c*(1.0-k) - k;
g = 1.0 - m*(1.0-k) - k;
b = 1.0 - y*(1.0-k) - k;
if(r<0.0) r=0.0; if(r>1.0) r=1.0;
if(g<0.0) g=0.0; if(g>1.0) g=1.0;
if(b<0.0) b=0.0; if(b>1.0) b=1.0;
dst[3*i+0] = (JSAMPLE)(0.5+255.0*r);
dst[3*i+1] = (JSAMPLE)(0.5+255.0*g);
dst[3*i+2] = (JSAMPLE)(0.5+255.0*b);
}
}
IW_IMPL(int) iw_read_jpeg_file(struct iw_context *ctx, struct iw_iodescr *iodescr)
{
int retval=0;
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
int cinfo_valid=0;
int colorspace;
JDIMENSION rownum;
JSAMPLE *jsamprow;
int numchannels=0;
struct iw_image img;
struct iwjpegrcontext rctx;
JSAMPLE *tmprow = NULL;
int cmyk_flag = 0;
iw_zeromem(&img,sizeof(struct iw_image));
iw_zeromem(&cinfo,sizeof(struct jpeg_decompress_struct));
iw_zeromem(&jerr,sizeof(struct my_error_mgr));
iw_zeromem(&rctx,sizeof(struct iwjpegrcontext));
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
jerr.pub.output_message = my_output_message;
if (setjmp(jerr.setjmp_buffer)) {
char buffer[JMSG_LENGTH_MAX];
(*cinfo.err->format_message) ((j_common_ptr)&cinfo, buffer);
iw_set_errorf(ctx,"libjpeg reports read error: %s",buffer);
goto done;
}
jpeg_create_decompress(&cinfo);
cinfo_valid=1;
// Set up our custom source manager.
rctx.pub.init_source = my_init_source_fn;
rctx.pub.fill_input_buffer = my_fill_input_buffer_fn;
rctx.pub.skip_input_data = my_skip_input_data_fn;
rctx.pub.resync_to_restart = jpeg_resync_to_restart; // libjpeg default
rctx.pub.term_source = my_term_source_fn;
rctx.ctx = ctx;
rctx.iodescr = iodescr;
rctx.buffer_len = 32768;
rctx.buffer = iw_malloc(ctx, rctx.buffer_len);
if(!rctx.buffer) goto done;
rctx.exif_density_x = -1.0;
rctx.exif_density_y = -1.0;
cinfo.src = (struct jpeg_source_mgr*)&rctx;
// The lazy way. It would be more efficient to use
// jpeg_set_marker_processor(), instead of saving everything to memory.
// But libjpeg's marker processing functions have fairly complex
// requirements.
jpeg_save_markers(&cinfo, 0xe1, 65535);
jpeg_read_header(&cinfo, TRUE);
rctx.is_jfif = cinfo.saw_JFIF_marker;
iwjpeg_read_density(ctx,&img,&cinfo);
iwjpeg_read_saved_markers(&rctx,&cinfo);
jpeg_start_decompress(&cinfo);
colorspace=cinfo.out_color_space;
numchannels=cinfo.output_components;
// libjpeg will automatically convert YCbCr images to RGB, and YCCK images
// to CMYK. That leaves GRAYSCALE, RGB, and CMYK for us to handle.
// Note: cinfo.jpeg_color_space is the colorspace before conversion, and
// cinfo.out_color_space is the colorspace after conversion.
if(colorspace==JCS_GRAYSCALE && numchannels==1) {
img.imgtype = IW_IMGTYPE_GRAY;
img.native_grayscale = 1;
}
else if((colorspace==JCS_RGB) && numchannels==3) {
img.imgtype = IW_IMGTYPE_RGB;
}
else if((colorspace==JCS_CMYK) && numchannels==4) {
img.imgtype = IW_IMGTYPE_RGB;
cmyk_flag = 1;
}
else {
iw_set_error(ctx,"Unsupported type of JPEG");
goto done;
}
img.width = cinfo.output_width;
img.height = cinfo.output_height;
if(!iw_check_image_dimensions(ctx,img.width,img.height)) {
goto done;
}
img.bit_depth = 8;
img.bpr = iw_calc_bytesperrow(img.width,img.bit_depth*numchannels);
img.pixels = (iw_byte*)iw_malloc_large(ctx, img.bpr, img.height);
if(!img.pixels) {
goto done;
}
if(cmyk_flag) {
tmprow = iw_malloc(ctx,4*img.width);
if(!tmprow) goto done;
}
while(cinfo.output_scanline < cinfo.output_height) {
rownum=cinfo.output_scanline;
jsamprow = &img.pixels[img.bpr * rownum];
if(cmyk_flag) {
// read into tmprow, then convert and copy to img.pixels
jpeg_read_scanlines(&cinfo, &tmprow, 1);
convert_cmyk_to_rbg(ctx,tmprow,jsamprow,img.width);
}
else {
// read directly into img.pixels
jpeg_read_scanlines(&cinfo, &jsamprow, 1);
}
if(cinfo.output_scanline<=rownum) {
iw_set_error(ctx,"Error reading JPEG file");
goto done;
}
}
jpeg_finish_decompress(&cinfo);
handle_exif_density(&rctx, &img);
iw_set_input_image(ctx, &img);
// The contents of img no longer belong to us.
img.pixels = NULL;
if(rctx.exif_orientation>=2 && rctx.exif_orientation<=8) {
static const unsigned int exif_orient_to_transform[9] =
{ 0,0, 1,3,2,4,5,7,6 };
// An Exif marker indicated an unusual image orientation.
if(rctx.is_jfif) {
// The presence of a JFIF marker implies a particular orientation.
// If there's also an Exif marker that says something different,
// I'm not sure what we're supposed to do.
iw_warning(ctx,"JPEG image has an ambiguous orientation");
}
iw_reorient_image(ctx,exif_orient_to_transform[rctx.exif_orientation]);
}
retval=1;
done:
iw_free(ctx, img.pixels);
if(cinfo_valid) jpeg_destroy_decompress(&cinfo);
if(rctx.buffer) iw_free(ctx,rctx.buffer);
if(tmprow) iw_free(ctx,tmprow);
return retval;
}
////////////////////////////////////
struct iwjpegwcontext {
struct jpeg_destination_mgr pub; // This field must be first.
struct iw_context *ctx;
struct iw_iodescr *iodescr;
JOCTET *buffer;
size_t buffer_len;
};
static void iwjpg_set_density(struct iw_context *ctx,struct jpeg_compress_struct *cinfo,
const struct iw_image *img)
{
int pref_units;
if(img->density_code==IW_DENSITY_UNITS_UNKNOWN) {
cinfo->density_unit=0; // unknown units
cinfo->X_density = (UINT16)(0.5+img->density_x);
cinfo->Y_density = (UINT16)(0.5+img->density_y);
}
else if(img->density_code==IW_DENSITY_UNITS_PER_METER) {
pref_units = iw_get_value(ctx,IW_VAL_PREF_UNITS);
if(pref_units==IW_PREF_UNITS_METRIC) {
// If we think the caller prefers metric, use dots/cm.
cinfo->density_unit=2; // dots/cm
cinfo->X_density = (UINT16)(0.5+ img->density_x*0.01);
cinfo->Y_density = (UINT16)(0.5+ img->density_y*0.01);
}
else {
// Otherwise use dpi.
cinfo->density_unit=1; // dots/inch
cinfo->X_density = (UINT16)(0.5+ img->density_x*0.0254);
cinfo->Y_density = (UINT16)(0.5+ img->density_y*0.0254);
}
}
}
static void my_init_destination_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
// Configure the destination manager to use our buffer.
wctx->pub.next_output_byte = wctx->buffer;
wctx->pub.free_in_buffer = wctx->buffer_len;
}
static boolean my_empty_output_buffer_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
// Write out the entire buffer
(*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,
wctx->buffer,wctx->buffer_len);
// Change the data pointer and free-space indicator to reflect the
// data we wrote.
wctx->pub.next_output_byte = wctx->buffer;
wctx->pub.free_in_buffer = wctx->buffer_len;
return TRUE;
}
static void my_term_destination_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
size_t bytesleft;
bytesleft = wctx->buffer_len - wctx->pub.free_in_buffer;
if(bytesleft>0) {
(*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,
wctx->buffer,bytesleft);
}
}
IW_IMPL(int) iw_write_jpeg_file(struct iw_context *ctx, struct iw_iodescr *iodescr)
{
int retval=0;
struct jpeg_compress_struct cinfo;
struct my_error_mgr jerr;
J_COLOR_SPACE in_colortype; // Color type of the data we give to libjpeg
int jpeg_cmpts;
int compress_created = 0;
int compress_started = 0;
JSAMPROW *row_pointers = NULL;
int is_grayscale;
int j;
struct iw_image img;
int jpeg_quality;
int samp_factor_h, samp_factor_v;
int disable_subsampling = 0;
struct iwjpegwcontext wctx;
const char *optv;
int ret;
iw_zeromem(&cinfo,sizeof(struct jpeg_compress_struct));
iw_zeromem(&jerr,sizeof(struct my_error_mgr));
iw_zeromem(&wctx,sizeof(struct iwjpegwcontext));
iw_get_output_image(ctx,&img);
if(IW_IMGTYPE_HAS_ALPHA(img.imgtype)) {
iw_set_error(ctx,"Internal: Transparency not supported with JPEG output");
goto done;
}
if(img.bit_depth!=8) {
iw_set_errorf(ctx,"Internal: Precision %d not supported with JPEG output",img.bit_depth);
goto done;
}
is_grayscale = IW_IMGTYPE_IS_GRAY(img.imgtype);
if(is_grayscale) {
in_colortype=JCS_GRAYSCALE;
jpeg_cmpts=1;
}
else {
in_colortype=JCS_RGB;
jpeg_cmpts=3;
}
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (setjmp(jerr.setjmp_buffer)) {
char buffer[JMSG_LENGTH_MAX];
(*cinfo.err->format_message) ((j_common_ptr)&cinfo, buffer);
iw_set_errorf(ctx,"libjpeg reports write error: %s",buffer);
goto done;
}
jpeg_create_compress(&cinfo);
compress_created=1;
// Set up our custom destination manager.
wctx.pub.init_destination = my_init_destination_fn;
wctx.pub.empty_output_buffer = my_empty_output_buffer_fn;
wctx.pub.term_destination = my_term_destination_fn;
wctx.ctx = ctx;
wctx.iodescr = iodescr;
wctx.buffer_len = 32768;
wctx.buffer = iw_malloc(ctx,wctx.buffer_len);
if(!wctx.buffer) goto done;
// Our wctx is organized so it can double as a
// 'struct jpeg_destination_mgr'.
cinfo.dest = (struct jpeg_destination_mgr*)&wctx;
cinfo.image_width = img.width;
cinfo.image_height = img.height;
cinfo.input_components = jpeg_cmpts;
cinfo.in_color_space = in_colortype;
jpeg_set_defaults(&cinfo);
optv = iw_get_option(ctx, "jpeg:block");
if(optv) {
#if (JPEG_LIB_VERSION_MAJOR>=9 || \
(JPEG_LIB_VERSION_MAJOR==8 && JPEG_LIB_VERSION_MINOR>=3))
// Note: This might not work if DCT_SCALING_SUPPORTED was not defined when
// libjpeg was compiled, but that symbol is not normally exposed to
// applications.
cinfo.block_size = iw_parse_int(optv);
#else
iw_warning(ctx, "Setting block size is not supported by this version of libjpeg");
#endif
}
optv = iw_get_option(ctx, "jpeg:arith");
if(optv)
cinfo.arith_code = iw_parse_int(optv) ? TRUE : FALSE;
else
cinfo.arith_code = FALSE;
optv = iw_get_option(ctx, "jpeg:colortype");
if(optv) {
if(!strcmp(optv, "rgb")) {
if(in_colortype==JCS_RGB) {
jpeg_set_colorspace(&cinfo,JCS_RGB);
disable_subsampling = 1;
}
}
else if(!strcmp(optv, "rgb1")) {
if(in_colortype==JCS_RGB) {
#if JPEG_LIB_VERSION_MAJOR >= 9
cinfo.color_transform = JCT_SUBTRACT_GREEN;
#else
iw_warning(ctx, "Color type rgb1 is not supported by this version of libjpeg");
#endif
jpeg_set_colorspace(&cinfo,JCS_RGB);
disable_subsampling = 1;
}
}
}
optv = iw_get_option(ctx, "jpeg:bgycc");
if(optv && iw_parse_int(optv)) {
#if (JPEG_LIB_VERSION_MAJOR>9 || \
(JPEG_LIB_VERSION_MAJOR==9 && JPEG_LIB_VERSION_MINOR>=1))
jpeg_set_colorspace(&cinfo, JCS_BG_YCC);
#else
iw_warning(ctx, "Big gamut YCC is not supported by this version of libjpeg");
#endif
}
iwjpg_set_density(ctx,&cinfo,&img);
optv = iw_get_option(ctx, "jpeg:quality");
if(optv)
jpeg_quality = iw_parse_int(optv);
else
jpeg_quality = 0;
if(jpeg_quality>0) {
jpeg_set_quality(&cinfo,jpeg_quality,0);
}
if(jpeg_cmpts>1 && !disable_subsampling) {
samp_factor_h = 0;
samp_factor_v = 0;
// sampling-x and sampling-y are for backward compatibility, and should
// not be used.
optv = iw_get_option(ctx, "jpeg:sampling-x");
if(optv)
samp_factor_h = iw_parse_int(optv);
optv = iw_get_option(ctx, "jpeg:sampling-y");
if(optv)
samp_factor_v = iw_parse_int(optv);
optv = iw_get_option(ctx, "jpeg:sampling");
if(optv) {
double tmpsamp[2];
tmpsamp[0] = 1.0;
tmpsamp[1] = 1.0;
ret = iw_parse_number_list(optv, 2, tmpsamp);
samp_factor_h = iw_round_to_int(tmpsamp[0]);
if(ret==1) {
// If only one value was given, use it for both factors.
samp_factor_v = samp_factor_h;
}
else {
samp_factor_v = iw_round_to_int(tmpsamp[1]);
}
}
if(samp_factor_h>0) {
if(samp_factor_h>4) samp_factor_h=4;
cinfo.comp_info[0].h_samp_factor = samp_factor_h;
}
if(samp_factor_v>0) {
if(samp_factor_v>4) samp_factor_v=4;
cinfo.comp_info[0].v_samp_factor = samp_factor_v;
}
}
if(iw_get_value(ctx,IW_VAL_OUTPUT_INTERLACED)) {
jpeg_simple_progression(&cinfo);
}
row_pointers = (JSAMPROW*)iw_malloc(ctx, img.height * sizeof(JSAMPROW));
if(!row_pointers) goto done;
for(j=0;j<img.height;j++) {
row_pointers[j] = &img.pixels[j*img.bpr];
}
jpeg_start_compress(&cinfo, TRUE);
compress_started=1;
jpeg_write_scanlines(&cinfo, row_pointers, img.height);
retval=1;
done:
if(compress_started)
jpeg_finish_compress(&cinfo);
if(compress_created)
jpeg_destroy_compress(&cinfo);
if(row_pointers) iw_free(ctx,row_pointers);
if(wctx.buffer) iw_free(ctx,wctx.buffer);
return retval;
}
IW_IMPL(char*) iw_get_libjpeg_version_string(char *s, int s_len)
{
struct jpeg_error_mgr jerr;
const char *jv;
char *space_ptr;
jpeg_std_error(&jerr);
jv = jerr.jpeg_message_table[JMSG_VERSION];
iw_snprintf(s,s_len,"%s",jv);
// The version is probably a string like "8c 16-Jan-2011", containing
// both the version number and the release date. We only need the version
// number, so chop it off at the first space.
space_ptr = strchr(s,' ');
if(space_ptr) *space_ptr = '\0';
return s;
}
#endif // IW_SUPPORT_JPEG
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3369_0 |
crossvul-cpp_data_good_2720_0 | /*
* Copyright (c) 2016 Antonin Décimo, Jean-Raphaël Gaglione
*
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
/* \summary: Home Networking Control Protocol (HNCP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent);
void
hncp_print(netdissect_options *ndo,
const u_char *cp, u_int length)
{
ND_PRINT((ndo, "hncp (%d)", length));
hncp_print_rec(ndo, cp, length, 1);
}
/* RFC7787 */
#define DNCP_REQUEST_NETWORK_STATE 1
#define DNCP_REQUEST_NODE_STATE 2
#define DNCP_NODE_ENDPOINT 3
#define DNCP_NETWORK_STATE 4
#define DNCP_NODE_STATE 5
#define DNCP_PEER 8
#define DNCP_KEEP_ALIVE_INTERVAL 9
#define DNCP_TRUST_VERDICT 10
/* RFC7788 */
#define HNCP_HNCP_VERSION 32
#define HNCP_EXTERNAL_CONNECTION 33
#define HNCP_DELEGATED_PREFIX 34
#define HNCP_PREFIX_POLICY 43
#define HNCP_DHCPV4_DATA 37
#define HNCP_DHCPV6_DATA 38
#define HNCP_ASSIGNED_PREFIX 35
#define HNCP_NODE_ADDRESS 36
#define HNCP_DNS_DELEGATED_ZONE 39
#define HNCP_DOMAIN_NAME 40
#define HNCP_NODE_NAME 41
#define HNCP_MANAGED_PSK 42
/* See type_mask in hncp_print_rec below */
#define RANGE_DNCP_RESERVED 0x10000
#define RANGE_HNCP_UNASSIGNED 0x10001
#define RANGE_DNCP_PRIVATE_USE 0x10002
#define RANGE_DNCP_FUTURE_USE 0x10003
static const struct tok type_values[] = {
{ DNCP_REQUEST_NETWORK_STATE, "Request network state" },
{ DNCP_REQUEST_NODE_STATE, "Request node state" },
{ DNCP_NODE_ENDPOINT, "Node endpoint" },
{ DNCP_NETWORK_STATE, "Network state" },
{ DNCP_NODE_STATE, "Node state" },
{ DNCP_PEER, "Peer" },
{ DNCP_KEEP_ALIVE_INTERVAL, "Keep-alive interval" },
{ DNCP_TRUST_VERDICT, "Trust-Verdict" },
{ HNCP_HNCP_VERSION, "HNCP-Version" },
{ HNCP_EXTERNAL_CONNECTION, "External-Connection" },
{ HNCP_DELEGATED_PREFIX, "Delegated-Prefix" },
{ HNCP_PREFIX_POLICY, "Prefix-Policy" },
{ HNCP_DHCPV4_DATA, "DHCPv4-Data" },
{ HNCP_DHCPV6_DATA, "DHCPv6-Data" },
{ HNCP_ASSIGNED_PREFIX, "Assigned-Prefix" },
{ HNCP_NODE_ADDRESS, "Node-Address" },
{ HNCP_DNS_DELEGATED_ZONE, "DNS-Delegated-Zone" },
{ HNCP_DOMAIN_NAME, "Domain-Name" },
{ HNCP_NODE_NAME, "Node-Name" },
{ HNCP_MANAGED_PSK, "Managed-PSK" },
{ RANGE_DNCP_RESERVED, "Reserved" },
{ RANGE_HNCP_UNASSIGNED, "Unassigned" },
{ RANGE_DNCP_PRIVATE_USE, "Private use" },
{ RANGE_DNCP_FUTURE_USE, "Future use" },
{ 0, NULL}
};
#define DH4OPT_DNS_SERVERS 6 /* RFC2132 */
#define DH4OPT_NTP_SERVERS 42 /* RFC2132 */
#define DH4OPT_DOMAIN_SEARCH 119 /* RFC3397 */
static const struct tok dh4opt_str[] = {
{ DH4OPT_DNS_SERVERS, "DNS-server" },
{ DH4OPT_NTP_SERVERS, "NTP-server"},
{ DH4OPT_DOMAIN_SEARCH, "DNS-search" },
{ 0, NULL }
};
#define DH6OPT_DNS_SERVERS 23 /* RFC3646 */
#define DH6OPT_DOMAIN_LIST 24 /* RFC3646 */
#define DH6OPT_SNTP_SERVERS 31 /* RFC4075 */
static const struct tok dh6opt_str[] = {
{ DH6OPT_DNS_SERVERS, "DNS-server" },
{ DH6OPT_DOMAIN_LIST, "DNS-search-list" },
{ DH6OPT_SNTP_SERVERS, "SNTP-servers" },
{ 0, NULL }
};
/*
* For IPv4-mapped IPv6 addresses, length of the prefix that precedes
* the 4 bytes of IPv4 address at the end of the IPv6 address.
*/
#define IPV4_MAPPED_HEADING_LEN 12
/*
* Is an IPv6 address an IPv4-mapped address?
*/
static inline int
is_ipv4_mapped_address(const u_char *addr)
{
/* The value of the prefix */
static const u_char ipv4_mapped_heading[IPV4_MAPPED_HEADING_LEN] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
return memcmp(addr, ipv4_mapped_heading, IPV4_MAPPED_HEADING_LEN) == 0;
}
static const char *
format_nid(const u_char *data)
{
static char buf[4][sizeof("01:01:01:01")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x",
data[0], data[1], data[2], data[3]);
return buf[i];
}
static const char *
format_256(const u_char *data)
{
static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64,
EXTRACT_64BITS(data),
EXTRACT_64BITS(data + 8),
EXTRACT_64BITS(data + 16),
EXTRACT_64BITS(data + 24)
);
return buf[i];
}
static const char *
format_interval(const uint32_t n)
{
static char buf[4][sizeof("0000000.000s")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%u.%03us", n / 1000, n % 1000);
return buf[i];
}
static const char *
format_ip6addr(netdissect_options *ndo, const u_char *cp)
{
if (is_ipv4_mapped_address(cp))
return ipaddr_string(ndo, cp + IPV4_MAPPED_HEADING_LEN);
else
return ip6addr_string(ndo, cp);
}
static int
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length)
{
int plenbytes;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")];
if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 &&
is_ipv4_mapped_address(&prefix[1])) {
struct in_addr addr;
u_int plen;
plen = prefix[0]-96;
if (32 < plen)
return -1;
max_length -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN)
return -3;
memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen);
plenbytes += 1 + IPV4_MAPPED_HEADING_LEN;
} else {
plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf));
}
ND_PRINT((ndo, "%s", buf));
return plenbytes;
}
static int
print_dns_label(netdissect_options *ndo,
const u_char *cp, u_int max_length, int print)
{
u_int length = 0;
while (length < max_length) {
u_int lab_length = cp[length++];
if (lab_length == 0)
return (int)length;
if (length > 1 && print)
safeputchar(ndo, '.');
if (length+lab_length > max_length) {
if (print)
safeputs(ndo, cp+length, max_length-length);
break;
}
if (print)
safeputs(ndo, cp+length, lab_length);
length += lab_length;
}
if (print)
ND_PRINT((ndo, "[|DNS]"));
return -1;
}
static int
dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
if (i + 2 > length)
return -1;
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
if (i + 2 + optlen > length)
return -1;
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
static int
dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
if (i + 4 > length)
return -1;
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
if (i + 4 + optlen > length)
return -1;
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
/* Determine in-line mode */
static int
is_in_line(netdissect_options *ndo, int indent)
{
return indent - 1 >= ndo->ndo_vflag && ndo->ndo_vflag < 3;
}
static void
print_type_in_line(netdissect_options *ndo,
uint32_t type, int count, int indent, int *first_one)
{
if (count > 0) {
if (*first_one) {
*first_one = 0;
if (indent > 1) {
u_int t;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
} else {
ND_PRINT((ndo, " "));
}
} else {
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, "%s", tok2str(type_values, "Easter Egg", type)));
if (count > 1)
ND_PRINT((ndo, " (x%d)", count));
}
}
void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
const int in_line = is_in_line(ndo, indent);
int first_one = 1;
u_int i, t;
uint32_t last_type_mask = 0xffffffffU;
int last_type_count = -1;
const u_char *tlv, *value;
uint16_t type, bodylen;
uint32_t type_mask;
i = 0;
while (i < length) {
tlv = cp + i;
if (!in_line) {
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
}
ND_TCHECK2(*tlv, 4);
if (i + 4 > length)
goto invalid;
type = EXTRACT_16BITS(tlv);
bodylen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_TCHECK2(*value, bodylen);
if (i + bodylen + 4 > length)
goto invalid;
type_mask =
(type == 0) ? RANGE_DNCP_RESERVED:
(44 <= type && type <= 511) ? RANGE_HNCP_UNASSIGNED:
(768 <= type && type <= 1023) ? RANGE_DNCP_PRIVATE_USE:
RANGE_DNCP_FUTURE_USE;
if (type == 6 || type == 7)
type_mask = RANGE_DNCP_FUTURE_USE;
/* defined types */
{
t = 0;
while (1) {
u_int key = type_values[t++].v;
if (key > 0xffff)
break;
if (key == type) {
type_mask = type;
break;
}
}
}
if (in_line) {
if (last_type_mask == type_mask) {
last_type_count++;
} else {
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
last_type_mask = type_mask;
last_type_count = 1;
}
goto skip_multiline;
}
ND_PRINT((ndo,"%s", tok2str(type_values, "Easter Egg (42)", type_mask) ));
if (type_mask > 0xffff)
ND_PRINT((ndo,": type=%u", type ));
ND_PRINT((ndo," (%u)", bodylen + 4 ));
switch (type_mask) {
case DNCP_REQUEST_NETWORK_STATE: {
if (bodylen != 0)
ND_PRINT((ndo, " %s", istr));
}
break;
case DNCP_REQUEST_NODE_STATE: {
const char *node_identifier;
if (bodylen != 4) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
ND_PRINT((ndo, " NID: %s", node_identifier));
}
break;
case DNCP_NODE_ENDPOINT: {
const char *node_identifier;
uint32_t endpoint_identifier;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
endpoint_identifier = EXTRACT_32BITS(value + 4);
ND_PRINT((ndo, " NID: %s EPID: %08x",
node_identifier,
endpoint_identifier
));
}
break;
case DNCP_NETWORK_STATE: {
uint64_t hash;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
hash = EXTRACT_64BITS(value);
ND_PRINT((ndo, " hash: %016" PRIx64, hash));
}
break;
case DNCP_NODE_STATE: {
const char *node_identifier, *interval;
uint32_t sequence_number;
uint64_t hash;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
sequence_number = EXTRACT_32BITS(value + 4);
interval = format_interval(EXTRACT_32BITS(value + 8));
hash = EXTRACT_64BITS(value + 12);
ND_PRINT((ndo, " NID: %s seqno: %u %s hash: %016" PRIx64,
node_identifier,
sequence_number,
interval,
hash
));
hncp_print_rec(ndo, value+20, bodylen-20, indent+1);
}
break;
case DNCP_PEER: {
const char *peer_node_identifier;
uint32_t peer_endpoint_identifier, endpoint_identifier;
if (bodylen != 12) {
ND_PRINT((ndo, " %s", istr));
break;
}
peer_node_identifier = format_nid(value);
peer_endpoint_identifier = EXTRACT_32BITS(value + 4);
endpoint_identifier = EXTRACT_32BITS(value + 8);
ND_PRINT((ndo, " Peer-NID: %s Peer-EPID: %08x Local-EPID: %08x",
peer_node_identifier,
peer_endpoint_identifier,
endpoint_identifier
));
}
break;
case DNCP_KEEP_ALIVE_INTERVAL: {
uint32_t endpoint_identifier;
const char *interval;
if (bodylen < 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
interval = format_interval(EXTRACT_32BITS(value + 4));
ND_PRINT((ndo, " EPID: %08x Interval: %s",
endpoint_identifier,
interval
));
}
break;
case DNCP_TRUST_VERDICT: {
if (bodylen <= 36) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Verdict: %u Fingerprint: %s Common Name: ",
*value,
format_256(value + 4)));
safeputs(ndo, value + 36, bodylen - 36);
}
break;
case HNCP_HNCP_VERSION: {
uint16_t capabilities;
uint8_t M, P, H, L;
if (bodylen < 5) {
ND_PRINT((ndo, " %s", istr));
break;
}
capabilities = EXTRACT_16BITS(value + 2);
M = (uint8_t)((capabilities >> 12) & 0xf);
P = (uint8_t)((capabilities >> 8) & 0xf);
H = (uint8_t)((capabilities >> 4) & 0xf);
L = (uint8_t)(capabilities & 0xf);
ND_PRINT((ndo, " M: %u P: %u H: %u L: %u User-agent: ",
M, P, H, L
));
safeputs(ndo, value + 4, bodylen - 4);
}
break;
case HNCP_EXTERNAL_CONNECTION: {
/* Container TLV */
hncp_print_rec(ndo, value, bodylen, indent+1);
}
break;
case HNCP_DELEGATED_PREFIX: {
int l;
if (bodylen < 9 || bodylen < 9 + (value[8] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " VLSO: %s PLSO: %s Prefix: ",
format_interval(EXTRACT_32BITS(value)),
format_interval(EXTRACT_32BITS(value + 4))
));
l = print_prefix(ndo, value + 8, bodylen - 8);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
l += 8 + (-l & 3);
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_PREFIX_POLICY: {
uint8_t policy;
int l;
if (bodylen < 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
policy = value[0];
ND_PRINT((ndo, " type: "));
if (policy == 0) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Internet connectivity"));
} else if (policy >= 1 && policy <= 128) {
ND_PRINT((ndo, "Dest-Prefix: "));
l = print_prefix(ndo, value, bodylen);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
} else if (policy == 129) {
ND_PRINT((ndo, "DNS domain: "));
print_dns_label(ndo, value+1, bodylen-1, 1);
} else if (policy == 130) {
ND_PRINT((ndo, "Opaque UTF-8: "));
safeputs(ndo, value + 1, bodylen - 1);
} else if (policy == 131) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Restrictive assignment"));
} else if (policy >= 132) {
ND_PRINT((ndo, "Unknown (%u)", policy)); /* Reserved for future additions */
}
}
break;
case HNCP_DHCPV4_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv4_print(ndo, value, bodylen, indent+1) != 0)
goto invalid;
}
break;
case HNCP_DHCPV6_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv6_print(ndo, value, bodylen, indent+1) != 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
}
break;
case HNCP_ASSIGNED_PREFIX: {
uint8_t prty;
int l;
if (bodylen < 6 || bodylen < 6 + (value[5] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
prty = (uint8_t)(value[4] & 0xf);
ND_PRINT((ndo, " EPID: %08x Prty: %u",
EXTRACT_32BITS(value),
prty
));
ND_PRINT((ndo, " Prefix: "));
if ((l = print_prefix(ndo, value + 5, bodylen - 5)) < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
l += 5;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_NODE_ADDRESS: {
uint32_t endpoint_identifier;
const char *ip_address;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
ip_address = format_ip6addr(ndo, value + 4);
ND_PRINT((ndo, " EPID: %08x IP Address: %s",
endpoint_identifier,
ip_address
));
hncp_print_rec(ndo, value + 20, bodylen - 20, indent+1);
}
break;
case HNCP_DNS_DELEGATED_ZONE: {
const char *ip_address;
int len;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
ip_address = format_ip6addr(ndo, value);
ND_PRINT((ndo, " IP-Address: %s %c%c%c ",
ip_address,
(value[16] & 4) ? 'l' : '-',
(value[16] & 2) ? 'b' : '-',
(value[16] & 1) ? 's' : '-'
));
len = print_dns_label(ndo, value+17, bodylen-17, 1);
if (len < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
len += 17;
len += -len & 3;
if (bodylen >= len)
hncp_print_rec(ndo, value+len, bodylen-len, indent+1);
}
break;
case HNCP_DOMAIN_NAME: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Domain: "));
print_dns_label(ndo, value, bodylen, 1);
}
break;
case HNCP_NODE_NAME: {
u_int l;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
l = value[16];
if (bodylen < 17 + l) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " IP-Address: %s Name: ",
format_ip6addr(ndo, value)
));
if (l < 64) {
safeputchar(ndo, '"');
safeputs(ndo, value + 17, l);
safeputchar(ndo, '"');
} else {
ND_PRINT((ndo, "%s", istr));
}
l += 17;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_MANAGED_PSK: {
if (bodylen < 32) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " PSK: %s", format_256(value)));
hncp_print_rec(ndo, value + 32, bodylen - 32, indent+1);
}
break;
case RANGE_DNCP_RESERVED:
case RANGE_HNCP_UNASSIGNED:
case RANGE_DNCP_PRIVATE_USE:
case RANGE_DNCP_FUTURE_USE:
break;
}
skip_multiline:
i += 4 + bodylen + (-bodylen & 3);
}
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
return;
trunc:
ND_PRINT((ndo, "%s", "[|hncp]"));
return;
invalid:
ND_PRINT((ndo, "%s", istr));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2720_0 |
crossvul-cpp_data_bad_1370_0 | /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, Inc. 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.
*/
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_auth.c 352438 2019-09-17 09:46:42Z tuexen $");
#endif
#include <netinet/sctp_os.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctputil.h>
#include <netinet/sctp_indata.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_auth.h>
#ifdef SCTP_DEBUG
#define SCTP_AUTH_DEBUG (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH1)
#define SCTP_AUTH_DEBUG2 (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH2)
#endif /* SCTP_DEBUG */
void
sctp_clear_chunklist(sctp_auth_chklist_t *chklist)
{
memset(chklist, 0, sizeof(*chklist));
/* chklist->num_chunks = 0; */
}
sctp_auth_chklist_t *
sctp_alloc_chunklist(void)
{
sctp_auth_chklist_t *chklist;
SCTP_MALLOC(chklist, sctp_auth_chklist_t *, sizeof(*chklist),
SCTP_M_AUTH_CL);
if (chklist == NULL) {
SCTPDBG(SCTP_DEBUG_AUTH1, "sctp_alloc_chunklist: failed to get memory!\n");
} else {
sctp_clear_chunklist(chklist);
}
return (chklist);
}
void
sctp_free_chunklist(sctp_auth_chklist_t *list)
{
if (list != NULL)
SCTP_FREE(list, SCTP_M_AUTH_CL);
}
sctp_auth_chklist_t *
sctp_copy_chunklist(sctp_auth_chklist_t *list)
{
sctp_auth_chklist_t *new_list;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_chunklist();
if (new_list == NULL)
return (NULL);
/* copy it */
memcpy(new_list, list, sizeof(*new_list));
return (new_list);
}
/*
* add a chunk to the required chunks list
*/
int
sctp_auth_add_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
/* is chunk restricted? */
if ((chunk == SCTP_INITIATION) ||
(chunk == SCTP_INITIATION_ACK) ||
(chunk == SCTP_SHUTDOWN_COMPLETE) ||
(chunk == SCTP_AUTHENTICATION)) {
return (-1);
}
if (list->chunks[chunk] == 0) {
list->chunks[chunk] = 1;
list->num_chunks++;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: added chunk %u (0x%02x) to Auth list\n",
chunk, chunk);
}
return (0);
}
/*
* delete a chunk from the required chunks list
*/
int
sctp_auth_delete_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
if (list->chunks[chunk] == 1) {
list->chunks[chunk] = 0;
list->num_chunks--;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: deleted chunk %u (0x%02x) from Auth list\n",
chunk, chunk);
}
return (0);
}
size_t
sctp_auth_get_chklist_size(const sctp_auth_chklist_t *list)
{
if (list == NULL)
return (0);
else
return (list->num_chunks);
}
/*
* return the current number and list of required chunks caller must
* guarantee ptr has space for up to 256 bytes
*/
int
sctp_serialize_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, count = 0;
if (list == NULL)
return (0);
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
count++;
}
}
return (count);
}
int
sctp_pack_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, size = 0;
if (list == NULL)
return (0);
if (list->num_chunks <= 32) {
/* just list them, one byte each */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
size++;
}
}
} else {
int index, offset;
/* pack into a 32 byte bitfield */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
index = i / 8;
offset = i % 8;
ptr[index] |= (1 << offset);
}
}
size = 32;
}
return (size);
}
int
sctp_unpack_auth_chunks(const uint8_t *ptr, uint8_t num_chunks,
sctp_auth_chklist_t *list)
{
int i;
int size;
if (list == NULL)
return (0);
if (num_chunks <= 32) {
/* just pull them, one byte each */
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(*ptr++, list);
}
size = num_chunks;
} else {
int index, offset;
/* unpack from a 32 byte bitfield */
for (index = 0; index < 32; index++) {
for (offset = 0; offset < 8; offset++) {
if (ptr[index] & (1 << offset)) {
(void)sctp_auth_add_chunk((index * 8) + offset, list);
}
}
}
size = 32;
}
return (size);
}
/*
* allocate structure space for a key of length keylen
*/
sctp_key_t *
sctp_alloc_key(uint32_t keylen)
{
sctp_key_t *new_key;
SCTP_MALLOC(new_key, sctp_key_t *, sizeof(*new_key) + keylen,
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
return (new_key);
}
void
sctp_free_key(sctp_key_t *key)
{
if (key != NULL)
SCTP_FREE(key,SCTP_M_AUTH_KY);
}
void
sctp_print_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
void
sctp_show_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
static uint32_t
sctp_get_keylen(sctp_key_t *key)
{
if (key != NULL)
return (key->keylen);
else
return (0);
}
/*
* generate a new random key of length 'keylen'
*/
sctp_key_t *
sctp_generate_random_key(uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
SCTP_READ_RANDOM(new_key->key, keylen);
new_key->keylen = keylen;
return (new_key);
}
sctp_key_t *
sctp_set_key(uint8_t *key, uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
memcpy(new_key->key, key, keylen);
return (new_key);
}
/*-
* given two keys of variable size, compute which key is "larger/smaller"
* returns: 1 if key1 > key2
* -1 if key1 < key2
* 0 if key1 = key2
*/
static int
sctp_compare_key(sctp_key_t *key1, sctp_key_t *key2)
{
uint32_t maxlen;
uint32_t i;
uint32_t key1len, key2len;
uint8_t *key_1, *key_2;
uint8_t val1, val2;
/* sanity/length check */
key1len = sctp_get_keylen(key1);
key2len = sctp_get_keylen(key2);
if ((key1len == 0) && (key2len == 0))
return (0);
else if (key1len == 0)
return (-1);
else if (key2len == 0)
return (1);
if (key1len < key2len) {
maxlen = key2len;
} else {
maxlen = key1len;
}
key_1 = key1->key;
key_2 = key2->key;
/* check for numeric equality */
for (i = 0; i < maxlen; i++) {
/* left-pad with zeros */
val1 = (i < (maxlen - key1len)) ? 0 : *(key_1++);
val2 = (i < (maxlen - key2len)) ? 0 : *(key_2++);
if (val1 > val2) {
return (1);
} else if (val1 < val2) {
return (-1);
}
}
/* keys are equal value, so check lengths */
if (key1len == key2len)
return (0);
else if (key1len < key2len)
return (-1);
else
return (1);
}
/*
* generate the concatenated keying material based on the two keys and the
* shared key (if available). draft-ietf-tsvwg-auth specifies the specific
* order for concatenation
*/
sctp_key_t *
sctp_compute_hashkey(sctp_key_t *key1, sctp_key_t *key2, sctp_key_t *shared)
{
uint32_t keylen;
sctp_key_t *new_key;
uint8_t *key_ptr;
keylen = sctp_get_keylen(key1) + sctp_get_keylen(key2) +
sctp_get_keylen(shared);
if (keylen > 0) {
/* get space for the new key */
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
key_ptr = new_key->key;
} else {
/* all keys empty/null?! */
return (NULL);
}
/* concatenate the keys */
if (sctp_compare_key(key1, key2) <= 0) {
/* key is shared + key1 + key2 */
if (sctp_get_keylen(shared)) {
memcpy(key_ptr, shared->key, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key1)) {
memcpy(key_ptr, key1->key, key1->keylen);
key_ptr += key1->keylen;
}
if (sctp_get_keylen(key2)) {
memcpy(key_ptr, key2->key, key2->keylen);
}
} else {
/* key is shared + key2 + key1 */
if (sctp_get_keylen(shared)) {
memcpy(key_ptr, shared->key, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key2)) {
memcpy(key_ptr, key2->key, key2->keylen);
key_ptr += key2->keylen;
}
if (sctp_get_keylen(key1)) {
memcpy(key_ptr, key1->key, key1->keylen);
}
}
return (new_key);
}
sctp_sharedkey_t *
sctp_alloc_sharedkey(void)
{
sctp_sharedkey_t *new_key;
SCTP_MALLOC(new_key, sctp_sharedkey_t *, sizeof(*new_key),
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keyid = 0;
new_key->key = NULL;
new_key->refcount = 1;
new_key->deactivated = 0;
return (new_key);
}
void
sctp_free_sharedkey(sctp_sharedkey_t *skey)
{
if (skey == NULL)
return;
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&skey->refcount)) {
if (skey->key != NULL)
sctp_free_key(skey->key);
SCTP_FREE(skey, SCTP_M_AUTH_KY);
}
}
sctp_sharedkey_t *
sctp_find_sharedkey(struct sctp_keyhead *shared_keys, uint16_t key_id)
{
sctp_sharedkey_t *skey;
LIST_FOREACH(skey, shared_keys, next) {
if (skey->keyid == key_id)
return (skey);
}
return (NULL);
}
int
sctp_insert_sharedkey(struct sctp_keyhead *shared_keys,
sctp_sharedkey_t *new_skey)
{
sctp_sharedkey_t *skey;
if ((shared_keys == NULL) || (new_skey == NULL))
return (EINVAL);
/* insert into an empty list? */
if (LIST_EMPTY(shared_keys)) {
LIST_INSERT_HEAD(shared_keys, new_skey, next);
return (0);
}
/* insert into the existing list, ordered by key id */
LIST_FOREACH(skey, shared_keys, next) {
if (new_skey->keyid < skey->keyid) {
/* insert it before here */
LIST_INSERT_BEFORE(skey, new_skey, next);
return (0);
} else if (new_skey->keyid == skey->keyid) {
/* replace the existing key */
/* verify this key *can* be replaced */
if ((skey->deactivated) || (skey->refcount > 1)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"can't replace shared key id %u\n",
new_skey->keyid);
return (EBUSY);
}
SCTPDBG(SCTP_DEBUG_AUTH1,
"replacing shared key id %u\n",
new_skey->keyid);
LIST_INSERT_BEFORE(skey, new_skey, next);
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey);
return (0);
}
if (LIST_NEXT(skey, next) == NULL) {
/* belongs at the end of the list */
LIST_INSERT_AFTER(skey, new_skey, next);
return (0);
}
}
/* shouldn't reach here */
return (EINVAL);
}
void
sctp_auth_key_acquire(struct sctp_tcb *stcb, uint16_t key_id)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* bump the ref count */
if (skey) {
atomic_add_int(&skey->refcount, 1);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount acquire to %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
}
}
void
sctp_auth_key_release(struct sctp_tcb *stcb, uint16_t key_id, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* decrement the ref count */
if (skey) {
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount release to %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
/* see if a notification should be generated */
if ((skey->refcount <= 2) && (skey->deactivated)) {
/* notify ULP that key is no longer used */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb,
key_id, 0, so_locked);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u no longer used, %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
}
sctp_free_sharedkey(skey);
}
}
static sctp_sharedkey_t *
sctp_copy_sharedkey(const sctp_sharedkey_t *skey)
{
sctp_sharedkey_t *new_skey;
if (skey == NULL)
return (NULL);
new_skey = sctp_alloc_sharedkey();
if (new_skey == NULL)
return (NULL);
if (skey->key != NULL)
new_skey->key = sctp_set_key(skey->key->key, skey->key->keylen);
else
new_skey->key = NULL;
new_skey->keyid = skey->keyid;
return (new_skey);
}
int
sctp_copy_skeylist(const struct sctp_keyhead *src, struct sctp_keyhead *dest)
{
sctp_sharedkey_t *skey, *new_skey;
int count = 0;
if ((src == NULL) || (dest == NULL))
return (0);
LIST_FOREACH(skey, src, next) {
new_skey = sctp_copy_sharedkey(skey);
if (new_skey != NULL) {
if (sctp_insert_sharedkey(dest, new_skey)) {
sctp_free_sharedkey(new_skey);
} else {
count++;
}
}
}
return (count);
}
sctp_hmaclist_t *
sctp_alloc_hmaclist(uint16_t num_hmacs)
{
sctp_hmaclist_t *new_list;
int alloc_size;
alloc_size = sizeof(*new_list) + num_hmacs * sizeof(new_list->hmac[0]);
SCTP_MALLOC(new_list, sctp_hmaclist_t *, alloc_size,
SCTP_M_AUTH_HL);
if (new_list == NULL) {
/* out of memory */
return (NULL);
}
new_list->max_algo = num_hmacs;
new_list->num_algo = 0;
return (new_list);
}
void
sctp_free_hmaclist(sctp_hmaclist_t *list)
{
if (list != NULL) {
SCTP_FREE(list,SCTP_M_AUTH_HL);
list = NULL;
}
}
int
sctp_auth_add_hmacid(sctp_hmaclist_t *list, uint16_t hmac_id)
{
int i;
if (list == NULL)
return (-1);
if (list->num_algo == list->max_algo) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: HMAC id list full, ignoring add %u\n", hmac_id);
return (-1);
}
#if defined(SCTP_SUPPORT_HMAC_SHA256)
if ((hmac_id != SCTP_AUTH_HMAC_ID_SHA1) &&
(hmac_id != SCTP_AUTH_HMAC_ID_SHA256)) {
#else
if (hmac_id != SCTP_AUTH_HMAC_ID_SHA1) {
#endif
return (-1);
}
/* Now is it already in the list */
for (i = 0; i < list->num_algo; i++) {
if (list->hmac[i] == hmac_id) {
/* already in list */
return (-1);
}
}
SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: add HMAC id %u to list\n", hmac_id);
list->hmac[list->num_algo++] = hmac_id;
return (0);
}
sctp_hmaclist_t *
sctp_copy_hmaclist(sctp_hmaclist_t *list)
{
sctp_hmaclist_t *new_list;
int i;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_hmaclist(list->max_algo);
if (new_list == NULL)
return (NULL);
/* copy it */
new_list->max_algo = list->max_algo;
new_list->num_algo = list->num_algo;
for (i = 0; i < list->num_algo; i++)
new_list->hmac[i] = list->hmac[i];
return (new_list);
}
sctp_hmaclist_t *
sctp_default_supported_hmaclist(void)
{
sctp_hmaclist_t *new_list;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
new_list = sctp_alloc_hmaclist(2);
#else
new_list = sctp_alloc_hmaclist(1);
#endif
if (new_list == NULL)
return (NULL);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
/* We prefer SHA256, so list it first */
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA256);
#endif
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA1);
return (new_list);
}
/*-
* HMAC algos are listed in priority/preference order
* find the best HMAC id to use for the peer based on local support
*/
uint16_t
sctp_negotiate_hmacid(sctp_hmaclist_t *peer, sctp_hmaclist_t *local)
{
int i, j;
if ((local == NULL) || (peer == NULL))
return (SCTP_AUTH_HMAC_ID_RSVD);
for (i = 0; i < peer->num_algo; i++) {
for (j = 0; j < local->num_algo; j++) {
if (peer->hmac[i] == local->hmac[j]) {
/* found the "best" one */
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: negotiated peer HMAC id %u\n",
peer->hmac[i]);
return (peer->hmac[i]);
}
}
}
/* didn't find one! */
return (SCTP_AUTH_HMAC_ID_RSVD);
}
/*-
* serialize the HMAC algo list and return space used
* caller must guarantee ptr has appropriate space
*/
int
sctp_serialize_hmaclist(sctp_hmaclist_t *list, uint8_t *ptr)
{
int i;
uint16_t hmac_id;
if (list == NULL)
return (0);
for (i = 0; i < list->num_algo; i++) {
hmac_id = htons(list->hmac[i]);
memcpy(ptr, &hmac_id, sizeof(hmac_id));
ptr += sizeof(hmac_id);
}
return (list->num_algo * sizeof(hmac_id));
}
int
sctp_verify_hmac_param (struct sctp_auth_hmac_algo *hmacs, uint32_t num_hmacs)
{
uint32_t i;
for (i = 0; i < num_hmacs; i++) {
if (ntohs(hmacs->hmac_ids[i]) == SCTP_AUTH_HMAC_ID_SHA1) {
return (0);
}
}
return (-1);
}
sctp_authinfo_t *
sctp_alloc_authinfo(void)
{
sctp_authinfo_t *new_authinfo;
SCTP_MALLOC(new_authinfo, sctp_authinfo_t *, sizeof(*new_authinfo),
SCTP_M_AUTH_IF);
if (new_authinfo == NULL) {
/* out of memory */
return (NULL);
}
memset(new_authinfo, 0, sizeof(*new_authinfo));
return (new_authinfo);
}
void
sctp_free_authinfo(sctp_authinfo_t *authinfo)
{
if (authinfo == NULL)
return;
if (authinfo->random != NULL)
sctp_free_key(authinfo->random);
if (authinfo->peer_random != NULL)
sctp_free_key(authinfo->peer_random);
if (authinfo->assoc_key != NULL)
sctp_free_key(authinfo->assoc_key);
if (authinfo->recv_key != NULL)
sctp_free_key(authinfo->recv_key);
/* We are NOT dynamically allocating authinfo's right now... */
/* SCTP_FREE(authinfo, SCTP_M_AUTH_??); */
}
uint32_t
sctp_get_auth_chunk_len(uint16_t hmac_algo)
{
int size;
size = sizeof(struct sctp_auth_chunk) + sctp_get_hmac_digest_len(hmac_algo);
return (SCTP_SIZE32(size));
}
uint32_t
sctp_get_hmac_digest_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (SCTP_AUTH_DIGEST_LEN_SHA1);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (SCTP_AUTH_DIGEST_LEN_SHA256);
#endif
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
static inline int
sctp_get_hmac_block_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (64);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (64);
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
#if defined(__Userspace__)
/* __Userspace__ SHA1_Init is defined in libcrypto.a (libssl-dev on Ubuntu) */
#endif
static void
sctp_hmac_init(uint16_t hmac_algo, sctp_hash_context_t *ctx)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_INIT(&ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_INIT(&ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_update(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *text, uint32_t textlen)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_UPDATE(&ctx->sha1, text, textlen);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_UPDATE(&ctx->sha256, text, textlen);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_final(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *digest)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_FINAL(digest, &ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_FINAL(digest, &ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
/*-
* Keyed-Hashing for Message Authentication: FIPS 198 (RFC 2104)
*
* Compute the HMAC digest using the desired hash key, text, and HMAC
* algorithm. Resulting digest is placed in 'digest' and digest length
* is returned, if the HMAC was performed.
*
* WARNING: it is up to the caller to supply sufficient space to hold the
* resultant digest.
*/
uint32_t
sctp_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
uint8_t *text, uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (text == NULL) ||
(textlen == 0) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
memset(ipad, 0, blocklen);
memset(opad, 0, blocklen);
memcpy(ipad, key, keylen);
memcpy(opad, key, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, text, textlen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/* mbuf version */
uint32_t
sctp_hmac_m(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
struct mbuf *m, uint32_t m_offset, uint8_t *digest, uint32_t trailer)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
struct mbuf *m_tmp;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
memset(ipad, 0, blocklen);
memset(opad, 0, blocklen);
memcpy(ipad, key, keylen);
memcpy(opad, key, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
/* find the correct starting mbuf and offset (get start of text) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain for the text */
while (m_tmp != NULL) {
if ((SCTP_BUF_NEXT(m_tmp) == NULL) && trailer) {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - (trailer+m_offset));
} else {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - m_offset);
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/*
* computes the requested HMAC using a key struct (which may be modified if
* the keylen exceeds the HMAC block len).
*/
uint32_t
sctp_compute_hmac(uint16_t hmac_algo, sctp_key_t *key, uint8_t *text,
uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (text == NULL) || (textlen == 0) ||
(digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
memcpy(key->key, temp, key->keylen);
}
return (sctp_hmac(hmac_algo, key->key, key->keylen, text, textlen,
digest));
}
/* mbuf version */
uint32_t
sctp_compute_hmac_m(uint16_t hmac_algo, sctp_key_t *key, struct mbuf *m,
uint32_t m_offset, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
memcpy(key->key, temp, key->keylen);
}
return (sctp_hmac_m(hmac_algo, key->key, key->keylen, m, m_offset, digest, 0));
}
int
sctp_auth_is_supported_hmac(sctp_hmaclist_t *list, uint16_t id)
{
int i;
if ((list == NULL) || (id == SCTP_AUTH_HMAC_ID_RSVD))
return (0);
for (i = 0; i < list->num_algo; i++)
if (list->hmac[i] == id)
return (1);
/* not in the list */
return (0);
}
/*-
* clear any cached key(s) if they match the given key id on an association.
* the cached key(s) will be recomputed and re-cached at next use.
* ASSUMES TCB_LOCK is already held
*/
void
sctp_clear_cachedkeys(struct sctp_tcb *stcb, uint16_t keyid)
{
if (stcb == NULL)
return;
if (keyid == stcb->asoc.authinfo.assoc_keyid) {
sctp_free_key(stcb->asoc.authinfo.assoc_key);
stcb->asoc.authinfo.assoc_key = NULL;
}
if (keyid == stcb->asoc.authinfo.recv_keyid) {
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key = NULL;
}
}
/*-
* clear any cached key(s) if they match the given key id for all assocs on
* an endpoint.
* ASSUMES INP_WLOCK is already held
*/
void
sctp_clear_cachedkeys_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
struct sctp_tcb *stcb;
if (inp == NULL)
return;
/* clear the cached keys on all assocs on this instance */
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
SCTP_TCB_LOCK(stcb);
sctp_clear_cachedkeys(stcb, keyid);
SCTP_TCB_UNLOCK(stcb);
}
}
/*-
* delete a shared key from an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_delete_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount > 1)
return (-1);
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys(stcb, keyid);
return (0);
}
/*-
* deletes a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_delete_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys_ep(inp, keyid);
return (0);
}
/*-
* set the active key on an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_auth_setactivekey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey = NULL;
/* find the key on the assoc */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
if ((skey->deactivated) && (skey->refcount > 1)) {
/* can't reactivate a deactivated key with other refcounts */
return (-1);
}
/* set the (new) active key */
stcb->asoc.authinfo.active_keyid = keyid;
/* reset the deactivated flag */
skey->deactivated = 0;
return (0);
}
/*-
* set the active key on an endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_auth_setactivekey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
/* find the key */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
inp->sctp_ep.default_keyid = keyid;
return (0);
}
/*-
* deactivates a shared key from the association
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount == 1) {
/* no other users, send a notification for this key */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb, keyid, 0,
SCTP_SO_LOCKED);
}
/* mark the key as deactivated */
skey->deactivated = 1;
return (0);
}
/*-
* deactivates a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
return (0);
}
/*
* get local authentication parameters from cookie (from INIT-ACK)
*/
void
sctp_auth_get_cookie_params(struct sctp_tcb *stcb, struct mbuf *m,
uint32_t offset, uint32_t length)
{
struct sctp_paramhdr *phdr, tmp_param;
uint16_t plen, ptype;
uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_random *p_random = NULL;
uint16_t random_len = 0;
uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs = NULL;
uint16_t hmacs_len = 0;
uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_chunk_list *chunks = NULL;
uint16_t num_chunks = 0;
sctp_key_t *new_key;
uint32_t keylen;
/* convert to upper bound */
length += offset;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset,
sizeof(struct sctp_paramhdr), (uint8_t *)&tmp_param);
while (phdr != NULL) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if ((plen == 0) || (offset + plen > length))
break;
if (ptype == SCTP_RANDOM) {
if (plen > sizeof(random_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)random_store, plen);
if (phdr == NULL)
return;
/* save the random and length for the key */
p_random = (struct sctp_auth_random *)phdr;
random_len = plen - sizeof(*p_random);
} else if (ptype == SCTP_HMAC_LIST) {
uint16_t num_hmacs;
uint16_t i;
if (plen > sizeof(hmacs_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)hmacs_store, plen);
if (phdr == NULL)
return;
/* save the hmacs list and num for the key */
hmacs = (struct sctp_auth_hmac_algo *)phdr;
hmacs_len = plen - sizeof(*hmacs);
num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
if (stcb->asoc.local_hmacs != NULL)
sctp_free_hmaclist(stcb->asoc.local_hmacs);
stcb->asoc.local_hmacs = sctp_alloc_hmaclist(num_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
for (i = 0; i < num_hmacs; i++) {
(void)sctp_auth_add_hmacid(stcb->asoc.local_hmacs,
ntohs(hmacs->hmac_ids[i]));
}
}
} else if (ptype == SCTP_CHUNK_LIST) {
int i;
if (plen > sizeof(chunks_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store, plen);
if (phdr == NULL)
return;
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
/* save chunks list and num for the key */
if (stcb->asoc.local_auth_chunks != NULL)
sctp_clear_chunklist(stcb->asoc.local_auth_chunks);
else
stcb->asoc.local_auth_chunks = sctp_alloc_chunklist();
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(chunks->chunk_types[i],
stcb->asoc.local_auth_chunks);
}
}
/* get next parameter */
offset += SCTP_SIZE32(plen);
if (offset + sizeof(struct sctp_paramhdr) > length)
break;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, sizeof(struct sctp_paramhdr),
(uint8_t *)&tmp_param);
}
/* concatenate the full random key */
keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
if (chunks != NULL) {
keylen += sizeof(*chunks) + num_chunks;
}
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
/* copy in the RANDOM */
if (p_random != NULL) {
keylen = sizeof(*p_random) + random_len;
memcpy(new_key->key, p_random, keylen);
} else {
keylen = 0;
}
/* append in the AUTH chunks */
if (chunks != NULL) {
memcpy(new_key->key + keylen, chunks,
sizeof(*chunks) + num_chunks);
keylen += sizeof(*chunks) + num_chunks;
}
/* append in the HMACs */
if (hmacs != NULL) {
memcpy(new_key->key + keylen, hmacs,
sizeof(*hmacs) + hmacs_len);
}
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
/* negotiate what HMAC to use for the peer */
stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
stcb->asoc.local_hmacs);
/* copy defaults from the endpoint */
/* FIX ME: put in cookie? */
stcb->asoc.authinfo.active_keyid = stcb->sctp_ep->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&stcb->sctp_ep->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
}
/*
* compute and fill in the HMAC digest for a packet
*/
void
sctp_fill_hmac_digest_m(struct mbuf *m, uint32_t auth_offset,
struct sctp_auth_chunk *auth, struct sctp_tcb *stcb, uint16_t keyid)
{
uint32_t digestlen;
sctp_sharedkey_t *skey;
sctp_key_t *key;
if ((stcb == NULL) || (auth == NULL))
return;
/* zero the digest + chunk padding */
digestlen = sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
memset(auth->hmac, 0, SCTP_SIZE32(digestlen));
/* is the desired key cached? */
if ((keyid != stcb->asoc.authinfo.assoc_keyid) ||
(stcb->asoc.authinfo.assoc_key == NULL)) {
if (stcb->asoc.authinfo.assoc_key != NULL) {
/* free the old cached key */
sctp_free_key(stcb->asoc.authinfo.assoc_key);
}
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
/* the only way skey is NULL is if null key id 0 is used */
if (skey != NULL)
key = skey->key;
else
key = NULL;
/* compute a new assoc key and cache it */
stcb->asoc.authinfo.assoc_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, key);
stcb->asoc.authinfo.assoc_keyid = keyid;
SCTPDBG(SCTP_DEBUG_AUTH1, "caching key id %u\n",
stcb->asoc.authinfo.assoc_keyid);
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.assoc_key,
"Assoc Key");
#endif
}
/* set in the active key id */
auth->shared_key_id = htons(keyid);
/* compute and fill in the digest */
(void)sctp_compute_hmac_m(stcb->asoc.peer_hmac_id, stcb->asoc.authinfo.assoc_key,
m, auth_offset, auth->hmac);
}
static void
sctp_zero_m(struct mbuf *m, uint32_t m_offset, uint32_t size)
{
struct mbuf *m_tmp;
uint8_t *data;
/* sanity check */
if (m == NULL)
return;
/* find the correct starting mbuf and offset (get start position) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain */
while ((m_tmp != NULL) && (size > 0)) {
data = mtod(m_tmp, uint8_t *) + m_offset;
if (size > (uint32_t)(SCTP_BUF_LEN(m_tmp) - m_offset)) {
memset(data, 0, SCTP_BUF_LEN(m_tmp) - m_offset);
size -= SCTP_BUF_LEN(m_tmp) - m_offset;
} else {
memset(data, 0, size);
size = 0;
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
}
/*-
* process the incoming Authentication chunk
* return codes:
* -1 on any authentication error
* 0 on authentication verification
*/
int
sctp_handle_auth(struct sctp_tcb *stcb, struct sctp_auth_chunk *auth,
struct mbuf *m, uint32_t offset)
{
uint16_t chunklen;
uint16_t shared_key_id;
uint16_t hmac_id;
sctp_sharedkey_t *skey;
uint32_t digestlen;
uint8_t digest[SCTP_AUTH_DIGEST_LEN_MAX];
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
/* auth is checked for NULL by caller */
chunklen = ntohs(auth->ch.chunk_length);
if (chunklen < sizeof(*auth)) {
SCTP_STAT_INCR(sctps_recvauthfailed);
return (-1);
}
SCTP_STAT_INCR(sctps_recvauth);
/* get the auth params */
shared_key_id = ntohs(auth->shared_key_id);
hmac_id = ntohs(auth->hmac_id);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP AUTH Chunk: shared key %u, HMAC id %u\n",
shared_key_id, hmac_id);
/* is the indicated HMAC supported? */
if (!sctp_auth_is_supported_hmac(stcb->asoc.local_hmacs, hmac_id)) {
struct mbuf *op_err;
struct sctp_error_auth_invalid_hmac *cause;
SCTP_STAT_INCR(sctps_recvivalhmacid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unsupported HMAC id %u\n",
hmac_id);
/*
* report this in an Error Chunk: Unsupported HMAC
* Identifier
*/
op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_error_auth_invalid_hmac),
0, M_NOWAIT, 1, MT_HEADER);
if (op_err != NULL) {
/* pre-reserve some space */
SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
/* fill in the error */
cause = mtod(op_err, struct sctp_error_auth_invalid_hmac *);
cause->cause.code = htons(SCTP_CAUSE_UNSUPPORTED_HMACID);
cause->cause.length = htons(sizeof(struct sctp_error_auth_invalid_hmac));
cause->hmac_id = ntohs(hmac_id);
SCTP_BUF_LEN(op_err) = sizeof(struct sctp_error_auth_invalid_hmac);
/* queue it */
sctp_queue_op_err(stcb, op_err);
}
return (-1);
}
/* get the indicated shared key, if available */
if ((stcb->asoc.authinfo.recv_key == NULL) ||
(stcb->asoc.authinfo.recv_keyid != shared_key_id)) {
/* find the shared key on the assoc first */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys,
shared_key_id);
/* if the shared key isn't found, discard the chunk */
if (skey == NULL) {
SCTP_STAT_INCR(sctps_recvivalkeyid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unknown key id %u\n",
shared_key_id);
return (-1);
}
/* generate a notification if this is a new key id */
if (stcb->asoc.authinfo.recv_keyid != shared_key_id)
/*
* sctp_ulp_notify(SCTP_NOTIFY_AUTH_NEW_KEY, stcb,
* shared_key_id, (void
* *)stcb->asoc.authinfo.recv_keyid);
*/
sctp_notify_authentication(stcb, SCTP_AUTH_NEW_KEY,
shared_key_id, stcb->asoc.authinfo.recv_keyid,
SCTP_SO_NOT_LOCKED);
/* compute a new recv assoc key and cache it */
if (stcb->asoc.authinfo.recv_key != NULL)
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, skey->key);
stcb->asoc.authinfo.recv_keyid = shared_key_id;
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.recv_key, "Recv Key");
#endif
}
/* validate the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_id);
if (chunklen < (sizeof(*auth) + digestlen)) {
/* invalid digest length */
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: chunk too short for HMAC\n");
return (-1);
}
/* save a copy of the digest, zero the pseudo header, and validate */
memcpy(digest, auth->hmac, digestlen);
sctp_zero_m(m, offset + sizeof(*auth), SCTP_SIZE32(digestlen));
(void)sctp_compute_hmac_m(hmac_id, stcb->asoc.authinfo.recv_key,
m, offset, computed_digest);
#if defined(__Userspace__)
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
return (0);
#endif
#endif
/* compare the computed digest with the one in the AUTH chunk */
if (timingsafe_bcmp(digest, computed_digest, digestlen) != 0) {
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: HMAC digest check failed\n");
return (-1);
}
return (0);
}
/*
* Generate NOTIFICATION
*/
void
sctp_notify_authentication(struct sctp_tcb *stcb, uint32_t indication,
uint16_t keyid, uint16_t alt_keyid, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
struct mbuf *m_notify;
struct sctp_authkey_event *auth;
struct sctp_queued_to_read *control;
if ((stcb == NULL) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)
) {
/* If the socket is gone we are out of here */
return;
}
if (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_AUTHEVNT))
/* event not enabled */
return;
m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_authkey_event),
0, M_NOWAIT, 1, MT_HEADER);
if (m_notify == NULL)
/* no space left */
return;
SCTP_BUF_LEN(m_notify) = 0;
auth = mtod(m_notify, struct sctp_authkey_event *);
memset(auth, 0, sizeof(struct sctp_authkey_event));
auth->auth_type = SCTP_AUTHENTICATION_EVENT;
auth->auth_flags = 0;
auth->auth_length = sizeof(*auth);
auth->auth_keynumber = keyid;
auth->auth_altkeynumber = alt_keyid;
auth->auth_indication = indication;
auth->auth_assoc_id = sctp_get_associd(stcb);
SCTP_BUF_LEN(m_notify) = sizeof(*auth);
SCTP_BUF_NEXT(m_notify) = NULL;
/* append to socket */
control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
0, 0, stcb->asoc.context, 0, 0, 0, m_notify);
if (control == NULL) {
/* no memory */
sctp_m_freem(m_notify);
return;
}
control->length = SCTP_BUF_LEN(m_notify);
control->spec_flags = M_NOTIFICATION;
/* not that we need this */
control->tail_mbuf = m_notify;
sctp_add_to_readq(stcb->sctp_ep, stcb, control,
&stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
}
/*-
* validates the AUTHentication related parameters in an INIT/INIT-ACK
* Note: currently only used for INIT as INIT-ACK is handled inline
* with sctp_load_addresses_from_init()
*/
int
sctp_validate_init_auth_params(struct mbuf *m, int offset, int limit)
{
struct sctp_paramhdr *phdr, param_buf;
uint16_t ptype, plen;
int peer_supports_asconf = 0;
int peer_supports_auth = 0;
int got_random = 0, got_hmacs = 0, got_chklist = 0;
uint8_t saw_asconf = 0;
uint8_t saw_asconf_ack = 0;
/* go through each of the params. */
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if (offset + plen > limit) {
break;
}
if (plen < sizeof(struct sctp_paramhdr)) {
break;
}
if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
/* A supported extension chunk */
struct sctp_supported_chunk_types_param *pr_supported;
uint8_t local_store[SCTP_SMALL_CHUNK_STORE];
int num_ent, i;
if (plen > sizeof(local_store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&local_store,
plen);
if (phdr == NULL) {
return (-1);
}
pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
num_ent = plen - sizeof(struct sctp_paramhdr);
for (i = 0; i < num_ent; i++) {
switch (pr_supported->chunk_types[i]) {
case SCTP_ASCONF:
case SCTP_ASCONF_ACK:
peer_supports_asconf = 1;
break;
default:
/* one we don't care about */
break;
}
}
} else if (ptype == SCTP_RANDOM) {
/* enforce the random length */
if (plen != (sizeof(struct sctp_auth_random) +
SCTP_AUTH_RANDOM_SIZE_REQUIRED)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid RANDOM len\n");
return (-1);
}
got_random = 1;
} else if (ptype == SCTP_HMAC_LIST) {
struct sctp_auth_hmac_algo *hmacs;
uint8_t store[SCTP_PARAM_BUFFER_SIZE];
int num_hmacs;
if (plen > sizeof(store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)store,
plen);
if (phdr == NULL) {
return (-1);
}
hmacs = (struct sctp_auth_hmac_algo *)phdr;
num_hmacs = (plen - sizeof(*hmacs)) / sizeof(hmacs->hmac_ids[0]);
/* validate the hmac list */
if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid HMAC param\n");
return (-1);
}
got_hmacs = 1;
} else if (ptype == SCTP_CHUNK_LIST) {
struct sctp_auth_chunk_list *chunks;
uint8_t chunks_store[SCTP_SMALL_CHUNK_STORE];
int i, num_chunks;
if (plen > sizeof(chunks_store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store,
plen);
if (phdr == NULL) {
return (-1);
}
/*-
* Flip through the list and mark that the
* peer supports asconf/asconf_ack.
*/
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
for (i = 0; i < num_chunks; i++) {
/* record asconf/asconf-ack if listed */
if (chunks->chunk_types[i] == SCTP_ASCONF)
saw_asconf = 1;
if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
saw_asconf_ack = 1;
}
if (num_chunks)
got_chklist = 1;
}
offset += SCTP_SIZE32(plen);
if (offset >= limit) {
break;
}
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
/* validate authentication required parameters */
if (got_random && got_hmacs) {
peer_supports_auth = 1;
} else {
peer_supports_auth = 0;
}
if (!peer_supports_auth && got_chklist) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer sent chunk list w/o AUTH\n");
return (-1);
}
if (peer_supports_asconf && !peer_supports_auth) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer supports ASCONF but not AUTH\n");
return (-1);
} else if ((peer_supports_asconf) && (peer_supports_auth) &&
((saw_asconf == 0) || (saw_asconf_ack == 0))) {
return (-2);
}
return (0);
}
void
sctp_initialize_auth_params(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
uint16_t chunks_len = 0;
uint16_t hmacs_len = 0;
uint16_t random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
sctp_key_t *new_key;
uint16_t keylen;
/* initialize hmac list from endpoint */
stcb->asoc.local_hmacs = sctp_copy_hmaclist(inp->sctp_ep.local_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
hmacs_len = stcb->asoc.local_hmacs->num_algo *
sizeof(stcb->asoc.local_hmacs->hmac[0]);
}
/* initialize auth chunks list from endpoint */
stcb->asoc.local_auth_chunks =
sctp_copy_chunklist(inp->sctp_ep.local_auth_chunks);
if (stcb->asoc.local_auth_chunks != NULL) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
chunks_len++;
}
}
/* copy defaults from the endpoint */
stcb->asoc.authinfo.active_keyid = inp->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&inp->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
/* now set the concatenated key (random + chunks + hmacs) */
/* key includes parameter headers */
keylen = (3 * sizeof(struct sctp_paramhdr)) + random_len + chunks_len +
hmacs_len;
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
struct sctp_paramhdr *ph;
int plen;
/* generate and copy in the RANDOM */
ph = (struct sctp_paramhdr *)new_key->key;
ph->param_type = htons(SCTP_RANDOM);
plen = sizeof(*ph) + random_len;
ph->param_length = htons(plen);
SCTP_READ_RANDOM(new_key->key + sizeof(*ph), random_len);
keylen = plen;
/* append in the AUTH chunks */
/* NOTE: currently we always have chunks to list */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_CHUNK_LIST);
plen = sizeof(*ph) + chunks_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
if (stcb->asoc.local_auth_chunks) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
new_key->key[keylen++] = i;
}
}
/* append in the HMACs */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_HMAC_LIST);
plen = sizeof(*ph) + hmacs_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
(void)sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
new_key->key + keylen);
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
}
#ifdef SCTP_HMAC_TEST
/*
* HMAC and key concatenation tests
*/
static void
sctp_print_digest(uint8_t *digest, uint32_t digestlen, const char *str)
{
uint32_t i;
SCTP_PRINTF("\n%s: 0x", str);
if (digest == NULL)
return;
for (i = 0; i < digestlen; i++)
SCTP_PRINTF("%02x", digest[i]);
}
static int
sctp_test_hmac(const char *str, uint16_t hmac_id, uint8_t *key,
uint32_t keylen, uint8_t *text, uint32_t textlen,
uint8_t *digest, uint32_t digestlen)
{
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
SCTP_PRINTF("\n%s:", str);
sctp_hmac(hmac_id, key, keylen, text, textlen, computed_digest);
sctp_print_digest(digest, digestlen, "Expected digest");
sctp_print_digest(computed_digest, digestlen, "Computed digest");
if (memcmp(digest, computed_digest, digestlen) != 0) {
SCTP_PRINTF("\nFAILED");
return (-1);
} else {
SCTP_PRINTF("\nPASSED");
return (0);
}
}
/*
* RFC 2202: HMAC-SHA1 test cases
*/
void
sctp_test_hmac_sha1(void)
{
uint8_t *digest;
uint8_t key[128];
uint32_t keylen;
uint8_t text[128];
uint32_t textlen;
uint32_t digestlen = 20;
int failed = 0;
/*-
* test_case = 1
* key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
* key_len = 20
* data = "Hi There"
* data_len = 8
* digest = 0xb617318655057264e28bc0b6fb378c8ef146be00
*/
keylen = 20;
memset(key, 0x0b, keylen);
textlen = 8;
strcpy(text, "Hi There");
digest = "\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00";
if (sctp_test_hmac("SHA1 test case 1", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 2
* key = "Jefe"
* key_len = 4
* data = "what do ya want for nothing?"
* data_len = 28
* digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
*/
keylen = 4;
strcpy(key, "Jefe");
textlen = 28;
strcpy(text, "what do ya want for nothing?");
digest = "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79";
if (sctp_test_hmac("SHA1 test case 2", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 3
* key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
* key_len = 20
* data = 0xdd repeated 50 times
* data_len = 50
* digest = 0x125d7342b9ac11cd91a39af48aa17b4f63f175d3
*/
keylen = 20;
memset(key, 0xaa, keylen);
textlen = 50;
memset(text, 0xdd, textlen);
digest = "\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3";
if (sctp_test_hmac("SHA1 test case 3", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 4
* key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
* key_len = 25
* data = 0xcd repeated 50 times
* data_len = 50
* digest = 0x4c9007f4026250c6bc8414f9bf50c86c2d7235da
*/
keylen = 25;
memcpy(key, "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", keylen);
textlen = 50;
memset(text, 0xcd, textlen);
digest = "\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda";
if (sctp_test_hmac("SHA1 test case 4", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 5
* key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
* key_len = 20
* data = "Test With Truncation"
* data_len = 20
* digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
* digest-96 = 0x4c1a03424b55e07fe7f27be1
*/
keylen = 20;
memset(key, 0x0c, keylen);
textlen = 20;
strcpy(text, "Test With Truncation");
digest = "\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04";
if (sctp_test_hmac("SHA1 test case 5", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 6
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key - Hash Key First"
* data_len = 54
* digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 54;
strcpy(text, "Test Using Larger Than Block-Size Key - Hash Key First");
digest = "\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12";
if (sctp_test_hmac("SHA1 test case 6", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 7
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
* data_len = 73
* digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 73;
strcpy(text, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
digest = "\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91";
if (sctp_test_hmac("SHA1 test case 7", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nSHA1 test results: %d cases failed", failed);
else
SCTP_PRINTF("\nSHA1 test results: all test cases passed");
}
/*
* test assoc key concatenation
*/
static int
sctp_test_key_concatenation(sctp_key_t *key1, sctp_key_t *key2,
sctp_key_t *expected_key)
{
sctp_key_t *key;
int ret_val;
sctp_show_key(key1, "\nkey1");
sctp_show_key(key2, "\nkey2");
key = sctp_compute_hashkey(key1, key2, NULL);
sctp_show_key(expected_key, "\nExpected");
sctp_show_key(key, "\nComputed");
if (memcmp(key, expected_key, expected_key->keylen) != 0) {
SCTP_PRINTF("\nFAILED");
ret_val = -1;
} else {
SCTP_PRINTF("\nPASSED");
ret_val = 0;
}
sctp_free_key(key1);
sctp_free_key(key2);
sctp_free_key(expected_key);
sctp_free_key(key);
return (ret_val);
}
void
sctp_test_authkey(void)
{
sctp_key_t *key1, *key2, *expected_key;
int failed = 0;
/* test case 1 */
key1 = sctp_set_key("\x01\x01\x01\x01", 4);
key2 = sctp_set_key("\x01\x02\x03\x04", 4);
expected_key = sctp_set_key("\x01\x01\x01\x01\x01\x02\x03\x04", 8);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 2 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x02", 1);
expected_key = sctp_set_key("\x00\x00\x00\x01\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 3 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x02", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 4 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x01", 1);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 5 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x01", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 6 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 7 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nKey concatenation test results: %d cases failed", failed);
else
SCTP_PRINTF("\nKey concatenation test results: all test cases passed");
}
#if defined(STANDALONE_HMAC_TEST)
int
main(void)
{
sctp_test_hmac_sha1();
sctp_test_authkey();
}
#endif /* STANDALONE_HMAC_TEST */
#endif /* SCTP_HMAC_TEST */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1370_0 |
crossvul-cpp_data_good_4938_0 | /*
* Copyright 2006-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/objects.h>
#include <openssl/bn.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/ts.h>
#include "ts_lcl.h"
int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num)
{
BIGNUM *num_bn;
int result = 0;
char *hex;
num_bn = BN_new();
if (num_bn == NULL)
return -1;
ASN1_INTEGER_to_BN(num, num_bn);
if ((hex = BN_bn2hex(num_bn))) {
result = BIO_write(bio, "0x", 2) > 0;
result = result && BIO_write(bio, hex, strlen(hex)) > 0;
OPENSSL_free(hex);
}
BN_free(num_bn);
return result;
}
int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj)
{
char obj_txt[128];
OBJ_obj2txt(obj_txt, sizeof(obj_txt), obj, 0);
BIO_printf(bio, "%s\n", obj_txt);
return 1;
}
int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions)
{
int i, critical, n;
X509_EXTENSION *ex;
ASN1_OBJECT *obj;
BIO_printf(bio, "Extensions:\n");
n = X509v3_get_ext_count(extensions);
for (i = 0; i < n; i++) {
ex = X509v3_get_ext(extensions, i);
obj = X509_EXTENSION_get_object(ex);
i2a_ASN1_OBJECT(bio, obj);
critical = X509_EXTENSION_get_critical(ex);
BIO_printf(bio, ": %s\n", critical ? "critical" : "");
if (!X509V3_EXT_print(bio, ex, 0, 4)) {
BIO_printf(bio, "%4s", "");
ASN1_STRING_print(bio, X509_EXTENSION_get_data(ex));
}
BIO_write(bio, "\n", 1);
}
return 1;
}
int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg)
{
int i = OBJ_obj2nid(alg->algorithm);
return BIO_printf(bio, "Hash Algorithm: %s\n",
(i == NID_undef) ? "UNKNOWN" : OBJ_nid2ln(i));
}
int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *a)
{
ASN1_OCTET_STRING *msg;
TS_X509_ALGOR_print_bio(bio, a->hash_algo);
BIO_printf(bio, "Message data:\n");
msg = a->hashed_msg;
BIO_dump_indent(bio, (const char *)ASN1_STRING_data(msg),
ASN1_STRING_length(msg), 4);
return 1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4938_0 |
crossvul-cpp_data_bad_2674_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved", /* 4 */
"Reserved", /* 5 */
"Reserved", /* 6 */
"Reserved", /* 7 */
};
static int
extract_header_length(uint16_t fc)
{
int len = 0;
switch ((fc >> 10) & 0x3) {
case 0x00:
if (fc & (1 << 6)) /* intra-PAN with none dest addr */
return -1;
break;
case 0x01:
return -1;
case 0x02:
len += 4;
break;
case 0x03:
len += 10;
break;
}
switch ((fc >> 14) & 0x3) {
case 0x00:
break;
case 0x01:
return -1;
case 0x02:
len += 4;
break;
case 0x03:
len += 10;
break;
}
if (fc & (1 << 6)) {
if (len < 2)
return -1;
len -= 2;
}
return len;
}
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
int hdrlen;
uint16_t fc;
uint8_t seq;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4] %x", caplen));
return caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(fc);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[fc & 0x7]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
if (hdrlen == -1) {
ND_PRINT((ndo,"invalid! "));
return caplen;
}
if (!ndo->ndo_vflag) {
p+= hdrlen;
caplen -= hdrlen;
} else {
uint16_t panid = 0;
switch ((fc >> 10) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved destination addressing mode"));
return 0;
case 0x02:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
panid = EXTRACT_LE_16BITS(p);
p += 2;
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
ND_PRINT((ndo,"< "));
switch ((fc >> 14) & 0x3) {
case 0x00:
ND_PRINT((ndo,"none "));
break;
case 0x01:
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case 0x02:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
break;
case 0x03:
if (!(fc & (1 << 6))) {
panid = EXTRACT_LE_16BITS(p);
p += 2;
}
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
break;
}
caplen -= hdrlen;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2674_0 |
crossvul-cpp_data_good_235_0 | /* radare2 - LGPL - Copyright 2016-2017 - Davis, Alex Kornitzer */
#include <r_util.h>
#include "mdmp.h"
ut64 r_bin_mdmp_get_paddr(struct r_bin_mdmp_obj *obj, ut64 vaddr) {
/* FIXME: Will only resolve exact matches, probably no need to fix as
** this function will become redundant on the optimisation stage */
struct minidump_memory_descriptor64 *memory;
ut64 index, paddr = 0;
RListIter *it;
/* Loop through the memories sections looking for a match */
index = obj->streams.memories64.base_rva;
r_list_foreach (obj->streams.memories64.memories, it, memory) {
if (vaddr == memory->start_of_memory_range) {
paddr = index;
break;
}
index += memory->data_size;
}
return paddr;
}
struct minidump_memory_info *r_bin_mdmp_get_mem_info(struct r_bin_mdmp_obj *obj, ut64 vaddr) {
struct minidump_memory_info *mem_info;
RListIter *it;
if (!obj) return NULL;
r_list_foreach (obj->streams.memory_infos, it, mem_info) {
if (mem_info->allocation_base && vaddr == mem_info->base_address) {
return mem_info;
}
}
return NULL;
}
ut32 r_bin_mdmp_get_srwx(struct r_bin_mdmp_obj *obj, ut64 vaddr) {
struct minidump_memory_info *mem_info;
if (!(mem_info = r_bin_mdmp_get_mem_info(obj, vaddr))) {
return 0;
}
/* FIXME: Have I got these mappings right, I am not sure I have!!! */
switch (mem_info->protect) {
case MINIDUMP_PAGE_READONLY:
return R_BIN_SCN_READABLE;
case MINIDUMP_PAGE_READWRITE:
return R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE;
case MINIDUMP_PAGE_EXECUTE:
return R_BIN_SCN_EXECUTABLE;
case MINIDUMP_PAGE_EXECUTE_READ:
return R_BIN_SCN_EXECUTABLE | R_BIN_SCN_READABLE;
case MINIDUMP_PAGE_EXECUTE_READWRITE:
return R_BIN_SCN_EXECUTABLE | R_BIN_SCN_READABLE | R_BIN_SCN_WRITABLE;
case MINIDUMP_PAGE_NOACCESS:
case MINIDUMP_PAGE_WRITECOPY:
case MINIDUMP_PAGE_EXECUTE_WRITECOPY:
case MINIDUMP_PAGE_GUARD:
case MINIDUMP_PAGE_NOCACHE:
case MINIDUMP_PAGE_WRITECOMBINE:
default:
return 0;
}
}
static void r_bin_mdmp_free_pe32_bin(void *pe_bin_) {
struct Pe32_r_bin_mdmp_pe_bin *pe_bin = pe_bin_;
if (pe_bin) {
sdb_free (pe_bin->bin->kv);
Pe32_r_bin_pe_free (pe_bin->bin);
R_FREE (pe_bin);
}
}
static void r_bin_mdmp_free_pe64_bin(void *pe_bin_) {
struct Pe64_r_bin_mdmp_pe_bin *pe_bin = pe_bin_;
if (pe_bin) {
sdb_free (pe_bin->bin->kv);
Pe64_r_bin_pe_free (pe_bin->bin);
R_FREE (pe_bin);
}
}
void r_bin_mdmp_free(struct r_bin_mdmp_obj *obj) {
if (!obj) return;
r_list_free (obj->streams.ex_threads);
r_list_free (obj->streams.memories);
r_list_free (obj->streams.memories64.memories);
r_list_free (obj->streams.memory_infos);
r_list_free (obj->streams.modules);
r_list_free (obj->streams.operations);
r_list_free (obj->streams.thread_infos);
r_list_free (obj->streams.threads);
r_list_free (obj->streams.unloaded_modules);
r_list_free (obj->pe32_bins);
r_list_free (obj->pe64_bins);
r_buf_free (obj->b);
obj->b = NULL;
free (obj);
return;
}
static void r_bin_mdmp_init_parsing(struct r_bin_mdmp_obj *obj) {
/* TODO: Handle unions, can we? */
/* FIXME: Why are we getting struct missing errors when it finds them */
sdb_set (obj->kv, "mdmp_mem_state.cparse",
"enum mdmp_mem_state { MEM_COMMIT=0x1000, "
"MEM_FREE=0x10000, MEM_RESERVE=0x02000 };", 0);
sdb_set (obj->kv, "mdmp_mem_type.cparse",
"enum mdmp_mem_type { MEM_IMAGE=0x1000000, "
"MEM_MAPPED=0x40000, MEM_PRIVATE=0x20000 };", 0);
sdb_set (obj->kv, "mdmp_page_protect.cparse",
"enum mdmp_page_protect { PAGE_NOACCESS=1, "
"PAGE_READONLY=2, PAGE_READWRITE=4, PAGE_WRITECOPY=8, "
"PAGE_EXECUTE=0x10, PAGE_EXECUTE_READ=0x20, "
"PAGE_EXECUTE_READWRITE=0x40, PAGE_EXECUTE_WRITECOPY=0x80, "
"PAGE_GUARD=0x100, PAGE_NOCACHE=0x200, "
"PAGE_WRITECOMBINE=0x400, PAGE_TARGETS_INVALID=0x40000000 };",
0);
sdb_set (obj->kv, "mdmp_misc1_flags.cparse",
"enum mdmp_misc1_flags { MINIDUMP_MISC1_PROCESS_ID=1, "
"MINIDUMP_MISC1_PROCESS_TIMES=2, "
"MINIDUMP_MISC1_PROCESSOR_POWER_INFO=4 };", 0);
sdb_set (obj->kv, "mdmp_processor_architecture.cparse",
"enum mdmp_processor_architecture { "
"PROCESSOR_ARCHITECTURE_INTEL=0, "
"PROCESSOR_ARCHITECTURE_ARM=5, "
"PROCESSOR_ARCHITECTURE_IA64=6, "
"PROCESSOR_ARCHITECTURE_AMD64=9, "
"PROCESSOR_ARCHITECTURE_UNKNOWN=0xffff };", 0);
sdb_set (obj->kv, "mdmp_product_type.cparse",
"enum mdmp_product_type { "
"VER_NT_WORKSTATION=1, VER_NT_DOMAIN_CONTROLLER=2, "
"VER_NT_SERVER=3 };", 0);
sdb_set (obj->kv, "mdmp_platform_id.cparse",
"enum mdmp_platform_id { "
"VER_PLATFORM_WIN32s=0, "
"VER_PLATFORM_WIN32_WINDOWS=1, "
"VER_PLATFORM_WIN32_NT=2 };", 0);
sdb_set (obj->kv, "mdmp_suite_mask.cparse",
"enum mdmp_suite_mask { "
"VER_SUITE_SMALLBUSINESS=1, VER_SUITE_ENTERPRISE=2, "
"VER_SUITE_BACKOFFICE=4, VER_SUITE_TERMINAL=0x10, "
"VER_SUITE_SMALLBUSINESS_RESTRICTED=0x20, "
"VER_SUITE_EMBEDDEDNT=0x40, VER_SUITE_DATACENTER=0x80, "
"VER_SUITE_SINGLEUSERTS=0x100, VER_SUITE_PERSONAL=0x200, "
"VER_SUITE_BLADE=0x400, VER_SUITE_STORAGE_SERVER=0x2000, "
"VER_SUITE_COMPUTE_SERVER=0x4000 };", 0);
sdb_set (obj->kv, "mdmp_callback_type.cparse",
"enum mdmp_type { ModuleCallback=0,"
"ThreadCallback=1, ThreadExCallback=2, "
"IncludeThreadCallback=3, IncludeModuleCallback=4, "
"MemoryCallback=5, CancelCallback=6, "
"WriteKernelMinidumpCallback=7, "
"KernelMinidumpStatusCallback=8, "
"RemoveMemoryCallback=9, "
"IncludeVmRegionCallback=10, "
"IoStartCallback=11, IoWriteAllCallback=12, "
"IoFinishCallback=13, ReadMemoryFailureCallback=14, "
"SecondaryFlagsCallback=15 };", 0);
sdb_set (obj->kv, "mdmp_exception_code.cparse",
"enum mdmp_exception_code { "
"DBG_CONTROL_C=0x40010005, "
"EXCEPTION_GUARD_PAGE_VIOLATION=0x80000001, "
"EXCEPTION_DATATYPE_MISALIGNMENT=0x80000002, "
"EXCEPTION_BREAKPOINT=0x80000003, "
"EXCEPTION_SINGLE_STEP=0x80000004, "
"EXCEPTION_ACCESS_VIOLATION=0xc0000005, "
"EXCEPTION_IN_PAGE_ERROR=0xc0000006, "
"EXCEPTION_INVALID_HANDLE=0xc0000008, "
"EXCEPTION_ILLEGAL_INSTRUCTION=0xc000001d, "
"EXCEPTION_NONCONTINUABLE_EXCEPTION=0xc0000025, "
"EXCEPTION_INVALID_DISPOSITION=0xc0000026, "
"EXCEPTION_ARRAY_BOUNDS_EXCEEDED=0xc000008c, "
"EXCEPTION_FLOAT_DENORMAL_OPERAND=0xc000008d, "
"EXCEPTION_FLOAT_DIVIDE_BY_ZERO=0xc000008e, "
"EXCEPTION_FLOAT_INEXACT_RESULT=0xc000008f, "
"EXCEPTION_FLOAT_INVALID_OPERATION=0xc0000090, "
"EXCEPTION_FLOAT_OVERFLOW=0xc0000091, "
"EXCEPTION_FLOAT_STACK_CHECK=0xc0000092, "
"EXCEPTION_FLOAT_UNDERFLOW=0xc0000093, "
"EXCEPTION_INTEGER_DIVIDE_BY_ZERO=0xc0000094, "
"EXCEPTION_INTEGER_OVERFLOW=0xc0000095, "
"EXCEPTION_PRIVILEGED_INSTRUCTION=0xc0000096, "
"EXCEPTION_STACK_OVERFLOW=0xc00000fd, "
"EXCEPTION_POSSIBLE_DEADLOCK=0xc0000194 };", 0);
sdb_set (obj->kv, "mdmp_exception_flags.cparse",
"enum mdmp_exception_flags { "
"EXCEPTION_CONTINUABLE=0, "
"EXCEPTION_NONCONTINUABLE=1 };", 0);
sdb_set (obj->kv, "mdmp_handle_object_information_type.cparse",
"enum mdmp_handle_object_information_type { "
"MiniHandleObjectInformationNone=0, "
"MiniThreadInformation1=1, MiniMutantInformation1=2, "
"MiniMutantInformation2=3, MiniMutantProcessInformation1=4, "
"MiniProcessInformation2=5 };", 0);
sdb_set (obj->kv, "mdmp_secondary_flags.cparse",
"enum mdmp_secondary_flags { "
"MiniSecondaryWithoutPowerInfo=0 };", 0);
sdb_set (obj->kv, "mdmp_stream_type.cparse",
"enum mdmp_stream_type { UnusedStream=0, "
"ReservedStream0=1, ReservedStream1=2, "
"ThreadListStream=3, ModuleListStream=4, "
"MemoryListStream=5, ExceptionStream=6, "
"SystemInfoStream=7, ThreadExListStream=8, "
"Memory64ListStream=9, CommentStreamA=10, "
"CommentStreamW=11, HandleDataStream=12, "
"FunctionTableStream=13, UnloadedModuleListStream=14, "
"MiscInfoStream=15, MemoryInfoListStream=16, "
"ThreadInfoListStream=17, "
"HandleOperationListStream=18, "
"LastReservedStream=0xffff };", 0);
sdb_set (obj->kv, "mdmp_type.cparse", "enum mdmp_type { "
"MiniDumpNormal=0x0, "
"MiniDumpWithDataSegs=0x1, "
"MiniDumpWithFullMemory=0x2, "
"MiniDumpWithHandleData=0x4, "
"MiniDumpFilterMemory=0x8, "
"MiniDumpScanMemory=0x10, "
"MiniDumpWithUnloadedModule=0x20, "
"MiniDumpWihinDirectlyReferencedMemory=0x40, "
"MiniDumpFilterWithModulePaths=0x80,"
"MiniDumpWithProcessThreadData=0x100, "
"MiniDumpWithPrivateReadWriteMemory=0x200, "
"MiniDumpWithoutOptionalDate=0x400, "
"MiniDumpWithFullMemoryInfo=0x800, "
"MiniDumpWithThreadInfo=0x1000, "
"MiniDumpWithCodeSegs=0x2000, "
"MiniDumpWithoutAuxiliaryState=0x4000, "
"MiniDumpWithFullAuxiliaryState=0x8000, "
"MiniDumpWithPrivateWriteCopyMemory=0x10000, "
"MiniDumpIgnoreInaccessibleMemory=0x20000, "
"MiniDumpWithTokenInformation=0x40000, "
"MiniDumpWithModuleHeaders=0x80000, "
"MiniDumpFilterTriage=0x100000, "
"MiniDumpValidTypeFlags=0x1fffff };", 0);
sdb_set (obj->kv, "mdmp_module_write_flags.cparse",
"enum mdmp_module_write_flags { "
"ModuleWriteModule=0, ModuleWriteDataSeg=2, "
"ModuleWriteMiscRecord=4, ModuleWriteCvRecord=8, "
"ModuleReferencedByMemory=0x10, ModuleWriteTlsData=0x20, "
"ModuleWriteCodeSegs=0x40 };", 0);
sdb_set (obj->kv, "mdmp_thread_write_flags.cparse",
"enum mdmp_thread_write_flags { "
"ThreadWriteThread=0, ThreadWriteStack=2, "
"ThreadWriteContext=4, ThreadWriteBackingStore=8, "
"ThreadWriteInstructionWindow=0x10, "
"ThreadWriteThreadData=0x20, "
"ThreadWriteThreadInfo=0x40 };", 0);
sdb_set (obj->kv, "mdmp_context_flags.cparse",
"enum mdmp_context_flags { CONTEXT_i386=0x10000, "
"CONTEXT_CONTROL=0x10001, CONTEXT_INTEGER=0x10002, "
"CONTEXT_SEGMENTS=0x10004, CONTEXT_FLOATING_POINT=0x10008, "
"CONTEXT_DEBUG_REGISTERS=0x10010, "
"CONTEXT_EXTENDED_REGISTERS=0x10020 };", 0);
sdb_set (obj->kv, "mdmp_location_descriptor.format",
"dd DataSize RVA", 0);
sdb_set (obj->kv, "mdmp_location_descriptor64.format",
"qq DataSize RVA", 0);
sdb_set (obj->kv, "mdmp_memory_descriptor.format", "q? "
"StartOfMemoryRange "
"(mdmp_location_descriptor)Memory", 0);
sdb_set (obj->kv, "mdmp_memory_descriptor64.format", "qq "
"StartOfMemoryRange DataSize", 0);
#if 0
/* TODO: Flag dependent thus not fully implemented */
sdb_set (obj->kv, "mdmp_context.format", "[4]B "
"(mdmp_context_flags)ContextFlags", 0);
#endif
sdb_set (obj->kv, "mdmp_vs_fixedfileinfo.format", "ddddddddddddd "
"dwSignature dwStrucVersion dwFileVersionMs "
"dwFileVersionLs dwProductVersionMs "
"dwProductVersionLs dwFileFlagsMask dwFileFlags "
"dwFileOs dwFileType dwFileSubtype dwFileDateMs "
"dwFileDateLs", 0);
sdb_set (obj->kv, "mdmp_string.format", "dZ Length Buffer", 0);
}
static bool r_bin_mdmp_init_hdr(struct r_bin_mdmp_obj *obj) {
obj->hdr = (struct minidump_header *)obj->b->buf;
if (obj->hdr->number_of_streams == 0) {
eprintf ("[WARN] No streams present!\n");
return false;
}
if (obj->hdr->stream_directory_rva < sizeof (struct minidump_header))
{
eprintf ("[ERROR] RVA for directory resides in the header!\n");
return false;
}
if (obj->hdr->check_sum) {
eprintf ("[INFO] Checksum present but needs validating!\n");
return false;
}
sdb_num_set (obj->kv, "mdmp.hdr.time_date_stamp", obj->hdr->time_date_stamp, 0);
sdb_num_set (obj->kv, "mdmp.hdr.flags", obj->hdr->flags, 0);
sdb_num_set (obj->kv, "mdmp_header.offset", 0, 0);
sdb_set (obj->kv, "mdmp_header.format", "[4]zddddt[8]B Signature "
"Version NumberOfStreams StreamDirectoryRVA CheckSum "
"TimeDateStamp (mdmp_type)Flags", 0);
return true;
}
static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) {
int i;
struct minidump_handle_operation_list *handle_operation_list;
struct minidump_memory_list *memory_list;
struct minidump_memory64_list *memory64_list;
struct minidump_memory_info_list *memory_info_list;
struct minidump_module_list *module_list;
struct minidump_thread_list *thread_list;
struct minidump_thread_ex_list *thread_ex_list;
struct minidump_thread_info_list *thread_info_list;
struct minidump_unloaded_module_list *unloaded_module_list;
struct avrf_handle_operation *handle_operations;
struct minidump_memory_descriptor *memories;
struct minidump_memory_descriptor64 *memories64;
struct minidump_memory_info *memory_infos;
struct minidump_module *modules;
struct minidump_thread *threads;
struct minidump_thread_ex *ex_threads;
struct minidump_thread_info *thread_infos;
struct minidump_unloaded_module *unloaded_modules;
/* We could confirm data sizes but a malcious MDMP will always get around
** this! But we can ensure that the data is not outside of the file */
if (entry->location.rva + entry->location.data_size > obj->b->length) {
eprintf ("[ERROR] Size Mismatch - Stream data is larger than file size!\n");
return false;
}
switch (entry->stream_type) {
case THREAD_LIST_STREAM:
thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread.format", "ddddq?? "
"ThreadId SuspendCount PriorityClass Priority "
"Teb (mdmp_memory_descriptor)Stack "
"(mdmp_location_descriptor)ThreadContext", 0);
sdb_num_set (obj->kv, "mdmp_thread_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_list.format",
sdb_fmt ("d[%i]? "
"NumberOfThreads (mdmp_thread)Threads",
thread_list->number_of_threads),
0);
/* TODO: Not yet fully parsed or utilised */
for (i = 0; i < thread_list->number_of_threads; i++) {
threads = (struct minidump_thread *)(&(thread_list->threads));
r_list_append (obj->streams.threads, &(threads[i]));
}
break;
case MODULE_LIST_STREAM:
module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_module.format", "qddtd???qq "
"BaseOfImage SizeOfImage CheckSum "
"TimeDateStamp ModuleNameRVA "
"(mdmp_vs_fixedfileinfo)VersionInfo "
"(mdmp_location_descriptor)CvRecord "
"(mdmp_location_descriptor)MiscRecord "
"Reserved0 Reserved1", 0);
sdb_num_set (obj->kv, "mdmp_module_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_module_list.format",
sdb_fmt ("d[%i]? "
"NumberOfModule (mdmp_module)Modules",
module_list->number_of_modules,
0),
0);
for (i = 0; i < module_list->number_of_modules; i++) {
modules = (struct minidump_module *)(&(module_list->modules));
r_list_append(obj->streams.modules, &(modules[i]));
}
break;
case MEMORY_LIST_STREAM:
memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_memory_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory_list.format",
sdb_fmt ("d[%i]? "
"NumberOfMemoryRanges "
"(mdmp_memory_descriptor)MemoryRanges ",
memory_list->number_of_memory_ranges,
0),
0);
for (i = 0; i < memory_list->number_of_memory_ranges; i++) {
memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges));
r_list_append (obj->streams.memories, &(memories[i]));
}
break;
case EXCEPTION_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_exception.format", "[4]E[4]Eqqdd[15]q "
"(mdmp_exception_code)ExceptionCode "
"(mdmp_exception_flags)ExceptionFlags "
"ExceptionRecord ExceptionAddress "
"NumberParameters __UnusedAlignment "
"ExceptionInformation", 0);
sdb_num_set (obj->kv, "mdmp_exception_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_exception_stream.format", "dd?? "
"ThreadId __Alignment "
"(mdmp_exception)ExceptionRecord "
"(mdmp_location_descriptor)ThreadContext", 0);
break;
case SYSTEM_INFO_STREAM:
obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_system_info.offset",
entry->location.rva, 0);
/* TODO: We need E as a byte! */
sdb_set (obj->kv, "mdmp_system_info.format", "[2]EwwbBddd[4]Ed[2]Ew[2]q "
"(mdmp_processor_architecture)ProcessorArchitecture "
"ProcessorLevel ProcessorRevision NumberOfProcessors "
"(mdmp_product_type)ProductType "
"MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId "
"CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures", 0);
break;
case THREAD_EX_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread_ex.format", "ddddq??? "
"ThreadId SuspendCount PriorityClass Priority "
"Teb (mdmp_memory_descriptor)Stack "
"(mdmp_location_descriptor)ThreadContext "
"(mdmp_memory_descriptor)BackingStore", 0);
sdb_num_set (obj->kv, "mdmp_thread_ex_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_ex_list.format",
sdb_fmt ("d[%i]? NumberOfThreads "
"(mdmp_thread_ex)Threads",
thread_ex_list->number_of_threads, 0),
0);
for (i = 0; i < thread_ex_list->number_of_threads; i++) {
ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads));
r_list_append (obj->streams.ex_threads, &(ex_threads[i]));
}
break;
case MEMORY_64_LIST_STREAM:
memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_memory64_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory64_list.format",
sdb_fmt ("qq[%i]? NumberOfMemoryRanges "
"BaseRva "
"(mdmp_memory_descriptor64)MemoryRanges",
memory64_list->number_of_memory_ranges),
0);
obj->streams.memories64.base_rva = memory64_list->base_rva;
for (i = 0; i < memory64_list->number_of_memory_ranges; i++) {
memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges));
r_list_append (obj->streams.memories64.memories, &(memories64[i]));
}
break;
case COMMENT_STREAM_A:
/* TODO: Not yet fully parsed or utilised */
obj->streams.comments_a = obj->b->buf + entry->location.rva;
sdb_num_set (obj->kv, "mdmp_comment_stream_a.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_comment_stream_a.format",
"s CommentA", 0);
break;
case COMMENT_STREAM_W:
/* TODO: Not yet fully parsed or utilised */
obj->streams.comments_w = obj->b->buf + entry->location.rva;
sdb_num_set (obj->kv, "mdmp_comment_stream_w.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_comment_stream_w.format",
"s CommentW", 0);
break;
case HANDLE_DATA_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_handle_data_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_handle_data_stream.format", "dddd "
"SizeOfHeader SizeOfDescriptor "
"NumberOfDescriptors Reserved", 0);
break;
case FUNCTION_TABLE_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_function_table_stream.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_function_table_stream.format", "dddddd "
"SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor "
"SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad",
0);
break;
case UNLOADED_MODULE_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_unloaded_module.format", "qddtd "
"BaseOfImage SizeOfImage CheckSum TimeDateStamp "
"ModuleNameRva", 0);
sdb_num_set (obj->kv, "mdmp_unloaded_module_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_unloaded_module_list.format", "ddd "
"SizeOfHeader SizeOfEntry NumberOfEntries", 0);
for (i = 0; i < unloaded_module_list->number_of_entries; i++) {
unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list));
r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i]));
}
break;
case MISC_INFO_STREAM:
/* TODO: Not yet fully parsed or utilised */
obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva);
/* TODO: Handle different sizes */
sdb_num_set (obj->kv, "mdmp_misc_info.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_misc_info.format", "d[4]Bdtttddddd "
"SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId "
"ProcessCreateTime ProcessUserTime ProcessKernelTime "
"ProcessorMaxMhz ProcessorCurrentMhz "
"ProcessorMhzLimit ProcessorMaxIdleState "
"ProcessorCurrentIdleState", 0);
break;
case MEMORY_INFO_LIST_STREAM:
memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_memory_info.format",
"qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase "
"(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize "
"(mdmp_mem_state)State (mdmp_page_protect)Protect "
"(mdmp_mem_type)Type __Alignment2", 0);
sdb_num_set (obj->kv, "mdmp_memory_info_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_memory_info_list.format",
sdb_fmt ("ddq[%i]? SizeOfHeader SizeOfEntry "
"NumberOfEntries (mdmp_memory_info)MemoryInfo",
memory_info_list->number_of_entries),
0);
for (i = 0; i < memory_info_list->number_of_entries; i++) {
memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list));
r_list_append (obj->streams.memory_infos, &(memory_infos[i]));
}
break;
case THREAD_INFO_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva);
sdb_set (obj->kv, "mdmp_thread_info.format", "ddddttttqq "
"ThreadId DumpFlags DumpError ExitStatus CreateTime "
"ExitTime KernelTime UserTime StartAddress Affinity",
0);
sdb_num_set (obj->kv, "mdmp_thread_info_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_thread_info_list.format", "ddd "
"SizeOfHeader SizeOfEntry NumberOfEntries", 0);
for (i = 0; i < thread_info_list->number_of_entries; i++) {
thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list));
r_list_append (obj->streams.thread_infos, &(thread_infos[i]));
}
break;
case HANDLE_OPERATION_LIST_STREAM:
/* TODO: Not yet fully parsed or utilised */
handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva);
sdb_num_set (obj->kv, "mdmp_handle_operation_list.offset",
entry->location.rva, 0);
sdb_set (obj->kv, "mdmp_handle_operation_list.format", "dddd "
"SizeOfHeader SizeOfEntry NumberOfEntries Reserved", 0);
for (i = 0; i < handle_operation_list->number_of_entries; i++) {
handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list));
r_list_append (obj->streams.operations, &(handle_operations[i]));
}
break;
case LAST_RESERVED_STREAM:
/* TODO: Not yet fully parsed or utilised */
break;
case UNUSED_STREAM:
case RESERVED_STREAM_0:
case RESERVED_STREAM_1:
/* Silently ignore reserved streams */
break;
default:
eprintf ("[WARN] Invalid or unsupported enumeration encountered %i\n", entry->stream_type);
return false;
}
return true;
}
static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) {
int i;
struct minidump_directory entry;
sdb_num_set (obj->kv, "mdmp_directory.offset",
obj->hdr->stream_directory_rva, 0);
sdb_set (obj->kv, "mdmp_directory.format", "[4]E? "
"(mdmp_stream_type)StreamType "
"(mdmp_location_descriptor)Location", 0);
/* Parse each entry in the directory */
ut64 rvadir = obj->hdr->stream_directory_rva;
for (i = 0; i < (int)obj->hdr->number_of_streams; i++) {
ut32 delta = i * sizeof (struct minidump_directory);
int r = r_buf_read_at (obj->b, rvadir + delta, (ut8*) &entry, sizeof (struct minidump_directory));
if (r) {
r_bin_mdmp_init_directory_entry (obj, &entry);
}
}
return true;
}
static bool r_bin_mdmp_patch_pe_headers(RBuffer *pe_buf) {
int i;
Pe64_image_dos_header dos_hdr;
Pe64_image_nt_headers nt_hdr;
Pe64_image_section_header *section_hdrs;
r_buf_read_at (pe_buf, 0, (ut8 *)&dos_hdr, sizeof (Pe64_image_dos_header));
r_buf_read_at (pe_buf, dos_hdr.e_lfanew, (ut8 *)&nt_hdr, sizeof (Pe64_image_nt_headers));
/* Patch RawData in headers */
section_hdrs = (Pe64_image_section_header *)(pe_buf->buf + dos_hdr.e_lfanew + 4 + sizeof (Pe64_image_file_header) + nt_hdr.file_header.SizeOfOptionalHeader);
for (i = 0; i < nt_hdr.file_header.NumberOfSections; i++) {
section_hdrs[i].PointerToRawData = section_hdrs[i].VirtualAddress;
}
return true;
}
static int check_pe32_bytes(const ut8 *buf, ut64 length) {
unsigned int idx;
if (!buf || length <= 0x3d) {
return false;
}
idx = (buf[0x3c] | (buf[0x3d]<<8));
if (length > idx + 0x18 + 2) {
if (!memcmp (buf, "MZ", 2) && !memcmp (buf+idx, "PE", 2) && !memcmp (buf+idx+0x18, "\x0b\x01", 2)) {
return true;
}
}
return false;
}
static int check_pe64_bytes(const ut8 *buf, ut64 length) {
int idx, ret = false;
if (!buf || length <= 0x3d) {
return false;
}
idx = buf[0x3c] | (buf[0x3d]<<8);
if (length >= idx + 0x20) {
if (!memcmp (buf, "MZ", 2) && !memcmp (buf+idx, "PE", 2) && !memcmp (buf+idx+0x18, "\x0b\x02", 2)) {
ret = true;
}
}
return ret;
}
static bool r_bin_mdmp_init_pe_bins(struct r_bin_mdmp_obj *obj) {
bool dup;
ut64 paddr;
struct minidump_module *module;
struct Pe32_r_bin_mdmp_pe_bin *pe32_bin, *pe32_dup;
struct Pe64_r_bin_mdmp_pe_bin *pe64_bin, *pe64_dup;
RBuffer *buf;
RListIter *it, *it_dup;
r_list_foreach (obj->streams.modules, it, module) {
/* Duplicate modules can appear in the MDMP module list,
** filtering them out seems to be the correct behaviour */
if (!(paddr = r_bin_mdmp_get_paddr (obj, module->base_of_image))) {
continue;
}
int left = 0;
const ut8 *b = r_buf_get_at (obj->b, paddr, &left);
buf = r_buf_new_with_bytes (b, R_MIN (left, module->size_of_image));
dup = false;
if (check_pe32_bytes (buf->buf, module->size_of_image)) {
r_list_foreach(obj->pe32_bins, it_dup, pe32_dup) {
if (pe32_dup->vaddr == module->base_of_image) {
dup = true;
continue;
}
}
if (dup) {
continue;
}
if (!(pe32_bin = R_NEW0 (struct Pe32_r_bin_mdmp_pe_bin))) {
continue;
}
r_bin_mdmp_patch_pe_headers (buf);
pe32_bin->vaddr = module->base_of_image;
pe32_bin->paddr = paddr;
pe32_bin->bin = Pe32_r_bin_pe_new_buf (buf, 0);
r_list_append (obj->pe32_bins, pe32_bin);
} else if (check_pe64_bytes (buf->buf, module->size_of_image)) {
r_list_foreach(obj->pe64_bins, it_dup, pe64_dup) {
if (pe64_dup->vaddr == module->base_of_image) {
dup = true;
continue;
}
}
if (dup) {
continue;
}
if (!(pe64_bin = R_NEW0 (struct Pe64_r_bin_mdmp_pe_bin))) {
continue;
}
r_bin_mdmp_patch_pe_headers (buf);
pe64_bin->vaddr = module->base_of_image;
pe64_bin->paddr = paddr;
pe64_bin->bin = Pe64_r_bin_pe_new_buf (buf, 0);
r_list_append (obj->pe64_bins, pe64_bin);
}
r_buf_free (buf);
}
return true;
}
static int r_bin_mdmp_init(struct r_bin_mdmp_obj *obj) {
r_bin_mdmp_init_parsing (obj);
if (!r_bin_mdmp_init_hdr (obj)) {
eprintf ("[ERROR] Failed to initialise header\n");
return false;
}
if (!r_bin_mdmp_init_directory (obj)) {
eprintf ("[ERROR] Failed to initialise directory structures!\n");
return false;
}
if (!r_bin_mdmp_init_pe_bins (obj)) {
eprintf ("[ERROR] Failed to initialise pe binaries!\n");
return false;
}
return true;
}
struct r_bin_mdmp_obj *r_bin_mdmp_new_buf(struct r_buf_t *buf) {
bool fail = false;
struct r_bin_mdmp_obj *obj = R_NEW0 (struct r_bin_mdmp_obj);
if (!obj) {
return NULL;
}
obj->kv = sdb_new0 ();
obj->b = r_buf_new ();
obj->size = (ut32)buf->length;
fail |= (!(obj->streams.ex_threads = r_list_new ()));
fail |= (!(obj->streams.memories = r_list_new ()));
fail |= (!(obj->streams.memories64.memories = r_list_new ()));
fail |= (!(obj->streams.memory_infos = r_list_new ()));
fail |= (!(obj->streams.modules = r_list_new ()));
fail |= (!(obj->streams.operations = r_list_new ()));
fail |= (!(obj->streams.thread_infos = r_list_new ()));
fail |= (!(obj->streams.threads = r_list_new ()));
fail |= (!(obj->streams.unloaded_modules = r_list_new ()));
fail |= (!(obj->pe32_bins = r_list_newf (r_bin_mdmp_free_pe32_bin)));
fail |= (!(obj->pe64_bins = r_list_newf (r_bin_mdmp_free_pe64_bin)));
if (fail) {
r_bin_mdmp_free (obj);
return NULL;
}
if (!r_buf_set_bytes (obj->b, buf->buf, buf->length)) {
r_bin_mdmp_free (obj);
return NULL;
}
if (!r_bin_mdmp_init (obj)) {
r_bin_mdmp_free (obj);
return NULL;
}
return obj;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_235_0 |
crossvul-cpp_data_bad_5313_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 "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colormap-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/distort.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magic.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/resource_.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/transform.h"
#include "MagickCore/utility.h"
#include "MagickCore/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(Image *image,unsigned char *p,ssize_t y,int bpp,
ExceptionInfo *exception)
{
int
bit;
Quantum
index;
register Quantum
*q;
ssize_t
x;
switch (bpp)
{
case 1: /* Convert bitmap scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
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);
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);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
p++;
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
case 2: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=4)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 4) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p >> 2) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x3,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if ((image->columns % 4) != 0)
{
index=ConstrainColormapIndex(image,(*p >> 6) & 0x3,exception);
SetPixelIndex(image,index,q);
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);
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);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
}
}
p++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 4: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-1); x+=2)
{
index=ConstrainColormapIndex(image,(*p >> 4) & 0x0f,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
q+=GetPixelChannels(image);
index=ConstrainColormapIndex(image,(*p) & 0x0f,exception);
SetPixelIndex(image,index,q);
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);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
break;
}
case 8: /* Convert PseudoColor scanline. */
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL) break;
for (x=0; x < (ssize_t) image->columns; x++)
{
index=ConstrainColormapIndex(image,*p,exception);
SetPixelIndex(image,index,q);
SetPixelViaPixelInfo(image,image->colormap+(ssize_t) index,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
break;
case 24: /* Convert DirectColor scanline. */
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
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);
}
if (!SyncAuthenticPixels(image,exception))
break;
break;
}
}
/* Helper for WPG1 raster reader. */
#define InsertByte(b) \
{ \
BImgBuff[x]=b; \
x++; \
if((ssize_t) x>=ldblk) \
{ \
InsertRow(image,BImgBuff,(ssize_t) y,bpp,exception); \
x=0; \
y++; \
} \
}
/* WPG1 raster reader. */
static int UnpackWPGRaster(Image *image,int bpp,ExceptionInfo *exception)
{
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(image,BImgBuff,y-1,bpp,exception);
}
}
}
}
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(image,BImgBuff,(ssize_t) y,bpp,exception); \
x=0; \
y++; \
} \
}
/* WPG2 raster reader. */
static int UnpackWPG2Raster(Image *image,int bpp,ExceptionInfo *exception)
{
int
RunCount,
XorMe = 0;
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(image,BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1),
bpp,exception);
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[MagickPathExtent];
const MagicInfo
*magic_info;
FILE
*ps_file;
ImageInfo
*clone_info;
Image
*image2;
unsigned char
magick[2*MagickPathExtent];
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*MagickPathExtent, 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*MagickPathExtent,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,MagickPathExtent);
/* Read nested image */
/*FormatString(clone_info->filename,"%s:%s",magic_info->name,postscript_file);*/
FormatLocaleString(clone_info->filename,MagickPathExtent,"%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,MagickPathExtent);
(void) CopyMagickMemory(image2->magick_filename,image->magick_filename,MagickPathExtent);
(void) CopyMagickMemory(image2->magick,image->magick,MagickPathExtent);
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 == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
one=1;
image=AcquireImage(image_info,exception);
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->resolution.x=BitmapHeader1.HorzRes/470.0;
image->resolution.y=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,exception))
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->resolution.x=BitmapHeader2.HorzRes/470.0;
image->resolution.y=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,exception))
{
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=(PixelInfo *) 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,exception) < 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,exception);
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,exception) == 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,exception))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelInfo *) 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(image,BImgBuff,i,bpp,exception);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp,exception) < 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,exception);
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,exception);
if (status == MagickFalse)
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=AcquireMagickInfo("WPG","WPG","Word Perfect Graphics");
entry->decoder=(DecodeImageHandler *) ReadWPGImage;
entry->magick=(IsImageFormatHandler *) IsWPG;
entry->flags|=CoderSeekableStreamFlag;
(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-125/c/bad_5313_0 |
crossvul-cpp_data_good_1370_0 | /*-
* SPDX-License-Identifier: BSD-3-Clause
*
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, Inc. 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.
*/
#ifdef __FreeBSD__
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/sys/netinet/sctp_auth.c 355931 2019-12-20 15:25:08Z tuexen $");
#endif
#include <netinet/sctp_os.h>
#include <netinet/sctp.h>
#include <netinet/sctp_header.h>
#include <netinet/sctp_pcb.h>
#include <netinet/sctp_var.h>
#include <netinet/sctp_sysctl.h>
#include <netinet/sctputil.h>
#include <netinet/sctp_indata.h>
#include <netinet/sctp_output.h>
#include <netinet/sctp_auth.h>
#ifdef SCTP_DEBUG
#define SCTP_AUTH_DEBUG (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH1)
#define SCTP_AUTH_DEBUG2 (SCTP_BASE_SYSCTL(sctp_debug_on) & SCTP_DEBUG_AUTH2)
#endif /* SCTP_DEBUG */
void
sctp_clear_chunklist(sctp_auth_chklist_t *chklist)
{
memset(chklist, 0, sizeof(*chklist));
/* chklist->num_chunks = 0; */
}
sctp_auth_chklist_t *
sctp_alloc_chunklist(void)
{
sctp_auth_chklist_t *chklist;
SCTP_MALLOC(chklist, sctp_auth_chklist_t *, sizeof(*chklist),
SCTP_M_AUTH_CL);
if (chklist == NULL) {
SCTPDBG(SCTP_DEBUG_AUTH1, "sctp_alloc_chunklist: failed to get memory!\n");
} else {
sctp_clear_chunklist(chklist);
}
return (chklist);
}
void
sctp_free_chunklist(sctp_auth_chklist_t *list)
{
if (list != NULL)
SCTP_FREE(list, SCTP_M_AUTH_CL);
}
sctp_auth_chklist_t *
sctp_copy_chunklist(sctp_auth_chklist_t *list)
{
sctp_auth_chklist_t *new_list;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_chunklist();
if (new_list == NULL)
return (NULL);
/* copy it */
memcpy(new_list, list, sizeof(*new_list));
return (new_list);
}
/*
* add a chunk to the required chunks list
*/
int
sctp_auth_add_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
/* is chunk restricted? */
if ((chunk == SCTP_INITIATION) ||
(chunk == SCTP_INITIATION_ACK) ||
(chunk == SCTP_SHUTDOWN_COMPLETE) ||
(chunk == SCTP_AUTHENTICATION)) {
return (-1);
}
if (list->chunks[chunk] == 0) {
list->chunks[chunk] = 1;
list->num_chunks++;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: added chunk %u (0x%02x) to Auth list\n",
chunk, chunk);
}
return (0);
}
/*
* delete a chunk from the required chunks list
*/
int
sctp_auth_delete_chunk(uint8_t chunk, sctp_auth_chklist_t *list)
{
if (list == NULL)
return (-1);
if (list->chunks[chunk] == 1) {
list->chunks[chunk] = 0;
list->num_chunks--;
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: deleted chunk %u (0x%02x) from Auth list\n",
chunk, chunk);
}
return (0);
}
size_t
sctp_auth_get_chklist_size(const sctp_auth_chklist_t *list)
{
if (list == NULL)
return (0);
else
return (list->num_chunks);
}
/*
* return the current number and list of required chunks caller must
* guarantee ptr has space for up to 256 bytes
*/
int
sctp_serialize_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, count = 0;
if (list == NULL)
return (0);
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
count++;
}
}
return (count);
}
int
sctp_pack_auth_chunks(const sctp_auth_chklist_t *list, uint8_t *ptr)
{
int i, size = 0;
if (list == NULL)
return (0);
if (list->num_chunks <= 32) {
/* just list them, one byte each */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
*ptr++ = i;
size++;
}
}
} else {
int index, offset;
/* pack into a 32 byte bitfield */
for (i = 0; i < 256; i++) {
if (list->chunks[i] != 0) {
index = i / 8;
offset = i % 8;
ptr[index] |= (1 << offset);
}
}
size = 32;
}
return (size);
}
int
sctp_unpack_auth_chunks(const uint8_t *ptr, uint8_t num_chunks,
sctp_auth_chklist_t *list)
{
int i;
int size;
if (list == NULL)
return (0);
if (num_chunks <= 32) {
/* just pull them, one byte each */
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(*ptr++, list);
}
size = num_chunks;
} else {
int index, offset;
/* unpack from a 32 byte bitfield */
for (index = 0; index < 32; index++) {
for (offset = 0; offset < 8; offset++) {
if (ptr[index] & (1 << offset)) {
(void)sctp_auth_add_chunk((index * 8) + offset, list);
}
}
}
size = 32;
}
return (size);
}
/*
* allocate structure space for a key of length keylen
*/
sctp_key_t *
sctp_alloc_key(uint32_t keylen)
{
sctp_key_t *new_key;
SCTP_MALLOC(new_key, sctp_key_t *, sizeof(*new_key) + keylen,
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
return (new_key);
}
void
sctp_free_key(sctp_key_t *key)
{
if (key != NULL)
SCTP_FREE(key,SCTP_M_AUTH_KY);
}
void
sctp_print_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
void
sctp_show_key(sctp_key_t *key, const char *str)
{
uint32_t i;
if (key == NULL) {
SCTP_PRINTF("%s: [Null key]\n", str);
return;
}
SCTP_PRINTF("%s: len %u, ", str, key->keylen);
if (key->keylen) {
for (i = 0; i < key->keylen; i++)
SCTP_PRINTF("%02x", key->key[i]);
SCTP_PRINTF("\n");
} else {
SCTP_PRINTF("[Null key]\n");
}
}
static uint32_t
sctp_get_keylen(sctp_key_t *key)
{
if (key != NULL)
return (key->keylen);
else
return (0);
}
/*
* generate a new random key of length 'keylen'
*/
sctp_key_t *
sctp_generate_random_key(uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
SCTP_READ_RANDOM(new_key->key, keylen);
new_key->keylen = keylen;
return (new_key);
}
sctp_key_t *
sctp_set_key(uint8_t *key, uint32_t keylen)
{
sctp_key_t *new_key;
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
memcpy(new_key->key, key, keylen);
return (new_key);
}
/*-
* given two keys of variable size, compute which key is "larger/smaller"
* returns: 1 if key1 > key2
* -1 if key1 < key2
* 0 if key1 = key2
*/
static int
sctp_compare_key(sctp_key_t *key1, sctp_key_t *key2)
{
uint32_t maxlen;
uint32_t i;
uint32_t key1len, key2len;
uint8_t *key_1, *key_2;
uint8_t val1, val2;
/* sanity/length check */
key1len = sctp_get_keylen(key1);
key2len = sctp_get_keylen(key2);
if ((key1len == 0) && (key2len == 0))
return (0);
else if (key1len == 0)
return (-1);
else if (key2len == 0)
return (1);
if (key1len < key2len) {
maxlen = key2len;
} else {
maxlen = key1len;
}
key_1 = key1->key;
key_2 = key2->key;
/* check for numeric equality */
for (i = 0; i < maxlen; i++) {
/* left-pad with zeros */
val1 = (i < (maxlen - key1len)) ? 0 : *(key_1++);
val2 = (i < (maxlen - key2len)) ? 0 : *(key_2++);
if (val1 > val2) {
return (1);
} else if (val1 < val2) {
return (-1);
}
}
/* keys are equal value, so check lengths */
if (key1len == key2len)
return (0);
else if (key1len < key2len)
return (-1);
else
return (1);
}
/*
* generate the concatenated keying material based on the two keys and the
* shared key (if available). draft-ietf-tsvwg-auth specifies the specific
* order for concatenation
*/
sctp_key_t *
sctp_compute_hashkey(sctp_key_t *key1, sctp_key_t *key2, sctp_key_t *shared)
{
uint32_t keylen;
sctp_key_t *new_key;
uint8_t *key_ptr;
keylen = sctp_get_keylen(key1) + sctp_get_keylen(key2) +
sctp_get_keylen(shared);
if (keylen > 0) {
/* get space for the new key */
new_key = sctp_alloc_key(keylen);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keylen = keylen;
key_ptr = new_key->key;
} else {
/* all keys empty/null?! */
return (NULL);
}
/* concatenate the keys */
if (sctp_compare_key(key1, key2) <= 0) {
/* key is shared + key1 + key2 */
if (sctp_get_keylen(shared)) {
memcpy(key_ptr, shared->key, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key1)) {
memcpy(key_ptr, key1->key, key1->keylen);
key_ptr += key1->keylen;
}
if (sctp_get_keylen(key2)) {
memcpy(key_ptr, key2->key, key2->keylen);
}
} else {
/* key is shared + key2 + key1 */
if (sctp_get_keylen(shared)) {
memcpy(key_ptr, shared->key, shared->keylen);
key_ptr += shared->keylen;
}
if (sctp_get_keylen(key2)) {
memcpy(key_ptr, key2->key, key2->keylen);
key_ptr += key2->keylen;
}
if (sctp_get_keylen(key1)) {
memcpy(key_ptr, key1->key, key1->keylen);
}
}
return (new_key);
}
sctp_sharedkey_t *
sctp_alloc_sharedkey(void)
{
sctp_sharedkey_t *new_key;
SCTP_MALLOC(new_key, sctp_sharedkey_t *, sizeof(*new_key),
SCTP_M_AUTH_KY);
if (new_key == NULL) {
/* out of memory */
return (NULL);
}
new_key->keyid = 0;
new_key->key = NULL;
new_key->refcount = 1;
new_key->deactivated = 0;
return (new_key);
}
void
sctp_free_sharedkey(sctp_sharedkey_t *skey)
{
if (skey == NULL)
return;
if (SCTP_DECREMENT_AND_CHECK_REFCOUNT(&skey->refcount)) {
if (skey->key != NULL)
sctp_free_key(skey->key);
SCTP_FREE(skey, SCTP_M_AUTH_KY);
}
}
sctp_sharedkey_t *
sctp_find_sharedkey(struct sctp_keyhead *shared_keys, uint16_t key_id)
{
sctp_sharedkey_t *skey;
LIST_FOREACH(skey, shared_keys, next) {
if (skey->keyid == key_id)
return (skey);
}
return (NULL);
}
int
sctp_insert_sharedkey(struct sctp_keyhead *shared_keys,
sctp_sharedkey_t *new_skey)
{
sctp_sharedkey_t *skey;
if ((shared_keys == NULL) || (new_skey == NULL))
return (EINVAL);
/* insert into an empty list? */
if (LIST_EMPTY(shared_keys)) {
LIST_INSERT_HEAD(shared_keys, new_skey, next);
return (0);
}
/* insert into the existing list, ordered by key id */
LIST_FOREACH(skey, shared_keys, next) {
if (new_skey->keyid < skey->keyid) {
/* insert it before here */
LIST_INSERT_BEFORE(skey, new_skey, next);
return (0);
} else if (new_skey->keyid == skey->keyid) {
/* replace the existing key */
/* verify this key *can* be replaced */
if ((skey->deactivated) || (skey->refcount > 1)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"can't replace shared key id %u\n",
new_skey->keyid);
return (EBUSY);
}
SCTPDBG(SCTP_DEBUG_AUTH1,
"replacing shared key id %u\n",
new_skey->keyid);
LIST_INSERT_BEFORE(skey, new_skey, next);
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey);
return (0);
}
if (LIST_NEXT(skey, next) == NULL) {
/* belongs at the end of the list */
LIST_INSERT_AFTER(skey, new_skey, next);
return (0);
}
}
/* shouldn't reach here */
return (EINVAL);
}
void
sctp_auth_key_acquire(struct sctp_tcb *stcb, uint16_t key_id)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* bump the ref count */
if (skey) {
atomic_add_int(&skey->refcount, 1);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount acquire to %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
}
}
void
sctp_auth_key_release(struct sctp_tcb *stcb, uint16_t key_id, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
sctp_sharedkey_t *skey;
/* find the shared key */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, key_id);
/* decrement the ref count */
if (skey) {
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u refcount release to %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
/* see if a notification should be generated */
if ((skey->refcount <= 2) && (skey->deactivated)) {
/* notify ULP that key is no longer used */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb,
key_id, 0, so_locked);
SCTPDBG(SCTP_DEBUG_AUTH2,
"%s: stcb %p key %u no longer used, %d\n",
__func__, (void *)stcb, key_id, skey->refcount);
}
sctp_free_sharedkey(skey);
}
}
static sctp_sharedkey_t *
sctp_copy_sharedkey(const sctp_sharedkey_t *skey)
{
sctp_sharedkey_t *new_skey;
if (skey == NULL)
return (NULL);
new_skey = sctp_alloc_sharedkey();
if (new_skey == NULL)
return (NULL);
if (skey->key != NULL)
new_skey->key = sctp_set_key(skey->key->key, skey->key->keylen);
else
new_skey->key = NULL;
new_skey->keyid = skey->keyid;
return (new_skey);
}
int
sctp_copy_skeylist(const struct sctp_keyhead *src, struct sctp_keyhead *dest)
{
sctp_sharedkey_t *skey, *new_skey;
int count = 0;
if ((src == NULL) || (dest == NULL))
return (0);
LIST_FOREACH(skey, src, next) {
new_skey = sctp_copy_sharedkey(skey);
if (new_skey != NULL) {
if (sctp_insert_sharedkey(dest, new_skey)) {
sctp_free_sharedkey(new_skey);
} else {
count++;
}
}
}
return (count);
}
sctp_hmaclist_t *
sctp_alloc_hmaclist(uint16_t num_hmacs)
{
sctp_hmaclist_t *new_list;
int alloc_size;
alloc_size = sizeof(*new_list) + num_hmacs * sizeof(new_list->hmac[0]);
SCTP_MALLOC(new_list, sctp_hmaclist_t *, alloc_size,
SCTP_M_AUTH_HL);
if (new_list == NULL) {
/* out of memory */
return (NULL);
}
new_list->max_algo = num_hmacs;
new_list->num_algo = 0;
return (new_list);
}
void
sctp_free_hmaclist(sctp_hmaclist_t *list)
{
if (list != NULL) {
SCTP_FREE(list,SCTP_M_AUTH_HL);
list = NULL;
}
}
int
sctp_auth_add_hmacid(sctp_hmaclist_t *list, uint16_t hmac_id)
{
int i;
if (list == NULL)
return (-1);
if (list->num_algo == list->max_algo) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: HMAC id list full, ignoring add %u\n", hmac_id);
return (-1);
}
#if defined(SCTP_SUPPORT_HMAC_SHA256)
if ((hmac_id != SCTP_AUTH_HMAC_ID_SHA1) &&
(hmac_id != SCTP_AUTH_HMAC_ID_SHA256)) {
#else
if (hmac_id != SCTP_AUTH_HMAC_ID_SHA1) {
#endif
return (-1);
}
/* Now is it already in the list */
for (i = 0; i < list->num_algo; i++) {
if (list->hmac[i] == hmac_id) {
/* already in list */
return (-1);
}
}
SCTPDBG(SCTP_DEBUG_AUTH1, "SCTP: add HMAC id %u to list\n", hmac_id);
list->hmac[list->num_algo++] = hmac_id;
return (0);
}
sctp_hmaclist_t *
sctp_copy_hmaclist(sctp_hmaclist_t *list)
{
sctp_hmaclist_t *new_list;
int i;
if (list == NULL)
return (NULL);
/* get a new list */
new_list = sctp_alloc_hmaclist(list->max_algo);
if (new_list == NULL)
return (NULL);
/* copy it */
new_list->max_algo = list->max_algo;
new_list->num_algo = list->num_algo;
for (i = 0; i < list->num_algo; i++)
new_list->hmac[i] = list->hmac[i];
return (new_list);
}
sctp_hmaclist_t *
sctp_default_supported_hmaclist(void)
{
sctp_hmaclist_t *new_list;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
new_list = sctp_alloc_hmaclist(2);
#else
new_list = sctp_alloc_hmaclist(1);
#endif
if (new_list == NULL)
return (NULL);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
/* We prefer SHA256, so list it first */
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA256);
#endif
(void)sctp_auth_add_hmacid(new_list, SCTP_AUTH_HMAC_ID_SHA1);
return (new_list);
}
/*-
* HMAC algos are listed in priority/preference order
* find the best HMAC id to use for the peer based on local support
*/
uint16_t
sctp_negotiate_hmacid(sctp_hmaclist_t *peer, sctp_hmaclist_t *local)
{
int i, j;
if ((local == NULL) || (peer == NULL))
return (SCTP_AUTH_HMAC_ID_RSVD);
for (i = 0; i < peer->num_algo; i++) {
for (j = 0; j < local->num_algo; j++) {
if (peer->hmac[i] == local->hmac[j]) {
/* found the "best" one */
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: negotiated peer HMAC id %u\n",
peer->hmac[i]);
return (peer->hmac[i]);
}
}
}
/* didn't find one! */
return (SCTP_AUTH_HMAC_ID_RSVD);
}
/*-
* serialize the HMAC algo list and return space used
* caller must guarantee ptr has appropriate space
*/
int
sctp_serialize_hmaclist(sctp_hmaclist_t *list, uint8_t *ptr)
{
int i;
uint16_t hmac_id;
if (list == NULL)
return (0);
for (i = 0; i < list->num_algo; i++) {
hmac_id = htons(list->hmac[i]);
memcpy(ptr, &hmac_id, sizeof(hmac_id));
ptr += sizeof(hmac_id);
}
return (list->num_algo * sizeof(hmac_id));
}
int
sctp_verify_hmac_param (struct sctp_auth_hmac_algo *hmacs, uint32_t num_hmacs)
{
uint32_t i;
for (i = 0; i < num_hmacs; i++) {
if (ntohs(hmacs->hmac_ids[i]) == SCTP_AUTH_HMAC_ID_SHA1) {
return (0);
}
}
return (-1);
}
sctp_authinfo_t *
sctp_alloc_authinfo(void)
{
sctp_authinfo_t *new_authinfo;
SCTP_MALLOC(new_authinfo, sctp_authinfo_t *, sizeof(*new_authinfo),
SCTP_M_AUTH_IF);
if (new_authinfo == NULL) {
/* out of memory */
return (NULL);
}
memset(new_authinfo, 0, sizeof(*new_authinfo));
return (new_authinfo);
}
void
sctp_free_authinfo(sctp_authinfo_t *authinfo)
{
if (authinfo == NULL)
return;
if (authinfo->random != NULL)
sctp_free_key(authinfo->random);
if (authinfo->peer_random != NULL)
sctp_free_key(authinfo->peer_random);
if (authinfo->assoc_key != NULL)
sctp_free_key(authinfo->assoc_key);
if (authinfo->recv_key != NULL)
sctp_free_key(authinfo->recv_key);
/* We are NOT dynamically allocating authinfo's right now... */
/* SCTP_FREE(authinfo, SCTP_M_AUTH_??); */
}
uint32_t
sctp_get_auth_chunk_len(uint16_t hmac_algo)
{
int size;
size = sizeof(struct sctp_auth_chunk) + sctp_get_hmac_digest_len(hmac_algo);
return (SCTP_SIZE32(size));
}
uint32_t
sctp_get_hmac_digest_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (SCTP_AUTH_DIGEST_LEN_SHA1);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (SCTP_AUTH_DIGEST_LEN_SHA256);
#endif
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
static inline int
sctp_get_hmac_block_len(uint16_t hmac_algo)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
return (64);
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
return (64);
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return (0);
} /* end switch */
}
#if defined(__Userspace__)
/* __Userspace__ SHA1_Init is defined in libcrypto.a (libssl-dev on Ubuntu) */
#endif
static void
sctp_hmac_init(uint16_t hmac_algo, sctp_hash_context_t *ctx)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_INIT(&ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_INIT(&ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_update(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *text, uint32_t textlen)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_UPDATE(&ctx->sha1, text, textlen);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_UPDATE(&ctx->sha256, text, textlen);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
static void
sctp_hmac_final(uint16_t hmac_algo, sctp_hash_context_t *ctx,
uint8_t *digest)
{
switch (hmac_algo) {
case SCTP_AUTH_HMAC_ID_SHA1:
SCTP_SHA1_FINAL(digest, &ctx->sha1);
break;
#if defined(SCTP_SUPPORT_HMAC_SHA256)
case SCTP_AUTH_HMAC_ID_SHA256:
SCTP_SHA256_FINAL(digest, &ctx->sha256);
break;
#endif
case SCTP_AUTH_HMAC_ID_RSVD:
default:
/* unknown HMAC algorithm: can't do anything */
return;
} /* end switch */
}
/*-
* Keyed-Hashing for Message Authentication: FIPS 198 (RFC 2104)
*
* Compute the HMAC digest using the desired hash key, text, and HMAC
* algorithm. Resulting digest is placed in 'digest' and digest length
* is returned, if the HMAC was performed.
*
* WARNING: it is up to the caller to supply sufficient space to hold the
* resultant digest.
*/
uint32_t
sctp_hmac(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
uint8_t *text, uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (text == NULL) ||
(textlen == 0) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
memset(ipad, 0, blocklen);
memset(opad, 0, blocklen);
memcpy(ipad, key, keylen);
memcpy(opad, key, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, text, textlen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/* mbuf version */
uint32_t
sctp_hmac_m(uint16_t hmac_algo, uint8_t *key, uint32_t keylen,
struct mbuf *m, uint32_t m_offset, uint8_t *digest, uint32_t trailer)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t ipad[128], opad[128]; /* keyed hash inner/outer pads */
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
uint32_t i;
struct mbuf *m_tmp;
/* sanity check the material and length */
if ((key == NULL) || (keylen == 0) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key, keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* set the hashed key as the key */
keylen = digestlen;
key = temp;
}
/* initialize the inner/outer pads with the key and "append" zeroes */
memset(ipad, 0, blocklen);
memset(opad, 0, blocklen);
memcpy(ipad, key, keylen);
memcpy(opad, key, keylen);
/* XOR the key with ipad and opad values */
for (i = 0; i < blocklen; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
/* perform inner hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, ipad, blocklen);
/* find the correct starting mbuf and offset (get start of text) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain for the text */
while (m_tmp != NULL) {
if ((SCTP_BUF_NEXT(m_tmp) == NULL) && trailer) {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - (trailer+m_offset));
} else {
sctp_hmac_update(hmac_algo, &ctx, mtod(m_tmp, uint8_t *) + m_offset,
SCTP_BUF_LEN(m_tmp) - m_offset);
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
sctp_hmac_final(hmac_algo, &ctx, temp);
/* perform outer hash */
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, opad, blocklen);
sctp_hmac_update(hmac_algo, &ctx, temp, digestlen);
sctp_hmac_final(hmac_algo, &ctx, digest);
return (digestlen);
}
/*
* computes the requested HMAC using a key struct (which may be modified if
* the keylen exceeds the HMAC block len).
*/
uint32_t
sctp_compute_hmac(uint16_t hmac_algo, sctp_key_t *key, uint8_t *text,
uint32_t textlen, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (text == NULL) || (textlen == 0) ||
(digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
memcpy(key->key, temp, key->keylen);
}
return (sctp_hmac(hmac_algo, key->key, key->keylen, text, textlen,
digest));
}
/* mbuf version */
uint32_t
sctp_compute_hmac_m(uint16_t hmac_algo, sctp_key_t *key, struct mbuf *m,
uint32_t m_offset, uint8_t *digest)
{
uint32_t digestlen;
uint32_t blocklen;
sctp_hash_context_t ctx;
uint8_t temp[SCTP_AUTH_DIGEST_LEN_MAX];
/* sanity check */
if ((key == NULL) || (m == NULL) || (digest == NULL)) {
/* can't do HMAC with empty key or text or digest store */
return (0);
}
/* validate the hmac algo and get the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_algo);
if (digestlen == 0)
return (0);
/* hash the key if it is longer than the hash block size */
blocklen = sctp_get_hmac_block_len(hmac_algo);
if (key->keylen > blocklen) {
sctp_hmac_init(hmac_algo, &ctx);
sctp_hmac_update(hmac_algo, &ctx, key->key, key->keylen);
sctp_hmac_final(hmac_algo, &ctx, temp);
/* save the hashed key as the new key */
key->keylen = digestlen;
memcpy(key->key, temp, key->keylen);
}
return (sctp_hmac_m(hmac_algo, key->key, key->keylen, m, m_offset, digest, 0));
}
int
sctp_auth_is_supported_hmac(sctp_hmaclist_t *list, uint16_t id)
{
int i;
if ((list == NULL) || (id == SCTP_AUTH_HMAC_ID_RSVD))
return (0);
for (i = 0; i < list->num_algo; i++)
if (list->hmac[i] == id)
return (1);
/* not in the list */
return (0);
}
/*-
* clear any cached key(s) if they match the given key id on an association.
* the cached key(s) will be recomputed and re-cached at next use.
* ASSUMES TCB_LOCK is already held
*/
void
sctp_clear_cachedkeys(struct sctp_tcb *stcb, uint16_t keyid)
{
if (stcb == NULL)
return;
if (keyid == stcb->asoc.authinfo.assoc_keyid) {
sctp_free_key(stcb->asoc.authinfo.assoc_key);
stcb->asoc.authinfo.assoc_key = NULL;
}
if (keyid == stcb->asoc.authinfo.recv_keyid) {
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key = NULL;
}
}
/*-
* clear any cached key(s) if they match the given key id for all assocs on
* an endpoint.
* ASSUMES INP_WLOCK is already held
*/
void
sctp_clear_cachedkeys_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
struct sctp_tcb *stcb;
if (inp == NULL)
return;
/* clear the cached keys on all assocs on this instance */
LIST_FOREACH(stcb, &inp->sctp_asoc_list, sctp_tcblist) {
SCTP_TCB_LOCK(stcb);
sctp_clear_cachedkeys(stcb, keyid);
SCTP_TCB_UNLOCK(stcb);
}
}
/*-
* delete a shared key from an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_delete_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount > 1)
return (-1);
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys(stcb, keyid);
return (0);
}
/*-
* deletes a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_delete_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
/* clear any cached keys */
sctp_clear_cachedkeys_ep(inp, keyid);
return (0);
}
/*-
* set the active key on an association
* ASSUMES TCB_LOCK is already held
*/
int
sctp_auth_setactivekey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey = NULL;
/* find the key on the assoc */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
if ((skey->deactivated) && (skey->refcount > 1)) {
/* can't reactivate a deactivated key with other refcounts */
return (-1);
}
/* set the (new) active key */
stcb->asoc.authinfo.active_keyid = keyid;
/* reset the deactivated flag */
skey->deactivated = 0;
return (0);
}
/*-
* set the active key on an endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_auth_setactivekey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
/* find the key */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL) {
/* that key doesn't exist */
return (-1);
}
inp->sctp_ep.default_keyid = keyid;
return (0);
}
/*-
* deactivates a shared key from the association
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey(struct sctp_tcb *stcb, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (stcb == NULL)
return (-1);
/* is the keyid the assoc active sending key */
if (keyid == stcb->asoc.authinfo.active_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* are there other refcount holders on the key? */
if (skey->refcount == 1) {
/* no other users, send a notification for this key */
sctp_ulp_notify(SCTP_NOTIFY_AUTH_FREE_KEY, stcb, keyid, 0,
SCTP_SO_LOCKED);
}
/* mark the key as deactivated */
skey->deactivated = 1;
return (0);
}
/*-
* deactivates a shared key from the endpoint
* ASSUMES INP_WLOCK is already held
*/
int
sctp_deact_sharedkey_ep(struct sctp_inpcb *inp, uint16_t keyid)
{
sctp_sharedkey_t *skey;
if (inp == NULL)
return (-1);
/* is the keyid the active sending key on the endpoint */
if (keyid == inp->sctp_ep.default_keyid)
return (-1);
/* does the key exist? */
skey = sctp_find_sharedkey(&inp->sctp_ep.shared_keys, keyid);
if (skey == NULL)
return (-1);
/* endpoint keys are not refcounted */
/* remove it */
LIST_REMOVE(skey, next);
sctp_free_sharedkey(skey); /* frees skey->key as well */
return (0);
}
/*
* get local authentication parameters from cookie (from INIT-ACK)
*/
void
sctp_auth_get_cookie_params(struct sctp_tcb *stcb, struct mbuf *m,
uint32_t offset, uint32_t length)
{
struct sctp_paramhdr *phdr, tmp_param;
uint16_t plen, ptype;
uint8_t random_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_random *p_random = NULL;
uint16_t random_len = 0;
uint8_t hmacs_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_hmac_algo *hmacs = NULL;
uint16_t hmacs_len = 0;
uint8_t chunks_store[SCTP_PARAM_BUFFER_SIZE];
struct sctp_auth_chunk_list *chunks = NULL;
uint16_t num_chunks = 0;
sctp_key_t *new_key;
uint32_t keylen;
/* convert to upper bound */
length += offset;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset,
sizeof(struct sctp_paramhdr), (uint8_t *)&tmp_param);
while (phdr != NULL) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if ((plen < sizeof(struct sctp_paramhdr)) ||
(offset + plen > length))
break;
if (ptype == SCTP_RANDOM) {
if (plen > sizeof(random_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)random_store, plen);
if (phdr == NULL)
return;
/* save the random and length for the key */
p_random = (struct sctp_auth_random *)phdr;
random_len = plen - sizeof(*p_random);
} else if (ptype == SCTP_HMAC_LIST) {
uint16_t num_hmacs;
uint16_t i;
if (plen > sizeof(hmacs_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)hmacs_store, plen);
if (phdr == NULL)
return;
/* save the hmacs list and num for the key */
hmacs = (struct sctp_auth_hmac_algo *)phdr;
hmacs_len = plen - sizeof(*hmacs);
num_hmacs = hmacs_len / sizeof(hmacs->hmac_ids[0]);
if (stcb->asoc.local_hmacs != NULL)
sctp_free_hmaclist(stcb->asoc.local_hmacs);
stcb->asoc.local_hmacs = sctp_alloc_hmaclist(num_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
for (i = 0; i < num_hmacs; i++) {
(void)sctp_auth_add_hmacid(stcb->asoc.local_hmacs,
ntohs(hmacs->hmac_ids[i]));
}
}
} else if (ptype == SCTP_CHUNK_LIST) {
int i;
if (plen > sizeof(chunks_store))
break;
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store, plen);
if (phdr == NULL)
return;
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
/* save chunks list and num for the key */
if (stcb->asoc.local_auth_chunks != NULL)
sctp_clear_chunklist(stcb->asoc.local_auth_chunks);
else
stcb->asoc.local_auth_chunks = sctp_alloc_chunklist();
for (i = 0; i < num_chunks; i++) {
(void)sctp_auth_add_chunk(chunks->chunk_types[i],
stcb->asoc.local_auth_chunks);
}
}
/* get next parameter */
offset += SCTP_SIZE32(plen);
if (offset + sizeof(struct sctp_paramhdr) > length)
break;
phdr = (struct sctp_paramhdr *)sctp_m_getptr(m, offset, sizeof(struct sctp_paramhdr),
(uint8_t *)&tmp_param);
}
/* concatenate the full random key */
keylen = sizeof(*p_random) + random_len + sizeof(*hmacs) + hmacs_len;
if (chunks != NULL) {
keylen += sizeof(*chunks) + num_chunks;
}
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
/* copy in the RANDOM */
if (p_random != NULL) {
keylen = sizeof(*p_random) + random_len;
memcpy(new_key->key, p_random, keylen);
} else {
keylen = 0;
}
/* append in the AUTH chunks */
if (chunks != NULL) {
memcpy(new_key->key + keylen, chunks,
sizeof(*chunks) + num_chunks);
keylen += sizeof(*chunks) + num_chunks;
}
/* append in the HMACs */
if (hmacs != NULL) {
memcpy(new_key->key + keylen, hmacs,
sizeof(*hmacs) + hmacs_len);
}
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.assoc_keyid);
sctp_clear_cachedkeys(stcb, stcb->asoc.authinfo.recv_keyid);
/* negotiate what HMAC to use for the peer */
stcb->asoc.peer_hmac_id = sctp_negotiate_hmacid(stcb->asoc.peer_hmacs,
stcb->asoc.local_hmacs);
/* copy defaults from the endpoint */
/* FIX ME: put in cookie? */
stcb->asoc.authinfo.active_keyid = stcb->sctp_ep->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&stcb->sctp_ep->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
}
/*
* compute and fill in the HMAC digest for a packet
*/
void
sctp_fill_hmac_digest_m(struct mbuf *m, uint32_t auth_offset,
struct sctp_auth_chunk *auth, struct sctp_tcb *stcb, uint16_t keyid)
{
uint32_t digestlen;
sctp_sharedkey_t *skey;
sctp_key_t *key;
if ((stcb == NULL) || (auth == NULL))
return;
/* zero the digest + chunk padding */
digestlen = sctp_get_hmac_digest_len(stcb->asoc.peer_hmac_id);
memset(auth->hmac, 0, SCTP_SIZE32(digestlen));
/* is the desired key cached? */
if ((keyid != stcb->asoc.authinfo.assoc_keyid) ||
(stcb->asoc.authinfo.assoc_key == NULL)) {
if (stcb->asoc.authinfo.assoc_key != NULL) {
/* free the old cached key */
sctp_free_key(stcb->asoc.authinfo.assoc_key);
}
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys, keyid);
/* the only way skey is NULL is if null key id 0 is used */
if (skey != NULL)
key = skey->key;
else
key = NULL;
/* compute a new assoc key and cache it */
stcb->asoc.authinfo.assoc_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, key);
stcb->asoc.authinfo.assoc_keyid = keyid;
SCTPDBG(SCTP_DEBUG_AUTH1, "caching key id %u\n",
stcb->asoc.authinfo.assoc_keyid);
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.assoc_key,
"Assoc Key");
#endif
}
/* set in the active key id */
auth->shared_key_id = htons(keyid);
/* compute and fill in the digest */
(void)sctp_compute_hmac_m(stcb->asoc.peer_hmac_id, stcb->asoc.authinfo.assoc_key,
m, auth_offset, auth->hmac);
}
static void
sctp_zero_m(struct mbuf *m, uint32_t m_offset, uint32_t size)
{
struct mbuf *m_tmp;
uint8_t *data;
/* sanity check */
if (m == NULL)
return;
/* find the correct starting mbuf and offset (get start position) */
m_tmp = m;
while ((m_tmp != NULL) && (m_offset >= (uint32_t) SCTP_BUF_LEN(m_tmp))) {
m_offset -= SCTP_BUF_LEN(m_tmp);
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
/* now use the rest of the mbuf chain */
while ((m_tmp != NULL) && (size > 0)) {
data = mtod(m_tmp, uint8_t *) + m_offset;
if (size > (uint32_t)(SCTP_BUF_LEN(m_tmp) - m_offset)) {
memset(data, 0, SCTP_BUF_LEN(m_tmp) - m_offset);
size -= SCTP_BUF_LEN(m_tmp) - m_offset;
} else {
memset(data, 0, size);
size = 0;
}
/* clear the offset since it's only for the first mbuf */
m_offset = 0;
m_tmp = SCTP_BUF_NEXT(m_tmp);
}
}
/*-
* process the incoming Authentication chunk
* return codes:
* -1 on any authentication error
* 0 on authentication verification
*/
int
sctp_handle_auth(struct sctp_tcb *stcb, struct sctp_auth_chunk *auth,
struct mbuf *m, uint32_t offset)
{
uint16_t chunklen;
uint16_t shared_key_id;
uint16_t hmac_id;
sctp_sharedkey_t *skey;
uint32_t digestlen;
uint8_t digest[SCTP_AUTH_DIGEST_LEN_MAX];
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
/* auth is checked for NULL by caller */
chunklen = ntohs(auth->ch.chunk_length);
if (chunklen < sizeof(*auth)) {
SCTP_STAT_INCR(sctps_recvauthfailed);
return (-1);
}
SCTP_STAT_INCR(sctps_recvauth);
/* get the auth params */
shared_key_id = ntohs(auth->shared_key_id);
hmac_id = ntohs(auth->hmac_id);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP AUTH Chunk: shared key %u, HMAC id %u\n",
shared_key_id, hmac_id);
/* is the indicated HMAC supported? */
if (!sctp_auth_is_supported_hmac(stcb->asoc.local_hmacs, hmac_id)) {
struct mbuf *op_err;
struct sctp_error_auth_invalid_hmac *cause;
SCTP_STAT_INCR(sctps_recvivalhmacid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unsupported HMAC id %u\n",
hmac_id);
/*
* report this in an Error Chunk: Unsupported HMAC
* Identifier
*/
op_err = sctp_get_mbuf_for_msg(sizeof(struct sctp_error_auth_invalid_hmac),
0, M_NOWAIT, 1, MT_HEADER);
if (op_err != NULL) {
/* pre-reserve some space */
SCTP_BUF_RESV_UF(op_err, sizeof(struct sctp_chunkhdr));
/* fill in the error */
cause = mtod(op_err, struct sctp_error_auth_invalid_hmac *);
cause->cause.code = htons(SCTP_CAUSE_UNSUPPORTED_HMACID);
cause->cause.length = htons(sizeof(struct sctp_error_auth_invalid_hmac));
cause->hmac_id = ntohs(hmac_id);
SCTP_BUF_LEN(op_err) = sizeof(struct sctp_error_auth_invalid_hmac);
/* queue it */
sctp_queue_op_err(stcb, op_err);
}
return (-1);
}
/* get the indicated shared key, if available */
if ((stcb->asoc.authinfo.recv_key == NULL) ||
(stcb->asoc.authinfo.recv_keyid != shared_key_id)) {
/* find the shared key on the assoc first */
skey = sctp_find_sharedkey(&stcb->asoc.shared_keys,
shared_key_id);
/* if the shared key isn't found, discard the chunk */
if (skey == NULL) {
SCTP_STAT_INCR(sctps_recvivalkeyid);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: unknown key id %u\n",
shared_key_id);
return (-1);
}
/* generate a notification if this is a new key id */
if (stcb->asoc.authinfo.recv_keyid != shared_key_id)
/*
* sctp_ulp_notify(SCTP_NOTIFY_AUTH_NEW_KEY, stcb,
* shared_key_id, (void
* *)stcb->asoc.authinfo.recv_keyid);
*/
sctp_notify_authentication(stcb, SCTP_AUTH_NEW_KEY,
shared_key_id, stcb->asoc.authinfo.recv_keyid,
SCTP_SO_NOT_LOCKED);
/* compute a new recv assoc key and cache it */
if (stcb->asoc.authinfo.recv_key != NULL)
sctp_free_key(stcb->asoc.authinfo.recv_key);
stcb->asoc.authinfo.recv_key =
sctp_compute_hashkey(stcb->asoc.authinfo.random,
stcb->asoc.authinfo.peer_random, skey->key);
stcb->asoc.authinfo.recv_keyid = shared_key_id;
#ifdef SCTP_DEBUG
if (SCTP_AUTH_DEBUG)
sctp_print_key(stcb->asoc.authinfo.recv_key, "Recv Key");
#endif
}
/* validate the digest length */
digestlen = sctp_get_hmac_digest_len(hmac_id);
if (chunklen < (sizeof(*auth) + digestlen)) {
/* invalid digest length */
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: chunk too short for HMAC\n");
return (-1);
}
/* save a copy of the digest, zero the pseudo header, and validate */
memcpy(digest, auth->hmac, digestlen);
sctp_zero_m(m, offset + sizeof(*auth), SCTP_SIZE32(digestlen));
(void)sctp_compute_hmac_m(hmac_id, stcb->asoc.authinfo.recv_key,
m, offset, computed_digest);
#if defined(__Userspace__)
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
return (0);
#endif
#endif
/* compare the computed digest with the one in the AUTH chunk */
if (timingsafe_bcmp(digest, computed_digest, digestlen) != 0) {
SCTP_STAT_INCR(sctps_recvauthfailed);
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP Auth: HMAC digest check failed\n");
return (-1);
}
return (0);
}
/*
* Generate NOTIFICATION
*/
void
sctp_notify_authentication(struct sctp_tcb *stcb, uint32_t indication,
uint16_t keyid, uint16_t alt_keyid, int so_locked
#if !defined(__APPLE__) && !defined(SCTP_SO_LOCK_TESTING)
SCTP_UNUSED
#endif
)
{
struct mbuf *m_notify;
struct sctp_authkey_event *auth;
struct sctp_queued_to_read *control;
if ((stcb == NULL) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_GONE) ||
(stcb->sctp_ep->sctp_flags & SCTP_PCB_FLAGS_SOCKET_ALLGONE) ||
(stcb->asoc.state & SCTP_STATE_CLOSED_SOCKET)
) {
/* If the socket is gone we are out of here */
return;
}
if (sctp_stcb_is_feature_off(stcb->sctp_ep, stcb, SCTP_PCB_FLAGS_AUTHEVNT))
/* event not enabled */
return;
m_notify = sctp_get_mbuf_for_msg(sizeof(struct sctp_authkey_event),
0, M_NOWAIT, 1, MT_HEADER);
if (m_notify == NULL)
/* no space left */
return;
SCTP_BUF_LEN(m_notify) = 0;
auth = mtod(m_notify, struct sctp_authkey_event *);
memset(auth, 0, sizeof(struct sctp_authkey_event));
auth->auth_type = SCTP_AUTHENTICATION_EVENT;
auth->auth_flags = 0;
auth->auth_length = sizeof(*auth);
auth->auth_keynumber = keyid;
auth->auth_altkeynumber = alt_keyid;
auth->auth_indication = indication;
auth->auth_assoc_id = sctp_get_associd(stcb);
SCTP_BUF_LEN(m_notify) = sizeof(*auth);
SCTP_BUF_NEXT(m_notify) = NULL;
/* append to socket */
control = sctp_build_readq_entry(stcb, stcb->asoc.primary_destination,
0, 0, stcb->asoc.context, 0, 0, 0, m_notify);
if (control == NULL) {
/* no memory */
sctp_m_freem(m_notify);
return;
}
control->length = SCTP_BUF_LEN(m_notify);
control->spec_flags = M_NOTIFICATION;
/* not that we need this */
control->tail_mbuf = m_notify;
sctp_add_to_readq(stcb->sctp_ep, stcb, control,
&stcb->sctp_socket->so_rcv, 1, SCTP_READ_LOCK_NOT_HELD, so_locked);
}
/*-
* validates the AUTHentication related parameters in an INIT/INIT-ACK
* Note: currently only used for INIT as INIT-ACK is handled inline
* with sctp_load_addresses_from_init()
*/
int
sctp_validate_init_auth_params(struct mbuf *m, int offset, int limit)
{
struct sctp_paramhdr *phdr, param_buf;
uint16_t ptype, plen;
int peer_supports_asconf = 0;
int peer_supports_auth = 0;
int got_random = 0, got_hmacs = 0, got_chklist = 0;
uint8_t saw_asconf = 0;
uint8_t saw_asconf_ack = 0;
/* go through each of the params. */
phdr = sctp_get_next_param(m, offset, ¶m_buf, sizeof(param_buf));
while (phdr) {
ptype = ntohs(phdr->param_type);
plen = ntohs(phdr->param_length);
if (offset + plen > limit) {
break;
}
if (plen < sizeof(struct sctp_paramhdr)) {
break;
}
if (ptype == SCTP_SUPPORTED_CHUNK_EXT) {
/* A supported extension chunk */
struct sctp_supported_chunk_types_param *pr_supported;
uint8_t local_store[SCTP_SMALL_CHUNK_STORE];
int num_ent, i;
if (plen > sizeof(local_store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)&local_store,
plen);
if (phdr == NULL) {
return (-1);
}
pr_supported = (struct sctp_supported_chunk_types_param *)phdr;
num_ent = plen - sizeof(struct sctp_paramhdr);
for (i = 0; i < num_ent; i++) {
switch (pr_supported->chunk_types[i]) {
case SCTP_ASCONF:
case SCTP_ASCONF_ACK:
peer_supports_asconf = 1;
break;
default:
/* one we don't care about */
break;
}
}
} else if (ptype == SCTP_RANDOM) {
/* enforce the random length */
if (plen != (sizeof(struct sctp_auth_random) +
SCTP_AUTH_RANDOM_SIZE_REQUIRED)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid RANDOM len\n");
return (-1);
}
got_random = 1;
} else if (ptype == SCTP_HMAC_LIST) {
struct sctp_auth_hmac_algo *hmacs;
uint8_t store[SCTP_PARAM_BUFFER_SIZE];
int num_hmacs;
if (plen > sizeof(store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)store,
plen);
if (phdr == NULL) {
return (-1);
}
hmacs = (struct sctp_auth_hmac_algo *)phdr;
num_hmacs = (plen - sizeof(*hmacs)) / sizeof(hmacs->hmac_ids[0]);
/* validate the hmac list */
if (sctp_verify_hmac_param(hmacs, num_hmacs)) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: invalid HMAC param\n");
return (-1);
}
got_hmacs = 1;
} else if (ptype == SCTP_CHUNK_LIST) {
struct sctp_auth_chunk_list *chunks;
uint8_t chunks_store[SCTP_SMALL_CHUNK_STORE];
int i, num_chunks;
if (plen > sizeof(chunks_store)) {
break;
}
phdr = sctp_get_next_param(m, offset,
(struct sctp_paramhdr *)chunks_store,
plen);
if (phdr == NULL) {
return (-1);
}
/*-
* Flip through the list and mark that the
* peer supports asconf/asconf_ack.
*/
chunks = (struct sctp_auth_chunk_list *)phdr;
num_chunks = plen - sizeof(*chunks);
for (i = 0; i < num_chunks; i++) {
/* record asconf/asconf-ack if listed */
if (chunks->chunk_types[i] == SCTP_ASCONF)
saw_asconf = 1;
if (chunks->chunk_types[i] == SCTP_ASCONF_ACK)
saw_asconf_ack = 1;
}
if (num_chunks)
got_chklist = 1;
}
offset += SCTP_SIZE32(plen);
if (offset >= limit) {
break;
}
phdr = sctp_get_next_param(m, offset, ¶m_buf,
sizeof(param_buf));
}
/* validate authentication required parameters */
if (got_random && got_hmacs) {
peer_supports_auth = 1;
} else {
peer_supports_auth = 0;
}
if (!peer_supports_auth && got_chklist) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer sent chunk list w/o AUTH\n");
return (-1);
}
if (peer_supports_asconf && !peer_supports_auth) {
SCTPDBG(SCTP_DEBUG_AUTH1,
"SCTP: peer supports ASCONF but not AUTH\n");
return (-1);
} else if ((peer_supports_asconf) && (peer_supports_auth) &&
((saw_asconf == 0) || (saw_asconf_ack == 0))) {
return (-2);
}
return (0);
}
void
sctp_initialize_auth_params(struct sctp_inpcb *inp, struct sctp_tcb *stcb)
{
uint16_t chunks_len = 0;
uint16_t hmacs_len = 0;
uint16_t random_len = SCTP_AUTH_RANDOM_SIZE_DEFAULT;
sctp_key_t *new_key;
uint16_t keylen;
/* initialize hmac list from endpoint */
stcb->asoc.local_hmacs = sctp_copy_hmaclist(inp->sctp_ep.local_hmacs);
if (stcb->asoc.local_hmacs != NULL) {
hmacs_len = stcb->asoc.local_hmacs->num_algo *
sizeof(stcb->asoc.local_hmacs->hmac[0]);
}
/* initialize auth chunks list from endpoint */
stcb->asoc.local_auth_chunks =
sctp_copy_chunklist(inp->sctp_ep.local_auth_chunks);
if (stcb->asoc.local_auth_chunks != NULL) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
chunks_len++;
}
}
/* copy defaults from the endpoint */
stcb->asoc.authinfo.active_keyid = inp->sctp_ep.default_keyid;
/* copy out the shared key list (by reference) from the endpoint */
(void)sctp_copy_skeylist(&inp->sctp_ep.shared_keys,
&stcb->asoc.shared_keys);
/* now set the concatenated key (random + chunks + hmacs) */
/* key includes parameter headers */
keylen = (3 * sizeof(struct sctp_paramhdr)) + random_len + chunks_len +
hmacs_len;
new_key = sctp_alloc_key(keylen);
if (new_key != NULL) {
struct sctp_paramhdr *ph;
int plen;
/* generate and copy in the RANDOM */
ph = (struct sctp_paramhdr *)new_key->key;
ph->param_type = htons(SCTP_RANDOM);
plen = sizeof(*ph) + random_len;
ph->param_length = htons(plen);
SCTP_READ_RANDOM(new_key->key + sizeof(*ph), random_len);
keylen = plen;
/* append in the AUTH chunks */
/* NOTE: currently we always have chunks to list */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_CHUNK_LIST);
plen = sizeof(*ph) + chunks_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
if (stcb->asoc.local_auth_chunks) {
int i;
for (i = 0; i < 256; i++) {
if (stcb->asoc.local_auth_chunks->chunks[i])
new_key->key[keylen++] = i;
}
}
/* append in the HMACs */
ph = (struct sctp_paramhdr *)(new_key->key + keylen);
ph->param_type = htons(SCTP_HMAC_LIST);
plen = sizeof(*ph) + hmacs_len;
ph->param_length = htons(plen);
keylen += sizeof(*ph);
(void)sctp_serialize_hmaclist(stcb->asoc.local_hmacs,
new_key->key + keylen);
}
if (stcb->asoc.authinfo.random != NULL)
sctp_free_key(stcb->asoc.authinfo.random);
stcb->asoc.authinfo.random = new_key;
stcb->asoc.authinfo.random_len = random_len;
}
#ifdef SCTP_HMAC_TEST
/*
* HMAC and key concatenation tests
*/
static void
sctp_print_digest(uint8_t *digest, uint32_t digestlen, const char *str)
{
uint32_t i;
SCTP_PRINTF("\n%s: 0x", str);
if (digest == NULL)
return;
for (i = 0; i < digestlen; i++)
SCTP_PRINTF("%02x", digest[i]);
}
static int
sctp_test_hmac(const char *str, uint16_t hmac_id, uint8_t *key,
uint32_t keylen, uint8_t *text, uint32_t textlen,
uint8_t *digest, uint32_t digestlen)
{
uint8_t computed_digest[SCTP_AUTH_DIGEST_LEN_MAX];
SCTP_PRINTF("\n%s:", str);
sctp_hmac(hmac_id, key, keylen, text, textlen, computed_digest);
sctp_print_digest(digest, digestlen, "Expected digest");
sctp_print_digest(computed_digest, digestlen, "Computed digest");
if (memcmp(digest, computed_digest, digestlen) != 0) {
SCTP_PRINTF("\nFAILED");
return (-1);
} else {
SCTP_PRINTF("\nPASSED");
return (0);
}
}
/*
* RFC 2202: HMAC-SHA1 test cases
*/
void
sctp_test_hmac_sha1(void)
{
uint8_t *digest;
uint8_t key[128];
uint32_t keylen;
uint8_t text[128];
uint32_t textlen;
uint32_t digestlen = 20;
int failed = 0;
/*-
* test_case = 1
* key = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
* key_len = 20
* data = "Hi There"
* data_len = 8
* digest = 0xb617318655057264e28bc0b6fb378c8ef146be00
*/
keylen = 20;
memset(key, 0x0b, keylen);
textlen = 8;
strcpy(text, "Hi There");
digest = "\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00";
if (sctp_test_hmac("SHA1 test case 1", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 2
* key = "Jefe"
* key_len = 4
* data = "what do ya want for nothing?"
* data_len = 28
* digest = 0xeffcdf6ae5eb2fa2d27416d5f184df9c259a7c79
*/
keylen = 4;
strcpy(key, "Jefe");
textlen = 28;
strcpy(text, "what do ya want for nothing?");
digest = "\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79";
if (sctp_test_hmac("SHA1 test case 2", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 3
* key = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
* key_len = 20
* data = 0xdd repeated 50 times
* data_len = 50
* digest = 0x125d7342b9ac11cd91a39af48aa17b4f63f175d3
*/
keylen = 20;
memset(key, 0xaa, keylen);
textlen = 50;
memset(text, 0xdd, textlen);
digest = "\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3";
if (sctp_test_hmac("SHA1 test case 3", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 4
* key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
* key_len = 25
* data = 0xcd repeated 50 times
* data_len = 50
* digest = 0x4c9007f4026250c6bc8414f9bf50c86c2d7235da
*/
keylen = 25;
memcpy(key, "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19", keylen);
textlen = 50;
memset(text, 0xcd, textlen);
digest = "\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda";
if (sctp_test_hmac("SHA1 test case 4", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 5
* key = 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
* key_len = 20
* data = "Test With Truncation"
* data_len = 20
* digest = 0x4c1a03424b55e07fe7f27be1d58bb9324a9a5a04
* digest-96 = 0x4c1a03424b55e07fe7f27be1
*/
keylen = 20;
memset(key, 0x0c, keylen);
textlen = 20;
strcpy(text, "Test With Truncation");
digest = "\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04";
if (sctp_test_hmac("SHA1 test case 5", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 6
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key - Hash Key First"
* data_len = 54
* digest = 0xaa4ae5e15272d00e95705637ce8a3b55ed402112
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 54;
strcpy(text, "Test Using Larger Than Block-Size Key - Hash Key First");
digest = "\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12";
if (sctp_test_hmac("SHA1 test case 6", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/*-
* test_case = 7
* key = 0xaa repeated 80 times
* key_len = 80
* data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"
* data_len = 73
* digest = 0xe8e99d0f45237d786d6bbaa7965c7808bbff1a91
*/
keylen = 80;
memset(key, 0xaa, keylen);
textlen = 73;
strcpy(text, "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
digest = "\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91";
if (sctp_test_hmac("SHA1 test case 7", SCTP_AUTH_HMAC_ID_SHA1, key, keylen,
text, textlen, digest, digestlen) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nSHA1 test results: %d cases failed", failed);
else
SCTP_PRINTF("\nSHA1 test results: all test cases passed");
}
/*
* test assoc key concatenation
*/
static int
sctp_test_key_concatenation(sctp_key_t *key1, sctp_key_t *key2,
sctp_key_t *expected_key)
{
sctp_key_t *key;
int ret_val;
sctp_show_key(key1, "\nkey1");
sctp_show_key(key2, "\nkey2");
key = sctp_compute_hashkey(key1, key2, NULL);
sctp_show_key(expected_key, "\nExpected");
sctp_show_key(key, "\nComputed");
if (memcmp(key, expected_key, expected_key->keylen) != 0) {
SCTP_PRINTF("\nFAILED");
ret_val = -1;
} else {
SCTP_PRINTF("\nPASSED");
ret_val = 0;
}
sctp_free_key(key1);
sctp_free_key(key2);
sctp_free_key(expected_key);
sctp_free_key(key);
return (ret_val);
}
void
sctp_test_authkey(void)
{
sctp_key_t *key1, *key2, *expected_key;
int failed = 0;
/* test case 1 */
key1 = sctp_set_key("\x01\x01\x01\x01", 4);
key2 = sctp_set_key("\x01\x02\x03\x04", 4);
expected_key = sctp_set_key("\x01\x01\x01\x01\x01\x02\x03\x04", 8);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 2 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x02", 1);
expected_key = sctp_set_key("\x00\x00\x00\x01\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 3 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x02", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x02", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 4 */
key1 = sctp_set_key("\x00\x00\x00\x01", 4);
key2 = sctp_set_key("\x01", 1);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 5 */
key1 = sctp_set_key("\x01", 1);
key2 = sctp_set_key("\x00\x00\x00\x01", 4);
expected_key = sctp_set_key("\x01\x00\x00\x00\x01", 5);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 6 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* test case 7 */
key1 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 11);
key2 = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07", 11);
expected_key = sctp_set_key("\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x08", 22);
if (sctp_test_key_concatenation(key1, key2, expected_key) < 0)
failed++;
/* done with all tests */
if (failed)
SCTP_PRINTF("\nKey concatenation test results: %d cases failed", failed);
else
SCTP_PRINTF("\nKey concatenation test results: all test cases passed");
}
#if defined(STANDALONE_HMAC_TEST)
int
main(void)
{
sctp_test_hmac_sha1();
sctp_test_authkey();
}
#endif /* STANDALONE_HMAC_TEST */
#endif /* SCTP_HMAC_TEST */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1370_0 |
crossvul-cpp_data_good_270_2 | /*
* rdbmp.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1994-1996, Thomas G. Lane.
* Modified 2009-2017 by Guido Vollbeding.
* libjpeg-turbo Modifications:
* Modified 2011 by Siarhei Siamashka.
* Copyright (C) 2015, 2017-2018, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains routines to read input images in Microsoft "BMP"
* format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors).
* Currently, only 8-bit and 24-bit images are supported, not 1-bit or
* 4-bit (feeding such low-depth images into JPEG would be silly anyway).
* Also, we don't support RLE-compressed files.
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed BMP format).
*
* This code contributed by James Arthur Boucher.
*/
#include "cmyk.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef BMP_SUPPORTED
/* Macros to deal with unsigned chars as efficiently as compiler allows */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char U_CHAR;
#define UCH(x) ((int)(x))
#else /* !HAVE_UNSIGNED_CHAR */
#ifdef __CHAR_UNSIGNED__
typedef char U_CHAR;
#define UCH(x) ((int)(x))
#else
typedef char U_CHAR;
#define UCH(x) ((int)(x) & 0xFF)
#endif
#endif /* HAVE_UNSIGNED_CHAR */
#define ReadOK(file, buffer, len) \
(JFREAD(file, buffer, len) == ((size_t)(len)))
static int alpha_index[JPEG_NUMCS] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1
};
/* Private version of data source object */
typedef struct _bmp_source_struct *bmp_source_ptr;
typedef struct _bmp_source_struct {
struct cjpeg_source_struct pub; /* public fields */
j_compress_ptr cinfo; /* back link saves passing separate parm */
JSAMPARRAY colormap; /* BMP colormap (converted to my format) */
jvirt_sarray_ptr whole_image; /* Needed to reverse row order */
JDIMENSION source_row; /* Current source row number */
JDIMENSION row_width; /* Physical width of scanlines in file */
int bits_per_pixel; /* remembers 8- or 24-bit format */
int cmap_length; /* colormap length */
boolean use_inversion_array; /* TRUE = preload the whole image, which is
stored in bottom-up order, and feed it to
the calling program in top-down order
FALSE = the calling program will maintain
its own image buffer and read the rows in
bottom-up order */
U_CHAR *iobuffer; /* I/O buffer (used to buffer a single row from
disk if use_inversion_array == FALSE) */
} bmp_source_struct;
LOCAL(int)
read_byte(bmp_source_ptr sinfo)
/* Read next byte from BMP file */
{
register FILE *infile = sinfo->pub.input_file;
register int c;
if ((c = getc(infile)) == EOF)
ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
return c;
}
LOCAL(void)
read_colormap(bmp_source_ptr sinfo, int cmaplen, int mapentrysize)
/* Read the colormap from a BMP file */
{
int i, gray = 1;
switch (mapentrysize) {
case 3:
/* BGR format (occurs in OS/2 files) */
for (i = 0; i < cmaplen; i++) {
sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo);
if (sinfo->colormap[2][i] != sinfo->colormap[1][i] ||
sinfo->colormap[1][i] != sinfo->colormap[0][i])
gray = 0;
}
break;
case 4:
/* BGR0 format (occurs in MS Windows files) */
for (i = 0; i < cmaplen; i++) {
sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo);
(void)read_byte(sinfo);
if (sinfo->colormap[2][i] != sinfo->colormap[1][i] ||
sinfo->colormap[1][i] != sinfo->colormap[0][i])
gray = 0;
}
break;
default:
ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP);
break;
}
if (sinfo->cinfo->in_color_space == JCS_UNKNOWN && gray)
sinfo->cinfo->in_color_space = JCS_GRAYSCALE;
if (sinfo->cinfo->in_color_space == JCS_GRAYSCALE && !gray)
ERREXIT(sinfo->cinfo, JERR_BAD_IN_COLORSPACE);
}
/*
* Read one row of pixels.
* The image has been read into the whole_image array, but is otherwise
* unprocessed. We must read it out in top-to-bottom row order, and if
* it is an 8-bit image, we must expand colormapped pixels to 24bit format.
*/
METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
int cmaplen = source->cmap_length;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
if (t >= cmaplen)
ERREXIT(cinfo, JERR_BMP_OUTOFRANGE);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_24bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 24-bit pixels */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
JSAMPARRAY image_ptr;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Transfer data. Note source values are in BGR order
* (even though Microsoft's own documents say the opposite).
*/
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_EXT_BGR) {
MEMCOPY(outptr, inptr, source->row_width);
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
/* can omit GETJSAMPLE() safely */
JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++;
rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr += ps;
}
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_32bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 32-bit pixels */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
JSAMPARRAY image_ptr;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Transfer data. Note source values are in BGR order
* (even though Microsoft's own documents say the opposite).
*/
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_EXT_BGRX ||
cinfo->in_color_space == JCS_EXT_BGRA) {
MEMCOPY(outptr, inptr, source->row_width);
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
/* can omit GETJSAMPLE() safely */
JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++;
rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3);
inptr++; /* skip the 4th byte (Alpha channel) */
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr[aindex] = *inptr++;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
inptr++; /* skip the 4th byte (Alpha channel) */
outptr += ps;
}
}
}
return 1;
}
/*
* This method loads the image into whole_image during the first call on
* get_pixel_rows. The get_pixel_rows pointer is then adjusted to call
* get_8bit_row, get_24bit_row, or get_32bit_row on subsequent calls.
*/
METHODDEF(JDIMENSION)
preload_image(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register FILE *infile = source->pub.input_file;
register JSAMPROW out_ptr;
JSAMPARRAY image_ptr;
JDIMENSION row;
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
/* Read the data into a virtual array in input-file row order. */
for (row = 0; row < cinfo->image_height; row++) {
if (progress != NULL) {
progress->pub.pass_counter = (long)row;
progress->pub.pass_limit = (long)cinfo->image_height;
(*progress->pub.progress_monitor) ((j_common_ptr)cinfo);
}
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image, row, (JDIMENSION)1, TRUE);
out_ptr = image_ptr[0];
if (fread(out_ptr, 1, source->row_width, infile) != source->row_width) {
if (feof(infile))
ERREXIT(cinfo, JERR_INPUT_EOF);
else
ERREXIT(cinfo, JERR_FILE_READ);
}
}
if (progress != NULL)
progress->completed_extra_passes++;
/* Set up to read from the virtual array in top-to-bottom order */
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
source->source_row = cinfo->image_height;
/* And read the first row */
return (*source->pub.get_pixel_rows) (cinfo, sinfo);
}
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
U_CHAR bmpfileheader[14];
U_CHAR bmpinfoheader[64];
#define GET_2B(array, offset) \
((unsigned short)UCH(array[offset]) + \
(((unsigned short)UCH(array[offset + 1])) << 8))
#define GET_4B(array, offset) \
((unsigned int)UCH(array[offset]) + \
(((unsigned int)UCH(array[offset + 1])) << 8) + \
(((unsigned int)UCH(array[offset + 2])) << 16) + \
(((unsigned int)UCH(array[offset + 3])) << 24))
unsigned int bfOffBits;
unsigned int headerSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned int biCompression;
int biXPelsPerMeter, biYPelsPerMeter;
unsigned int biClrUsed = 0;
int mapentrysize = 0; /* 0 indicates no colormap */
int bPad;
JDIMENSION row_width = 0;
/* Read and verify the bitmap file header */
if (!ReadOK(source->pub.input_file, bmpfileheader, 14))
ERREXIT(cinfo, JERR_INPUT_EOF);
if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */
ERREXIT(cinfo, JERR_BMP_NOT);
bfOffBits = GET_4B(bmpfileheader, 10);
/* We ignore the remaining fileheader fields */
/* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
* or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which.
*/
if (!ReadOK(source->pub.input_file, bmpinfoheader, 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
headerSize = GET_4B(bmpinfoheader, 0);
if (headerSize < 12 || headerSize > 64)
ERREXIT(cinfo, JERR_BMP_BADHEADER);
if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
switch (headerSize) {
case 12:
/* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
biWidth = (int)GET_2B(bmpinfoheader, 4);
biHeight = (int)GET_2B(bmpinfoheader, 6);
biPlanes = GET_2B(bmpinfoheader, 8);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10);
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
break;
case 40:
case 64:
/* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
/* or OS/2 2.x header, which has additional fields that we ignore */
biWidth = (int)GET_4B(bmpinfoheader, 4);
biHeight = (int)GET_4B(bmpinfoheader, 8);
biPlanes = GET_2B(bmpinfoheader, 12);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14);
biCompression = GET_4B(bmpinfoheader, 16);
biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24);
biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28);
biClrUsed = GET_4B(bmpinfoheader, 32);
/* biSizeImage, biClrImportant fields are ignored */
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 4; /* Windows uses RGBQUAD colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
case 32: /* RGB image + Alpha channel */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
if (biCompression != 0)
ERREXIT(cinfo, JERR_BMP_COMPRESSED);
if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
/* Set JFIF density parameters from the BMP data */
cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */
cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100);
cinfo->density_unit = 2; /* dots/cm */
}
break;
default:
ERREXIT(cinfo, JERR_BMP_BADHEADER);
return;
}
if (biWidth <= 0 || biHeight <= 0)
ERREXIT(cinfo, JERR_BMP_EMPTY);
if (biPlanes != 1)
ERREXIT(cinfo, JERR_BMP_BADPLANES);
/* Compute distance to bitmap data --- will adjust for colormap below */
bPad = bfOffBits - (headerSize + 14);
/* Read the colormap, if any */
if (mapentrysize > 0) {
if (biClrUsed <= 0)
biClrUsed = 256; /* assume it's 256 */
else if (biClrUsed > 256)
ERREXIT(cinfo, JERR_BMP_BADCMAP);
/* Allocate space to store the colormap */
source->colormap = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3);
source->cmap_length = (int)biClrUsed;
/* and read it from the file */
read_colormap(source, (int)biClrUsed, mapentrysize);
/* account for size of colormap */
bPad -= biClrUsed * mapentrysize;
}
/* Skip any remaining pad bytes */
if (bPad < 0) /* incorrect bfOffBits value? */
ERREXIT(cinfo, JERR_BMP_BADHEADER);
while (--bPad >= 0) {
(void)read_byte(source);
}
/* Compute row width in file, including padding to 4-byte boundary */
switch (source->bits_per_pixel) {
case 8:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)biWidth;
break;
case 24:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGR;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 3);
break;
case 32:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGRA;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 4);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
while ((row_width & 3) != 0) row_width++;
source->row_width = row_width;
if (source->use_inversion_array) {
/* Allocate space for inversion array, prepare for preload pass */
source->whole_image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,
row_width, (JDIMENSION)biHeight, (JDIMENSION)1);
source->pub.get_pixel_rows = preload_image;
if (cinfo->progress != NULL) {
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
progress->total_extra_passes++; /* count file input as separate pass */
}
} else {
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width);
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
}
/* Ensure that biWidth * cinfo->input_components doesn't exceed the maximum
value of the JDIMENSION type. This is only a danger with BMP files, since
their width and height fields are 32-bit integers. */
if ((unsigned long long)biWidth *
(unsigned long long)cinfo->input_components > 0xFFFFFFFFULL)
ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
/* Allocate one-row buffer for returned data */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1);
source->pub.buffer_height = 1;
cinfo->data_precision = 8;
cinfo->image_width = (JDIMENSION)biWidth;
cinfo->image_height = (JDIMENSION)biHeight;
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for BMP format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_bmp(j_compress_ptr cinfo, boolean use_inversion_array)
{
bmp_source_ptr source;
/* Create module interface object */
source = (bmp_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
sizeof(bmp_source_struct));
source->cinfo = cinfo; /* make back link for subroutines */
/* Fill in method ptrs, except get_pixel_rows which start_input sets */
source->pub.start_input = start_input_bmp;
source->pub.finish_input = finish_input_bmp;
source->use_inversion_array = use_inversion_array;
return (cjpeg_source_ptr)source;
}
#endif /* BMP_SUPPORTED */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_270_2 |
crossvul-cpp_data_good_3945_0 | /**
* WinPR: Windows Portable Runtime
* NTLM Security Package (Message)
*
* Copyright 2011-2014 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 "ntlm.h"
#include "../sspi.h"
#include <winpr/crt.h>
#include <winpr/print.h>
#include <winpr/stream.h>
#include <winpr/sysinfo.h>
#include "ntlm_compute.h"
#include "ntlm_message.h"
#include "../log.h"
#define TAG WINPR_TAG("sspi.NTLM")
static const char NTLM_SIGNATURE[8] = { 'N', 'T', 'L', 'M', 'S', 'S', 'P', '\0' };
#ifdef WITH_DEBUG_NTLM
static const char* const NTLM_NEGOTIATE_STRINGS[] = { "NTLMSSP_NEGOTIATE_56",
"NTLMSSP_NEGOTIATE_KEY_EXCH",
"NTLMSSP_NEGOTIATE_128",
"NTLMSSP_RESERVED1",
"NTLMSSP_RESERVED2",
"NTLMSSP_RESERVED3",
"NTLMSSP_NEGOTIATE_VERSION",
"NTLMSSP_RESERVED4",
"NTLMSSP_NEGOTIATE_TARGET_INFO",
"NTLMSSP_REQUEST_NON_NT_SESSION_KEY",
"NTLMSSP_RESERVED5",
"NTLMSSP_NEGOTIATE_IDENTIFY",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY",
"NTLMSSP_RESERVED6",
"NTLMSSP_TARGET_TYPE_SERVER",
"NTLMSSP_TARGET_TYPE_DOMAIN",
"NTLMSSP_NEGOTIATE_ALWAYS_SIGN",
"NTLMSSP_RESERVED7",
"NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED",
"NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED",
"NTLMSSP_NEGOTIATE_ANONYMOUS",
"NTLMSSP_RESERVED8",
"NTLMSSP_NEGOTIATE_NTLM",
"NTLMSSP_RESERVED9",
"NTLMSSP_NEGOTIATE_LM_KEY",
"NTLMSSP_NEGOTIATE_DATAGRAM",
"NTLMSSP_NEGOTIATE_SEAL",
"NTLMSSP_NEGOTIATE_SIGN",
"NTLMSSP_RESERVED10",
"NTLMSSP_REQUEST_TARGET",
"NTLMSSP_NEGOTIATE_OEM",
"NTLMSSP_NEGOTIATE_UNICODE" };
static void ntlm_print_negotiate_flags(UINT32 flags)
{
int i;
const char* str;
WLog_INFO(TAG, "negotiateFlags \"0x%08" PRIX32 "\"", flags);
for (i = 31; i >= 0; i--)
{
if ((flags >> i) & 1)
{
str = NTLM_NEGOTIATE_STRINGS[(31 - i)];
WLog_INFO(TAG, "\t%s (%d),", str, (31 - i));
}
}
}
#endif
static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
if (Stream_GetRemainingLength(s) < 12)
return -1;
Stream_Read(s, header->Signature, 8);
Stream_Read_UINT32(s, header->MessageType);
if (strncmp((char*)header->Signature, NTLM_SIGNATURE, 8) != 0)
return -1;
return 1;
}
static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header)
{
Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE));
Stream_Write_UINT32(s, header->MessageType);
}
static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType)
{
CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE));
header->MessageType = MessageType;
}
static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (Stream_GetRemainingLength(s) < 8)
return -1;
Stream_Read_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Read_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Read_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
return 1;
}
static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->MaxLen < 1)
fields->MaxLen = fields->Len;
Stream_Write_UINT16(s, fields->Len); /* Len (2 bytes) */
Stream_Write_UINT16(s, fields->MaxLen); /* MaxLen (2 bytes) */
Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */
}
static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
const UINT32 offset = fields->BufferOffset + fields->Len;
if (fields->BufferOffset > UINT32_MAX - fields->Len)
return -1;
if (offset > Stream_Length(s))
return -1;
fields->Buffer = (PBYTE)malloc(fields->Len);
if (!fields->Buffer)
return -1;
Stream_SetPosition(s, fields->BufferOffset);
Stream_Read(s, fields->Buffer, fields->Len);
}
return 1;
}
static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields)
{
if (fields->Len > 0)
{
Stream_SetPosition(s, fields->BufferOffset);
Stream_Write(s, fields->Buffer, fields->Len);
}
}
static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields)
{
if (fields)
{
if (fields->Buffer)
{
free(fields->Buffer);
fields->Len = 0;
fields->MaxLen = 0;
fields->Buffer = NULL;
fields->BufferOffset = 0;
}
}
}
#ifdef WITH_DEBUG_NTLM
static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name)
{
WLog_DBG(TAG, "%s (Len: %" PRIu16 " MaxLen: %" PRIu16 " BufferOffset: %" PRIu32 ")", name,
fields->Len, fields->MaxLen, fields->BufferOffset);
if (fields->Len > 0)
winpr_HexDump(TAG, WLOG_DEBUG, fields->Buffer, fields->Len);
}
#endif
SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_NEGOTIATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) &&
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE)))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
context->NegotiateFlags = message->NegotiateFlags;
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %" PRIu32 ")", context->NegotiateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer,
context->NegotiateMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
NTLM_NEGOTIATE_MESSAGE* message;
message = &context->NEGOTIATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_NEGOTIATE);
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_LM_KEY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_OEM;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
context->NegotiateFlags = message->NegotiateFlags;
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
/* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */
/* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName));
/* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */
/* WorkstationFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer);
context->NegotiateMessage.BufferType = buffer->BufferType;
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "NEGOTIATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
#endif
context->state = NTLM_STATE_CHALLENGE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
int length;
PBYTE StartOffset;
PBYTE PayloadOffset;
NTLM_AV_PAIR* AvTimestamp;
NTLM_CHALLENGE_MESSAGE* message;
ntlm_generate_client_challenge(context);
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
StartOffset = Stream_Pointer(s);
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_CHALLENGE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->TargetName)) < 0) /* TargetNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (Stream_GetRemainingLength(s) < 4)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateFlags = message->NegotiateFlags;
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
CopyMemory(context->ServerChallenge, message->ServerChallenge, 8);
if (Stream_GetRemainingLength(s) < 8)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
if (ntlm_read_message_fields(s, &(message->TargetInfo)) < 0) /* TargetInfoFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
/* Payload (variable) */
PayloadOffset = Stream_Pointer(s);
if (message->TargetName.Len > 0)
{
if (ntlm_read_message_fields_buffer(s, &(message->TargetName)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
}
if (message->TargetInfo.Len > 0)
{
size_t cbAvTimestamp;
if (ntlm_read_message_fields_buffer(s, &(message->TargetInfo)) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
context->ChallengeTargetInfo.pvBuffer = message->TargetInfo.Buffer;
context->ChallengeTargetInfo.cbBuffer = message->TargetInfo.Len;
AvTimestamp = ntlm_av_pair_get((NTLM_AV_PAIR*)message->TargetInfo.Buffer,
message->TargetInfo.Len, MsvAvTimestamp, &cbAvTimestamp);
if (AvTimestamp)
{
PBYTE ptr = ntlm_av_pair_get_value_pointer(AvTimestamp);
if (!ptr)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
context->UseMIC = TRUE;
CopyMemory(context->ChallengeTimestamp, ptr, 8);
}
}
length = (PayloadOffset - StartOffset) + message->TargetName.Len + message->TargetInfo.Len;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, StartOffset, length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(context->NegotiateFlags);
if (context->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
if (context->ChallengeTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG, "ChallengeTargetInfo (%" PRIu32 "):", context->ChallengeTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->ChallengeTargetInfo.pvBuffer,
context->ChallengeTargetInfo.cbBuffer);
}
#endif
/* AV_PAIRs */
if (context->NTLMv2)
{
if (ntlm_construct_authenticate_target_info(context) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
sspi_SecBufferFree(&context->ChallengeTargetInfo);
context->ChallengeTargetInfo.pvBuffer = context->AuthenticateTargetInfo.pvBuffer;
context->ChallengeTargetInfo.cbBuffer = context->AuthenticateTargetInfo.cbBuffer;
}
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
ntlm_generate_key_exchange_key(context); /* KeyExchangeKey */
ntlm_generate_random_session_key(context); /* RandomSessionKey */
ntlm_generate_exported_session_key(context); /* ExportedSessionKey */
ntlm_encrypt_random_session_key(context); /* EncryptedRandomSessionKey */
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state using client sealing key */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_AUTHENTICATE;
ntlm_free_message_fields_buffer(&(message->TargetName));
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_write_ChallengeMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadOffset;
NTLM_CHALLENGE_MESSAGE* message;
message = &context->CHALLENGE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_CHALLENGE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
ntlm_get_version_info(&(message->Version)); /* Version */
ntlm_generate_server_challenge(context); /* Server Challenge */
ntlm_generate_timestamp(context); /* Timestamp */
if (ntlm_construct_challenge_target_info(context) < 0) /* TargetInfo */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(message->ServerChallenge, context->ServerChallenge, 8); /* ServerChallenge */
message->NegotiateFlags = context->NegotiateFlags;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_CHALLENGE);
/* Message Header (12 bytes) */
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message);
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
{
message->TargetName.Len = (UINT16)context->TargetName.cbBuffer;
message->TargetName.Buffer = (PBYTE)context->TargetName.pvBuffer;
}
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
{
message->TargetInfo.Len = (UINT16)context->ChallengeTargetInfo.cbBuffer;
message->TargetInfo.Buffer = (PBYTE)context->ChallengeTargetInfo.pvBuffer;
}
PayloadOffset = 48;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadOffset += 8;
message->TargetName.BufferOffset = PayloadOffset;
message->TargetInfo.BufferOffset = message->TargetName.BufferOffset + message->TargetName.Len;
/* TargetNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetName));
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
Stream_Write(s, message->ServerChallenge, 8); /* ServerChallenge (8 bytes) */
Stream_Write(s, message->Reserved, 8); /* Reserved (8 bytes), should be ignored */
/* TargetInfoFields (8 bytes) */
ntlm_write_message_fields(s, &(message->TargetInfo));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
/* Payload (variable) */
if (message->NegotiateFlags & NTLMSSP_REQUEST_TARGET)
ntlm_write_message_fields_buffer(s, &(message->TargetName));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_TARGET_INFO)
ntlm_write_message_fields_buffer(s, &(message->TargetInfo));
length = Stream_GetPosition(s);
buffer->cbBuffer = length;
if (!sspi_SecBufferAlloc(&context->ChallengeMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->ChallengeMessage.pvBuffer, Stream_Buffer(s), length);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "CHALLENGE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, context->ChallengeMessage.pvBuffer,
context->ChallengeMessage.cbBuffer);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->TargetName), "TargetName");
ntlm_print_message_fields(&(message->TargetInfo), "TargetInfo");
#endif
context->state = NTLM_STATE_AUTHENTICATE;
Stream_Free(s, FALSE);
return SEC_I_CONTINUE_NEEDED;
}
SECURITY_STATUS ntlm_read_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 flags;
NTLM_AV_PAIR* AvFlags;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
flags = 0;
AvFlags = NULL;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*)message) < 0)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->MessageType != MESSAGE_TYPE_AUTHENTICATE)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponseFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponseFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->UserName)) < 0) /* UserNameFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (ntlm_read_message_fields(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKeyFields (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
context->NegotiateKeyExchange =
(message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH) ? TRUE : FALSE;
if ((context->NegotiateKeyExchange && !message->EncryptedRandomSessionKey.Len) ||
(!context->NegotiateKeyExchange && message->EncryptedRandomSessionKey.Len))
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
{
if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
}
PayloadBufferOffset = Stream_GetPosition(s);
if (ntlm_read_message_fields_buffer(s, &(message->DomainName)) < 0) /* DomainName */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->UserName)) < 0) /* UserName */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->Workstation)) < 0) /* Workstation */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->LmChallengeResponse)) <
0) /* LmChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_message_fields_buffer(s, &(message->NtChallengeResponse)) <
0) /* NtChallengeResponse */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (message->NtChallengeResponse.Len > 0)
{
size_t cbAvFlags;
wStream* snt =
Stream_New(message->NtChallengeResponse.Buffer, message->NtChallengeResponse.Len);
if (!snt)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (ntlm_read_ntlm_v2_response(snt, &(context->NTLMv2Response)) < 0)
{
Stream_Free(s, FALSE);
Stream_Free(snt, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Free(snt, FALSE);
context->NtChallengeResponse.pvBuffer = message->NtChallengeResponse.Buffer;
context->NtChallengeResponse.cbBuffer = message->NtChallengeResponse.Len;
sspi_SecBufferFree(&(context->ChallengeTargetInfo));
context->ChallengeTargetInfo.pvBuffer = (void*)context->NTLMv2Response.Challenge.AvPairs;
context->ChallengeTargetInfo.cbBuffer = message->NtChallengeResponse.Len - (28 + 16);
CopyMemory(context->ClientChallenge, context->NTLMv2Response.Challenge.ClientChallenge, 8);
AvFlags =
ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
}
if (ntlm_read_message_fields_buffer(s, &(message->EncryptedRandomSessionKey)) <
0) /* EncryptedRandomSessionKey */
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
if (message->EncryptedRandomSessionKey.Len > 0)
{
if (message->EncryptedRandomSessionKey.Len != 16)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
CopyMemory(context->EncryptedRandomSessionKey, message->EncryptedRandomSessionKey.Buffer,
16);
}
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
Stream_SetPosition(s, PayloadBufferOffset);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
if (Stream_GetRemainingLength(s) < 16)
{
Stream_Free(s, FALSE);
return SEC_E_INVALID_TOKEN;
}
Stream_Read(s, message->MessageIntegrityCheck, 16);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %" PRIu32 ")",
context->AuthenticateMessage.cbBuffer);
winpr_HexDump(TAG, WLOG_DEBUG, context->AuthenticateMessage.pvBuffer,
context->AuthenticateMessage.cbBuffer);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
ntlm_print_av_pair_list(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
WLog_DBG(TAG, "MessageIntegrityCheck:");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
if (message->UserName.Len > 0)
{
credentials->identity.User = (UINT16*)malloc(message->UserName.Len);
if (!credentials->identity.User)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(credentials->identity.User, message->UserName.Buffer, message->UserName.Len);
credentials->identity.UserLength = message->UserName.Len / 2;
}
if (message->DomainName.Len > 0)
{
credentials->identity.Domain = (UINT16*)malloc(message->DomainName.Len);
if (!credentials->identity.Domain)
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(credentials->identity.Domain, message->DomainName.Buffer,
message->DomainName.Len);
credentials->identity.DomainLength = message->DomainName.Len / 2;
}
Stream_Free(s, FALSE);
/* Computations beyond this point require the NTLM hash of the password */
context->state = NTLM_STATE_COMPLETION;
return SEC_I_COMPLETE_NEEDED;
}
/**
* Send NTLMSSP AUTHENTICATE_MESSAGE.\n
* AUTHENTICATE_MESSAGE @msdn{cc236643}
* @param NTLM context
* @param buffer
*/
SECURITY_STATUS ntlm_write_AuthenticateMessage(NTLM_CONTEXT* context, PSecBuffer buffer)
{
wStream* s;
size_t length;
UINT32 PayloadBufferOffset;
NTLM_AUTHENTICATE_MESSAGE* message;
SSPI_CREDENTIALS* credentials = context->credentials;
message = &context->AUTHENTICATE_MESSAGE;
ZeroMemory(message, sizeof(NTLM_AUTHENTICATE_MESSAGE));
s = Stream_New((BYTE*)buffer->pvBuffer, buffer->cbBuffer);
if (!s)
return SEC_E_INTERNAL_ERROR;
if (context->NTLMv2)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_56;
if (context->SendVersionInfo)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_VERSION;
}
if (context->UseMIC)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_TARGET_INFO;
if (context->SendWorkstationName)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED;
if (context->confidentiality)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SEAL;
if (context->CHALLENGE_MESSAGE.NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_KEY_EXCH;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_128;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_EXTENDED_SESSION_SECURITY;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_ALWAYS_SIGN;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_NTLM;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_SIGN;
message->NegotiateFlags |= NTLMSSP_REQUEST_TARGET;
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_UNICODE;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_get_version_info(&(message->Version));
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
{
message->Workstation.Len = context->Workstation.Length;
message->Workstation.Buffer = (BYTE*)context->Workstation.Buffer;
}
if (credentials->identity.DomainLength > 0)
{
message->NegotiateFlags |= NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED;
message->DomainName.Len = (UINT16)credentials->identity.DomainLength * 2;
message->DomainName.Buffer = (BYTE*)credentials->identity.Domain;
}
message->UserName.Len = (UINT16)credentials->identity.UserLength * 2;
message->UserName.Buffer = (BYTE*)credentials->identity.User;
message->LmChallengeResponse.Len = (UINT16)context->LmChallengeResponse.cbBuffer;
message->LmChallengeResponse.Buffer = (BYTE*)context->LmChallengeResponse.pvBuffer;
message->NtChallengeResponse.Len = (UINT16)context->NtChallengeResponse.cbBuffer;
message->NtChallengeResponse.Buffer = (BYTE*)context->NtChallengeResponse.pvBuffer;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
{
message->EncryptedRandomSessionKey.Len = 16;
message->EncryptedRandomSessionKey.Buffer = context->EncryptedRandomSessionKey;
}
PayloadBufferOffset = 64;
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
PayloadBufferOffset += 8; /* Version (8 bytes) */
if (context->UseMIC)
PayloadBufferOffset += 16; /* Message Integrity Check (16 bytes) */
message->DomainName.BufferOffset = PayloadBufferOffset;
message->UserName.BufferOffset = message->DomainName.BufferOffset + message->DomainName.Len;
message->Workstation.BufferOffset = message->UserName.BufferOffset + message->UserName.Len;
message->LmChallengeResponse.BufferOffset =
message->Workstation.BufferOffset + message->Workstation.Len;
message->NtChallengeResponse.BufferOffset =
message->LmChallengeResponse.BufferOffset + message->LmChallengeResponse.Len;
message->EncryptedRandomSessionKey.BufferOffset =
message->NtChallengeResponse.BufferOffset + message->NtChallengeResponse.Len;
ntlm_populate_message_header((NTLM_MESSAGE_HEADER*)message, MESSAGE_TYPE_AUTHENTICATE);
ntlm_write_message_header(s, (NTLM_MESSAGE_HEADER*)message); /* Message Header (12 bytes) */
ntlm_write_message_fields(
s, &(message->LmChallengeResponse)); /* LmChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->NtChallengeResponse)); /* NtChallengeResponseFields (8 bytes) */
ntlm_write_message_fields(s, &(message->DomainName)); /* DomainNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->UserName)); /* UserNameFields (8 bytes) */
ntlm_write_message_fields(s, &(message->Workstation)); /* WorkstationFields (8 bytes) */
ntlm_write_message_fields(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKeyFields (8 bytes) */
Stream_Write_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_write_version_info(s, &(message->Version)); /* Version (8 bytes) */
if (context->UseMIC)
{
context->MessageIntegrityCheckOffset = (UINT32)Stream_GetPosition(s);
Stream_Zero(s, 16); /* Message Integrity Check (16 bytes) */
}
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->DomainName)); /* DomainName */
ntlm_write_message_fields_buffer(s, &(message->UserName)); /* UserName */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED)
ntlm_write_message_fields_buffer(s, &(message->Workstation)); /* Workstation */
ntlm_write_message_fields_buffer(s, &(message->LmChallengeResponse)); /* LmChallengeResponse */
ntlm_write_message_fields_buffer(s, &(message->NtChallengeResponse)); /* NtChallengeResponse */
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_KEY_EXCH)
ntlm_write_message_fields_buffer(
s, &(message->EncryptedRandomSessionKey)); /* EncryptedRandomSessionKey */
length = Stream_GetPosition(s);
if (!sspi_SecBufferAlloc(&context->AuthenticateMessage, length))
{
Stream_Free(s, FALSE);
return SEC_E_INTERNAL_ERROR;
}
CopyMemory(context->AuthenticateMessage.pvBuffer, Stream_Buffer(s), length);
buffer->cbBuffer = length;
if (context->UseMIC)
{
/* Message Integrity Check */
ntlm_compute_message_integrity_check(context, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, context->MessageIntegrityCheckOffset);
Stream_Write(s, message->MessageIntegrityCheck, 16);
Stream_SetPosition(s, length);
}
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "AUTHENTICATE_MESSAGE (length = %d)", length);
winpr_HexDump(TAG, WLOG_DEBUG, Stream_Buffer(s), length);
ntlm_print_negotiate_flags(message->NegotiateFlags);
if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION)
ntlm_print_version_info(&(message->Version));
if (context->AuthenticateTargetInfo.cbBuffer > 0)
{
WLog_DBG(TAG,
"AuthenticateTargetInfo (%" PRIu32 "):", context->AuthenticateTargetInfo.cbBuffer);
ntlm_print_av_pair_list(context->AuthenticateTargetInfo.pvBuffer,
context->AuthenticateTargetInfo.cbBuffer);
}
ntlm_print_message_fields(&(message->DomainName), "DomainName");
ntlm_print_message_fields(&(message->UserName), "UserName");
ntlm_print_message_fields(&(message->Workstation), "Workstation");
ntlm_print_message_fields(&(message->LmChallengeResponse), "LmChallengeResponse");
ntlm_print_message_fields(&(message->NtChallengeResponse), "NtChallengeResponse");
ntlm_print_message_fields(&(message->EncryptedRandomSessionKey), "EncryptedRandomSessionKey");
if (context->UseMIC)
{
WLog_DBG(TAG, "MessageIntegrityCheck (length = 16)");
winpr_HexDump(TAG, WLOG_DEBUG, message->MessageIntegrityCheck, 16);
}
#endif
context->state = NTLM_STATE_FINAL;
Stream_Free(s, FALSE);
return SEC_I_COMPLETE_NEEDED;
}
SECURITY_STATUS ntlm_server_AuthenticateComplete(NTLM_CONTEXT* context)
{
UINT32 flags = 0;
size_t cbAvFlags;
NTLM_AV_PAIR* AvFlags = NULL;
NTLM_AUTHENTICATE_MESSAGE* message;
BYTE messageIntegrityCheck[16];
if (!context)
return SEC_E_INVALID_PARAMETER;
if (context->state != NTLM_STATE_COMPLETION)
return SEC_E_OUT_OF_SEQUENCE;
message = &context->AUTHENTICATE_MESSAGE;
AvFlags = ntlm_av_pair_get(context->NTLMv2Response.Challenge.AvPairs,
context->NTLMv2Response.Challenge.cbAvPairs, MsvAvFlags, &cbAvFlags);
if (AvFlags)
Data_Read_UINT32(ntlm_av_pair_get_value_pointer(AvFlags), flags);
if (ntlm_compute_lm_v2_response(context) < 0) /* LmChallengeResponse */
return SEC_E_INTERNAL_ERROR;
if (ntlm_compute_ntlm_v2_response(context) < 0) /* NtChallengeResponse */
return SEC_E_INTERNAL_ERROR;
/* KeyExchangeKey */
ntlm_generate_key_exchange_key(context);
/* EncryptedRandomSessionKey */
ntlm_decrypt_random_session_key(context);
/* ExportedSessionKey */
ntlm_generate_exported_session_key(context);
if (flags & MSV_AV_FLAGS_MESSAGE_INTEGRITY_CHECK)
{
ZeroMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
16);
ntlm_compute_message_integrity_check(context, messageIntegrityCheck,
sizeof(messageIntegrityCheck));
CopyMemory(
&((PBYTE)context->AuthenticateMessage.pvBuffer)[context->MessageIntegrityCheckOffset],
message->MessageIntegrityCheck, 16);
if (memcmp(messageIntegrityCheck, message->MessageIntegrityCheck, 16) != 0)
{
WLog_ERR(TAG, "Message Integrity Check (MIC) verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected MIC:");
winpr_HexDump(TAG, WLOG_ERROR, messageIntegrityCheck, sizeof(messageIntegrityCheck));
WLog_ERR(TAG, "Actual MIC:");
winpr_HexDump(TAG, WLOG_ERROR, message->MessageIntegrityCheck,
sizeof(message->MessageIntegrityCheck));
#endif
return SEC_E_MESSAGE_ALTERED;
}
}
else
{
/* no mic message was present
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/f9e6fbc4-a953-4f24-b229-ccdcc213b9ec
the mic is optional, as not supported in Windows NT, Windows 2000, Windows XP, and
Windows Server 2003 and, as it seems, in the NTLMv2 implementation of Qt5.
now check the NtProofString, to detect if the entered client password matches the
expected password.
*/
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "No MIC present, using NtProofString for verification.");
#endif
if (memcmp(context->NTLMv2Response.Response, context->NtProofString, 16) != 0)
{
WLog_ERR(TAG, "NtProofString verification failed!");
#ifdef WITH_DEBUG_NTLM
WLog_ERR(TAG, "Expected NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NtProofString, sizeof(context->NtProofString));
WLog_ERR(TAG, "Actual NtProofString:");
winpr_HexDump(TAG, WLOG_ERROR, context->NTLMv2Response.Response,
sizeof(context->NTLMv2Response));
#endif
return SEC_E_LOGON_DENIED;
}
}
/* Generate signing keys */
ntlm_generate_client_signing_key(context);
ntlm_generate_server_signing_key(context);
/* Generate sealing keys */
ntlm_generate_client_sealing_key(context);
ntlm_generate_server_sealing_key(context);
/* Initialize RC4 seal state */
ntlm_init_rc4_seal_states(context);
#ifdef WITH_DEBUG_NTLM
WLog_DBG(TAG, "ClientChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientChallenge, 8);
WLog_DBG(TAG, "ServerChallenge");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerChallenge, 8);
WLog_DBG(TAG, "SessionBaseKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->SessionBaseKey, 16);
WLog_DBG(TAG, "KeyExchangeKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->KeyExchangeKey, 16);
WLog_DBG(TAG, "ExportedSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ExportedSessionKey, 16);
WLog_DBG(TAG, "RandomSessionKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->RandomSessionKey, 16);
WLog_DBG(TAG, "ClientSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSigningKey, 16);
WLog_DBG(TAG, "ClientSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ClientSealingKey, 16);
WLog_DBG(TAG, "ServerSigningKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSigningKey, 16);
WLog_DBG(TAG, "ServerSealingKey");
winpr_HexDump(TAG, WLOG_DEBUG, context->ServerSealingKey, 16);
WLog_DBG(TAG, "Timestamp");
winpr_HexDump(TAG, WLOG_DEBUG, context->Timestamp, 8);
#endif
context->state = NTLM_STATE_FINAL;
ntlm_free_message_fields_buffer(&(message->DomainName));
ntlm_free_message_fields_buffer(&(message->UserName));
ntlm_free_message_fields_buffer(&(message->Workstation));
ntlm_free_message_fields_buffer(&(message->LmChallengeResponse));
ntlm_free_message_fields_buffer(&(message->NtChallengeResponse));
ntlm_free_message_fields_buffer(&(message->EncryptedRandomSessionKey));
return SEC_E_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3945_0 |
crossvul-cpp_data_bad_615_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 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, 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, &ds64_chunk, chunk_header.ckSize)) {
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;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_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);
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);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
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;
}
// 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))) ||
(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-125/c/bad_615_0 |
crossvul-cpp_data_bad_1853_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% SSSSS U U N N %
% SS U U NN N %
% SSS U U N N N %
% SS U U N NN %
% SSSSS UUU N N %
% %
% %
% Read/Write Sun Rasterfile Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 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 "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/colorspace.h"
#include "MagickCore/colorspace-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/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteSUNImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s S U N %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsSUN() returns MagickTrue if the image format type, identified by the
% magick string, is SUN.
%
% The format of the IsSUN method is:
%
% MagickBooleanType IsSUN(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 IsSUN(const unsigned char *magick,const size_t length)
{
if (length < 4)
return(MagickFalse);
if (memcmp(magick,"\131\246\152\225",4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodeImage unpacks the packed image pixels into runlength-encoded pixel
% packets.
%
% The format of the DecodeImage method is:
%
% MagickBooleanType DecodeImage(const unsigned char *compressed_pixels,
% const size_t length,unsigned char *pixels)
%
% A description of each parameter follows:
%
% o compressed_pixels: The address of a byte (8 bits) array of compressed
% pixel data.
%
% o length: An integer value that is the total number of bytes of the
% source image (as just read by ReadBlob)
%
% o pixels: The address of a byte (8 bits) array of pixel data created by
% the uncompression process. The number of bytes in this array
% must be at least equal to the number columns times the number of rows
% of the source pixels.
%
*/
static MagickBooleanType DecodeImage(const unsigned char *compressed_pixels,
const size_t length,unsigned char *pixels,size_t maxpixels)
{
register const unsigned char
*l,
*p;
register unsigned char
*q;
ssize_t
count;
unsigned char
byte;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(compressed_pixels != (unsigned char *) NULL);
assert(pixels != (unsigned char *) NULL);
p=compressed_pixels;
q=pixels;
l=q+maxpixels;
while (((size_t) (p-compressed_pixels) < length) && (q < l))
{
byte=(*p++);
if (byte != 128U)
*q++=byte;
else
{
/*
Runlength-encoded packet: <count><byte>
*/
count=(ssize_t) (*p++);
if (count > 0)
byte=(*p++);
while ((count >= 0) && (q < l))
{
*q++=byte;
count--;
}
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadSUNImage() reads a SUN 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 ReadSUNImage method is:
%
% Image *ReadSUNImage(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 *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_ENCODED 2
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
Image
*image;
int
bit;
MagickBooleanType
status;
MagickSizeType
number_pixels;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
size_t
bytes_per_line,
extent,
height,
length;
ssize_t
count,
y;
SUNInfo
sun_info;
unsigned char
*sun_data,
*sun_pixels;
/*
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,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read SUN raster header.
*/
(void) ResetMagickMemory(&sun_info,0,sizeof(sun_info));
sun_info.magic=ReadBlobMSBLong(image);
do
{
/*
Verify SUN identifier.
*/
if (sun_info.magic != 0x59a66a95)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
sun_info.width=ReadBlobMSBLong(image);
sun_info.height=ReadBlobMSBLong(image);
sun_info.depth=ReadBlobMSBLong(image);
sun_info.length=ReadBlobMSBLong(image);
sun_info.type=ReadBlobMSBLong(image);
sun_info.maptype=ReadBlobMSBLong(image);
sun_info.maplength=ReadBlobMSBLong(image);
extent=sun_info.height*sun_info.width;
if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) &&
(sun_info.type != RT_FORMAT_RGB))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.depth == 0) || (sun_info.depth > 32))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) &&
(sun_info.maptype != RMT_RAW))
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
image->columns=sun_info.width;
image->rows=sun_info.height;
image->depth=sun_info.depth <= 8 ? sun_info.depth :
MAGICKCORE_QUANTUM_DEPTH;
if (sun_info.depth < 24)
{
size_t
one;
image->colors=sun_info.maplength;
one=1;
if (sun_info.maptype == RMT_NONE)
image->colors=one << sun_info.depth;
if (sun_info.maptype == RMT_EQUAL_RGB)
image->colors=sun_info.maplength/3;
if (AcquireImageColormap(image,image->colors,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
switch (sun_info.maptype)
{
case RMT_NONE:
break;
case RMT_EQUAL_RGB:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
count=ReadBlob(image,image->colors,sun_colormap);
if (count != (ssize_t) image->colors)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
for (i=0; i < (ssize_t) image->colors; i++)
image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(
sun_colormap[i]);
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
case RMT_RAW:
{
unsigned char
*sun_colormap;
/*
Read SUN raster colormap.
*/
sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength,
sizeof(*sun_colormap));
if (sun_colormap == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=ReadBlob(image,sun_info.maplength,sun_colormap);
if (count != (ssize_t) sun_info.maplength)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap);
break;
}
default:
ThrowReaderException(CoderError,"ColormapTypeNotSupported");
}
image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait :
UndefinedPixelTrait;
image->columns=sun_info.width;
image->rows=sun_info.height;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) !=
sun_info.length || !sun_info.length)
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((sun_info.type != RT_ENCODED) &&
((number_pixels*sun_info.depth) > (8*sun_info.length)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
bytes_per_line=sun_info.width*sun_info.depth;
sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(
sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data));
if (sun_data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
count=(ssize_t) ReadBlob(image,sun_info.length,sun_data);
if (count != (ssize_t) sun_info.length)
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
height=sun_info.height;
if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) ||
((bytes_per_line/sun_info.depth) != sun_info.width))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line+=15;
bytes_per_line<<=1;
if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
bytes_per_line>>=4;
sun_pixels=(unsigned char *) AcquireQuantumMemory(height,
bytes_per_line*sizeof(*sun_pixels));
if (sun_pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (sun_info.type == RT_ENCODED)
(void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line*
height);
else
{
if (sun_info.length > (height*bytes_per_line))
ThrowReaderException(ResourceLimitError,"ImproperImageHeader");
(void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length);
}
sun_data=(unsigned char *) RelinquishMagickMemory(sun_data);
/*
Convert SUN raster image to pixel packets.
*/
p=sun_pixels;
if (sun_info.depth == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < ((ssize_t) image->columns-7); x+=8)
{
for (bit=7; bit >= 0; bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01),
q);
q+=GetPixelChannels(image);
}
p++;
}
if ((image->columns % 8) != 0)
{
for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--)
{
SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 :
0x01),q);
q+=GetPixelChannels(image);
}
p++;
}
if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
else
if (image->storage_class == PseudoClass)
{
if (bytes_per_line == 0)
bytes_per_line=image->columns;
length=image->rows*(image->columns+image->columns % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelIndex(image,*p++,q);
q+=GetPixelChannels(image);
}
if ((image->columns % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
size_t
bytes_per_pixel;
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
if (bytes_per_line == 0)
bytes_per_line=bytes_per_pixel*image->columns;
length=image->rows*(bytes_per_line+bytes_per_line % 2);
if (((sun_info.type == RT_ENCODED) &&
(length > (bytes_per_line*image->rows))) ||
((sun_info.type != RT_ENCODED) && (length > sun_info.length)))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
if (sun_info.type == RT_STANDARD)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
}
else
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
}
if (image->colors != 0)
{
SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelRed(image,q)].red),q);
SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelGreen(image,q)].green),q);
SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t)
GetPixelBlue(image,q)].blue),q);
}
q+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) % 2) != 0)
p++;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
sun_info.magic=ReadBlobMSBLong(image);
if (sun_info.magic == 0x59a66a95)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
} while (sun_info.magic == 0x59a66a95);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterSUNImage() adds attributes for the SUN 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 RegisterSUNImage method is:
%
% size_t RegisterSUNImage(void)
%
*/
ModuleExport size_t RegisterSUNImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("RAS");
entry->decoder=(DecodeImageHandler *) ReadSUNImage;
entry->encoder=(EncodeImageHandler *) WriteSUNImage;
entry->magick=(IsImageFormatHandler *) IsSUN;
entry->description=ConstantString("SUN Rasterfile");
entry->module=ConstantString("SUN");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("SUN");
entry->decoder=(DecodeImageHandler *) ReadSUNImage;
entry->encoder=(EncodeImageHandler *) WriteSUNImage;
entry->description=ConstantString("SUN Rasterfile");
entry->module=ConstantString("SUN");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterSUNImage() removes format registrations made by the
% SUN module from the list of supported formats.
%
% The format of the UnregisterSUNImage method is:
%
% UnregisterSUNImage(void)
%
*/
ModuleExport void UnregisterSUNImage(void)
{
(void) UnregisterMagickInfo("RAS");
(void) UnregisterMagickInfo("SUN");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e S U N I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteSUNImage() writes an image in the SUN rasterfile format.
%
% The format of the WriteSUNImage method is:
%
% MagickBooleanType WriteSUNImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteSUNImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
#define RMT_EQUAL_RGB 1
#define RMT_NONE 0
#define RMT_RAW 2
#define RT_STANDARD 1
#define RT_FORMAT_RGB 3
typedef struct _SUNInfo
{
unsigned int
magic,
width,
height,
depth,
length,
type,
maptype,
maplength;
} SUNInfo;
MagickBooleanType
status;
MagickOffsetType
scene;
MagickSizeType
number_pixels;
register const Quantum
*p;
register ssize_t
i,
x;
ssize_t
y;
SUNInfo
sun_info;
/*
Open output 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);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Initialize SUN raster file header.
*/
(void) TransformImageColorspace(image,sRGBColorspace,exception);
sun_info.magic=0x59a66a95;
if ((image->columns != (unsigned int) image->columns) ||
(image->rows != (unsigned int) image->rows))
ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit");
sun_info.width=(unsigned int) image->columns;
sun_info.height=(unsigned int) image->rows;
sun_info.type=(unsigned int)
(image->storage_class == DirectClass ? RT_FORMAT_RGB : RT_STANDARD);
sun_info.maptype=RMT_NONE;
sun_info.maplength=0;
number_pixels=(MagickSizeType) image->columns*image->rows;
if ((4*number_pixels) != (size_t) (4*number_pixels))
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
if (image->storage_class == DirectClass)
{
/*
Full color SUN raster.
*/
sun_info.depth=(unsigned int) image->alpha_trait != UndefinedPixelTrait ?
32U : 24U;
sun_info.length=(unsigned int) ((image->alpha_trait != UndefinedPixelTrait ?
4 : 3)*number_pixels);
sun_info.length+=sun_info.length & 0x01 ? (unsigned int) image->rows :
0;
}
else
if (IsImageMonochrome(image,exception) != MagickFalse)
{
/*
Monochrome SUN raster.
*/
sun_info.depth=1;
sun_info.length=(unsigned int) (((image->columns+7) >> 3)*
image->rows);
sun_info.length+=(unsigned int) (((image->columns/8)+(image->columns %
8 ? 1 : 0)) % 2 ? image->rows : 0);
}
else
{
/*
Colormapped SUN raster.
*/
sun_info.depth=8;
sun_info.length=(unsigned int) number_pixels;
sun_info.length+=(unsigned int) (image->columns & 0x01 ? image->rows :
0);
sun_info.maptype=RMT_EQUAL_RGB;
sun_info.maplength=(unsigned int) (3*image->colors);
}
/*
Write SUN header.
*/
(void) WriteBlobMSBLong(image,sun_info.magic);
(void) WriteBlobMSBLong(image,sun_info.width);
(void) WriteBlobMSBLong(image,sun_info.height);
(void) WriteBlobMSBLong(image,sun_info.depth);
(void) WriteBlobMSBLong(image,sun_info.length);
(void) WriteBlobMSBLong(image,sun_info.type);
(void) WriteBlobMSBLong(image,sun_info.maptype);
(void) WriteBlobMSBLong(image,sun_info.maplength);
/*
Convert MIFF to SUN raster pixels.
*/
x=0;
y=0;
if (image->storage_class == DirectClass)
{
register unsigned char
*q;
size_t
bytes_per_pixel,
length;
unsigned char
*pixels;
/*
Allocate memory for pixels.
*/
bytes_per_pixel=3;
if (image->alpha_trait != UndefinedPixelTrait)
bytes_per_pixel++;
length=image->columns;
pixels=(unsigned char *) AcquireQuantumMemory(length,4*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Convert DirectClass packet to SUN RGB pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait != UndefinedPixelTrait)
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
if (((bytes_per_pixel*image->columns) & 0x01) != 0)
*q++='\0'; /* pad scanline */
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
}
else
if (IsImageMonochrome(image,exception) != MagickFalse)
{
register unsigned char
bit,
byte;
/*
Convert PseudoClass image to a SUN monochrome image.
*/
(void) SetImageType(image,BilevelType,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
bit=0;
byte=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
byte<<=1;
if (GetPixelLuma(image,p) < (QuantumRange/2.0))
byte|=0x01;
bit++;
if (bit == 8)
{
(void) WriteBlobByte(image,byte);
bit=0;
byte=0;
}
p+=GetPixelChannels(image);
}
if (bit != 0)
(void) WriteBlobByte(image,(unsigned char) (byte << (8-bit)));
if ((((image->columns/8)+
(image->columns % 8 ? 1 : 0)) % 2) != 0)
(void) WriteBlobByte(image,0); /* pad scanline */
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
/*
Dump colormap to file.
*/
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].red)));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].green)));
for (i=0; i < (ssize_t) image->colors; i++)
(void) WriteBlobByte(image,ScaleQuantumToChar(
ClampToQuantum(image->colormap[i].blue)));
/*
Convert PseudoClass packet to SUN colormapped pixel.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,(unsigned char)
GetPixelIndex(image,p));
p+=GetPixelChannels(image);
}
if (image->columns & 0x01)
(void) WriteBlobByte(image,0); /* pad scanline */
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene++,
GetImageListLength(image));
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1853_0 |
crossvul-cpp_data_bad_4039_1 | /*
* rdppm.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1997, Thomas G. Lane.
* Modified 2009 by Bill Allombert, Guido Vollbeding.
* libjpeg-turbo Modifications:
* Copyright (C) 2015-2017, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains routines to read input images in PPM/PGM format.
* The extended 2-byte-per-sample raw PPM/PGM formats are supported.
* The PBMPLUS library is NOT required to compile this software
* (but it is highly useful as a set of PPM image manipulation programs).
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed PPM format).
*/
#include "cmyk.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef PPM_SUPPORTED
/* Portions of this code are based on the PBMPLUS library, which is:
**
** Copyright (C) 1988 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
/* Macros to deal with unsigned chars as efficiently as compiler allows */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char U_CHAR;
#define UCH(x) ((int)(x))
#else /* !HAVE_UNSIGNED_CHAR */
#ifdef __CHAR_UNSIGNED__
typedef char U_CHAR;
#define UCH(x) ((int)(x))
#else
typedef char U_CHAR;
#define UCH(x) ((int)(x) & 0xFF)
#endif
#endif /* HAVE_UNSIGNED_CHAR */
#define ReadOK(file, buffer, len) \
(JFREAD(file, buffer, len) == ((size_t)(len)))
static int alpha_index[JPEG_NUMCS] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1
};
/* Private version of data source object */
typedef struct {
struct cjpeg_source_struct pub; /* public fields */
/* Usually these two pointers point to the same place: */
U_CHAR *iobuffer; /* fread's I/O buffer */
JSAMPROW pixrow; /* compressor input buffer */
size_t buffer_width; /* width of I/O buffer */
JSAMPLE *rescale; /* => maxval-remapping array, or NULL */
unsigned int maxval;
} ppm_source_struct;
typedef ppm_source_struct *ppm_source_ptr;
LOCAL(int)
pbm_getc(FILE *infile)
/* Read next char, skipping over any comments */
/* A comment/newline sequence is returned as a newline */
{
register int ch;
ch = getc(infile);
if (ch == '#') {
do {
ch = getc(infile);
} while (ch != '\n' && ch != EOF);
}
return ch;
}
LOCAL(unsigned int)
read_pbm_integer(j_compress_ptr cinfo, FILE *infile, unsigned int maxval)
/* Read an unsigned decimal integer from the PPM file */
/* Swallows one trailing character after the integer */
/* Note that on a 16-bit-int machine, only values up to 64k can be read. */
/* This should not be a problem in practice. */
{
register int ch;
register unsigned int val;
/* Skip any leading whitespace */
do {
ch = pbm_getc(infile);
if (ch == EOF)
ERREXIT(cinfo, JERR_INPUT_EOF);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r');
if (ch < '0' || ch > '9')
ERREXIT(cinfo, JERR_PPM_NONNUMERIC);
val = ch - '0';
while ((ch = pbm_getc(infile)) >= '0' && ch <= '9') {
val *= 10;
val += ch - '0';
}
if (val > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
return val;
}
/*
* Read one row of pixels.
*
* We provide several different versions depending on input file format.
* In all cases, input is scaled to the size of JSAMPLE.
*
* A really fast path is provided for reading byte/sample raw files with
* maxval = MAXJSAMPLE, which is the normal case for 8-bit data.
*/
METHODDEF(JDIMENSION)
get_text_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[read_pbm_integer(cinfo, infile, maxval)];
}
return 1;
}
#define GRAY_RGB_READ_LOOP(read_op, alpha_set_op) { \
for (col = cinfo->image_width; col > 0; col--) { \
ptr[rindex] = ptr[gindex] = ptr[bindex] = read_op; \
alpha_set_op \
ptr += ps; \
} \
}
METHODDEF(JDIMENSION)
get_text_gray_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval and
converting to extended RGB */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),
ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),)
} else {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],
ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_text_gray_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PGM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = read_pbm_integer(cinfo, infile, maxval);
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = rescale[read_pbm_integer(cinfo, infile, maxval)];
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
#define RGB_READ_LOOP(read_op, alpha_set_op) { \
for (col = cinfo->image_width; col > 0; col--) { \
ptr[rindex] = read_op; \
ptr[gindex] = read_op; \
ptr[bindex] = read_op; \
alpha_set_op \
ptr += ps; \
} \
}
METHODDEF(JDIMENSION)
get_text_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),
ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(read_pbm_integer(cinfo, infile, maxval),)
} else {
if (aindex >= 0)
RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],
ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(rescale[read_pbm_integer(cinfo, infile, maxval)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_text_rgb_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading text-format PPM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
FILE *infile = source->pub.input_file;
register JSAMPROW ptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
ptr = source->pub.buffer[0];
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = read_pbm_integer(cinfo, infile, maxval);
JSAMPLE g = read_pbm_integer(cinfo, infile, maxval);
JSAMPLE b = read_pbm_integer(cinfo, infile, maxval);
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = rescale[read_pbm_integer(cinfo, infile, maxval)];
JSAMPLE g = rescale[read_pbm_integer(cinfo, infile, maxval)];
JSAMPLE b = rescale[read_pbm_integer(cinfo, infile, maxval)];
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_scaled_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
*ptr++ = rescale[UCH(*bufferptr++)];
}
return 1;
}
METHODDEF(JDIMENSION)
get_gray_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval
and converting to extended RGB */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(*bufferptr++, ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(*bufferptr++,)
} else {
if (aindex >= 0)
GRAY_RGB_READ_LOOP(rescale[UCH(*bufferptr++)], ptr[aindex] = 0xFF;)
else
GRAY_RGB_READ_LOOP(rescale[UCH(*bufferptr++)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_gray_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PGM files with any maxval
and converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = *bufferptr++;
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE gray = rescale[UCH(*bufferptr++)];
rgb_to_cmyk(gray, gray, gray, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
if (aindex >= 0)
RGB_READ_LOOP(*bufferptr++, ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(*bufferptr++,)
} else {
if (aindex >= 0)
RGB_READ_LOOP(rescale[UCH(*bufferptr++)], ptr[aindex] = 0xFF;)
else
RGB_READ_LOOP(rescale[UCH(*bufferptr++)],)
}
return 1;
}
METHODDEF(JDIMENSION)
get_rgb_cmyk_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format PPM files with any maxval and
converting to CMYK */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
if (maxval == MAXJSAMPLE) {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = *bufferptr++;
JSAMPLE g = *bufferptr++;
JSAMPLE b = *bufferptr++;
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
JSAMPLE r = rescale[UCH(*bufferptr++)];
JSAMPLE g = rescale[UCH(*bufferptr++)];
JSAMPLE b = rescale[UCH(*bufferptr++)];
rgb_to_cmyk(r, g, b, ptr, ptr + 1, ptr + 2, ptr + 3);
ptr += 4;
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_raw_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-byte-format files with maxval = MAXJSAMPLE.
* In this case we just read right into the JSAMPLE buffer!
* Note that same code works for PPM and PGM files.
*/
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
return 1;
}
METHODDEF(JDIMENSION)
get_word_gray_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PGM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
}
return 1;
}
METHODDEF(JDIMENSION)
get_word_rgb_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading raw-word-format PPM files with any maxval */
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
register JSAMPROW ptr;
register U_CHAR *bufferptr;
register JSAMPLE *rescale = source->rescale;
JDIMENSION col;
unsigned int maxval = source->maxval;
if (!ReadOK(source->pub.input_file, source->iobuffer, source->buffer_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
ptr = source->pub.buffer[0];
bufferptr = source->iobuffer;
for (col = cinfo->image_width; col > 0; col--) {
register unsigned int temp;
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
temp = UCH(*bufferptr++) << 8;
temp |= UCH(*bufferptr++);
if (temp > maxval)
ERREXIT(cinfo, JERR_PPM_OUTOFRANGE);
*ptr++ = rescale[temp];
}
return 1;
}
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
ppm_source_ptr source = (ppm_source_ptr)sinfo;
int c;
unsigned int w, h, maxval;
boolean need_iobuffer, use_raw_buffer, need_rescale;
if (getc(source->pub.input_file) != 'P')
ERREXIT(cinfo, JERR_PPM_NOT);
c = getc(source->pub.input_file); /* subformat discriminator character */
/* detect unsupported variants (ie, PBM) before trying to read header */
switch (c) {
case '2': /* it's a text-format PGM file */
case '3': /* it's a text-format PPM file */
case '5': /* it's a raw-format PGM file */
case '6': /* it's a raw-format PPM file */
break;
default:
ERREXIT(cinfo, JERR_PPM_NOT);
break;
}
/* fetch the remaining header info */
w = read_pbm_integer(cinfo, source->pub.input_file, 65535);
h = read_pbm_integer(cinfo, source->pub.input_file, 65535);
maxval = read_pbm_integer(cinfo, source->pub.input_file, 65535);
if (w <= 0 || h <= 0 || maxval <= 0) /* error check */
ERREXIT(cinfo, JERR_PPM_NOT);
cinfo->data_precision = BITS_IN_JSAMPLE; /* we always rescale data to this */
cinfo->image_width = (JDIMENSION)w;
cinfo->image_height = (JDIMENSION)h;
source->maxval = maxval;
/* initialize flags to most common settings */
need_iobuffer = TRUE; /* do we need an I/O buffer? */
use_raw_buffer = FALSE; /* do we map input buffer onto I/O buffer? */
need_rescale = TRUE; /* do we need a rescale array? */
switch (c) {
case '2': /* it's a text-format PGM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM_TEXT, w, h);
if (cinfo->in_color_space == JCS_GRAYSCALE)
source->pub.get_pixel_rows = get_text_gray_row;
else if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_text_gray_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_text_gray_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
need_iobuffer = FALSE;
break;
case '3': /* it's a text-format PPM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM_TEXT, w, h);
if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_text_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_text_rgb_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
need_iobuffer = FALSE;
break;
case '5': /* it's a raw-format PGM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_GRAYSCALE;
TRACEMS2(cinfo, 1, JTRC_PGM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_gray_row;
} else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) &&
cinfo->in_color_space == JCS_GRAYSCALE) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
if (cinfo->in_color_space == JCS_GRAYSCALE)
source->pub.get_pixel_rows = get_scaled_gray_row;
else if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_gray_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_gray_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
}
break;
case '6': /* it's a raw-format PPM file */
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
TRACEMS2(cinfo, 1, JTRC_PPM, w, h);
if (maxval > 255) {
source->pub.get_pixel_rows = get_word_rgb_row;
} else if (maxval == MAXJSAMPLE && sizeof(JSAMPLE) == sizeof(U_CHAR) &&
(cinfo->in_color_space == JCS_EXT_RGB
#if RGB_RED == 0 && RGB_GREEN == 1 && RGB_BLUE == 2 && RGB_PIXELSIZE == 3
|| cinfo->in_color_space == JCS_RGB
#endif
)) {
source->pub.get_pixel_rows = get_raw_row;
use_raw_buffer = TRUE;
need_rescale = FALSE;
} else {
if (IsExtRGB(cinfo->in_color_space))
source->pub.get_pixel_rows = get_rgb_row;
else if (cinfo->in_color_space == JCS_CMYK)
source->pub.get_pixel_rows = get_rgb_cmyk_row;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
}
break;
}
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
/* Allocate space for I/O buffer: 1 or 3 bytes or words/pixel. */
if (need_iobuffer) {
if (c == '6')
source->buffer_width = (size_t)w * 3 *
((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR)));
else
source->buffer_width = (size_t)w *
((maxval <= 255) ? sizeof(U_CHAR) : (2 * sizeof(U_CHAR)));
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
source->buffer_width);
}
/* Create compressor input buffer. */
if (use_raw_buffer) {
/* For unscaled raw-input case, we can just map it onto the I/O buffer. */
/* Synthesize a JSAMPARRAY pointer structure */
source->pixrow = (JSAMPROW)source->iobuffer;
source->pub.buffer = &source->pixrow;
source->pub.buffer_height = 1;
} else {
/* Need to translate anyway, so make a separate sample buffer. */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)w * cinfo->input_components, (JDIMENSION)1);
source->pub.buffer_height = 1;
}
/* Compute the rescaling array if required. */
if (need_rescale) {
long val, half_maxval;
/* On 16-bit-int machines we have to be careful of maxval = 65535 */
source->rescale = (JSAMPLE *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
(size_t)(((long)maxval + 1L) *
sizeof(JSAMPLE)));
half_maxval = maxval / 2;
for (val = 0; val <= (long)maxval; val++) {
/* The multiplication here must be done in 32 bits to avoid overflow */
source->rescale[val] = (JSAMPLE)((val * MAXJSAMPLE + half_maxval) /
maxval);
}
}
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_ppm(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for PPM format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_ppm(j_compress_ptr cinfo)
{
ppm_source_ptr source;
/* Create module interface object */
source = (ppm_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
sizeof(ppm_source_struct));
/* Fill in method ptrs, except get_pixel_rows which start_input sets */
source->pub.start_input = start_input_ppm;
source->pub.finish_input = finish_input_ppm;
return (cjpeg_source_ptr)source;
}
#endif /* PPM_SUPPORTED */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4039_1 |
crossvul-cpp_data_bad_328_0 | /*
* Copyright (c) 2001
* Fortress Technologies, Inc. All rights reserved.
* Charlie Lenahan (clenahan@fortresstech.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.11 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "cpack.h"
/* Lengths of 802.11 header components. */
#define IEEE802_11_FC_LEN 2
#define IEEE802_11_DUR_LEN 2
#define IEEE802_11_DA_LEN 6
#define IEEE802_11_SA_LEN 6
#define IEEE802_11_BSSID_LEN 6
#define IEEE802_11_RA_LEN 6
#define IEEE802_11_TA_LEN 6
#define IEEE802_11_ADDR1_LEN 6
#define IEEE802_11_SEQ_LEN 2
#define IEEE802_11_CTL_LEN 2
#define IEEE802_11_CARRIED_FC_LEN 2
#define IEEE802_11_HT_CONTROL_LEN 4
#define IEEE802_11_IV_LEN 3
#define IEEE802_11_KID_LEN 1
/* Frame check sequence length. */
#define IEEE802_11_FCS_LEN 4
/* Lengths of beacon components. */
#define IEEE802_11_TSTAMP_LEN 8
#define IEEE802_11_BCNINT_LEN 2
#define IEEE802_11_CAPINFO_LEN 2
#define IEEE802_11_LISTENINT_LEN 2
#define IEEE802_11_AID_LEN 2
#define IEEE802_11_STATUS_LEN 2
#define IEEE802_11_REASON_LEN 2
/* Length of previous AP in reassocation frame */
#define IEEE802_11_AP_LEN 6
#define T_MGMT 0x0 /* management */
#define T_CTRL 0x1 /* control */
#define T_DATA 0x2 /* data */
#define T_RESV 0x3 /* reserved */
#define ST_ASSOC_REQUEST 0x0
#define ST_ASSOC_RESPONSE 0x1
#define ST_REASSOC_REQUEST 0x2
#define ST_REASSOC_RESPONSE 0x3
#define ST_PROBE_REQUEST 0x4
#define ST_PROBE_RESPONSE 0x5
/* RESERVED 0x6 */
/* RESERVED 0x7 */
#define ST_BEACON 0x8
#define ST_ATIM 0x9
#define ST_DISASSOC 0xA
#define ST_AUTH 0xB
#define ST_DEAUTH 0xC
#define ST_ACTION 0xD
/* RESERVED 0xE */
/* RESERVED 0xF */
static const struct tok st_str[] = {
{ ST_ASSOC_REQUEST, "Assoc Request" },
{ ST_ASSOC_RESPONSE, "Assoc Response" },
{ ST_REASSOC_REQUEST, "ReAssoc Request" },
{ ST_REASSOC_RESPONSE, "ReAssoc Response" },
{ ST_PROBE_REQUEST, "Probe Request" },
{ ST_PROBE_RESPONSE, "Probe Response" },
{ ST_BEACON, "Beacon" },
{ ST_ATIM, "ATIM" },
{ ST_DISASSOC, "Disassociation" },
{ ST_AUTH, "Authentication" },
{ ST_DEAUTH, "DeAuthentication" },
{ ST_ACTION, "Action" },
{ 0, NULL }
};
#define CTRL_CONTROL_WRAPPER 0x7
#define CTRL_BAR 0x8
#define CTRL_BA 0x9
#define CTRL_PS_POLL 0xA
#define CTRL_RTS 0xB
#define CTRL_CTS 0xC
#define CTRL_ACK 0xD
#define CTRL_CF_END 0xE
#define CTRL_END_ACK 0xF
static const struct tok ctrl_str[] = {
{ CTRL_CONTROL_WRAPPER, "Control Wrapper" },
{ CTRL_BAR, "BAR" },
{ CTRL_BA, "BA" },
{ CTRL_PS_POLL, "Power Save-Poll" },
{ CTRL_RTS, "Request-To-Send" },
{ CTRL_CTS, "Clear-To-Send" },
{ CTRL_ACK, "Acknowledgment" },
{ CTRL_CF_END, "CF-End" },
{ CTRL_END_ACK, "CF-End+CF-Ack" },
{ 0, NULL }
};
#define DATA_DATA 0x0
#define DATA_DATA_CF_ACK 0x1
#define DATA_DATA_CF_POLL 0x2
#define DATA_DATA_CF_ACK_POLL 0x3
#define DATA_NODATA 0x4
#define DATA_NODATA_CF_ACK 0x5
#define DATA_NODATA_CF_POLL 0x6
#define DATA_NODATA_CF_ACK_POLL 0x7
#define DATA_QOS_DATA 0x8
#define DATA_QOS_DATA_CF_ACK 0x9
#define DATA_QOS_DATA_CF_POLL 0xA
#define DATA_QOS_DATA_CF_ACK_POLL 0xB
#define DATA_QOS_NODATA 0xC
#define DATA_QOS_CF_POLL_NODATA 0xE
#define DATA_QOS_CF_ACK_POLL_NODATA 0xF
/*
* The subtype field of a data frame is, in effect, composed of 4 flag
* bits - CF-Ack, CF-Poll, Null (means the frame doesn't actually have
* any data), and QoS.
*/
#define DATA_FRAME_IS_CF_ACK(x) ((x) & 0x01)
#define DATA_FRAME_IS_CF_POLL(x) ((x) & 0x02)
#define DATA_FRAME_IS_NULL(x) ((x) & 0x04)
#define DATA_FRAME_IS_QOS(x) ((x) & 0x08)
/*
* Bits in the frame control field.
*/
#define FC_VERSION(fc) ((fc) & 0x3)
#define FC_TYPE(fc) (((fc) >> 2) & 0x3)
#define FC_SUBTYPE(fc) (((fc) >> 4) & 0xF)
#define FC_TO_DS(fc) ((fc) & 0x0100)
#define FC_FROM_DS(fc) ((fc) & 0x0200)
#define FC_MORE_FLAG(fc) ((fc) & 0x0400)
#define FC_RETRY(fc) ((fc) & 0x0800)
#define FC_POWER_MGMT(fc) ((fc) & 0x1000)
#define FC_MORE_DATA(fc) ((fc) & 0x2000)
#define FC_PROTECTED(fc) ((fc) & 0x4000)
#define FC_ORDER(fc) ((fc) & 0x8000)
struct mgmt_header_t {
uint16_t fc;
uint16_t duration;
uint8_t da[IEEE802_11_DA_LEN];
uint8_t sa[IEEE802_11_SA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint16_t seq_ctrl;
};
#define MGMT_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_DA_LEN+IEEE802_11_SA_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_SEQ_LEN)
#define CAPABILITY_ESS(cap) ((cap) & 0x0001)
#define CAPABILITY_IBSS(cap) ((cap) & 0x0002)
#define CAPABILITY_CFP(cap) ((cap) & 0x0004)
#define CAPABILITY_CFP_REQ(cap) ((cap) & 0x0008)
#define CAPABILITY_PRIVACY(cap) ((cap) & 0x0010)
struct ssid_t {
uint8_t element_id;
uint8_t length;
u_char ssid[33]; /* 32 + 1 for null */
};
struct rates_t {
uint8_t element_id;
uint8_t length;
uint8_t rate[16];
};
struct challenge_t {
uint8_t element_id;
uint8_t length;
uint8_t text[254]; /* 1-253 + 1 for null */
};
struct fh_t {
uint8_t element_id;
uint8_t length;
uint16_t dwell_time;
uint8_t hop_set;
uint8_t hop_pattern;
uint8_t hop_index;
};
struct ds_t {
uint8_t element_id;
uint8_t length;
uint8_t channel;
};
struct cf_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint16_t max_duration;
uint16_t dur_remaing;
};
struct tim_t {
uint8_t element_id;
uint8_t length;
uint8_t count;
uint8_t period;
uint8_t bitmap_control;
uint8_t bitmap[251];
};
#define E_SSID 0
#define E_RATES 1
#define E_FH 2
#define E_DS 3
#define E_CF 4
#define E_TIM 5
#define E_IBSS 6
/* reserved 7 */
/* reserved 8 */
/* reserved 9 */
/* reserved 10 */
/* reserved 11 */
/* reserved 12 */
/* reserved 13 */
/* reserved 14 */
/* reserved 15 */
/* reserved 16 */
#define E_CHALLENGE 16
/* reserved 17 */
/* reserved 18 */
/* reserved 19 */
/* reserved 16 */
/* reserved 16 */
struct mgmt_body_t {
uint8_t timestamp[IEEE802_11_TSTAMP_LEN];
uint16_t beacon_interval;
uint16_t listen_interval;
uint16_t status_code;
uint16_t aid;
u_char ap[IEEE802_11_AP_LEN];
uint16_t reason_code;
uint16_t auth_alg;
uint16_t auth_trans_seq_num;
int challenge_present;
struct challenge_t challenge;
uint16_t capability_info;
int ssid_present;
struct ssid_t ssid;
int rates_present;
struct rates_t rates;
int ds_present;
struct ds_t ds;
int cf_present;
struct cf_t cf;
int fh_present;
struct fh_t fh;
int tim_present;
struct tim_t tim;
};
struct ctrl_control_wrapper_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t addr1[IEEE802_11_ADDR1_LEN];
uint16_t carried_fc[IEEE802_11_CARRIED_FC_LEN];
uint16_t ht_control[IEEE802_11_HT_CONTROL_LEN];
};
#define CTRL_CONTROL_WRAPPER_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_ADDR1_LEN+\
IEEE802_11_CARRIED_FC_LEN+\
IEEE802_11_HT_CONTROL_LEN)
struct ctrl_rts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_RTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN)
struct ctrl_cts_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_CTS_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_ps_poll_hdr_t {
uint16_t fc;
uint16_t aid;
uint8_t bssid[IEEE802_11_BSSID_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
};
#define CTRL_PS_POLL_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_AID_LEN+\
IEEE802_11_BSSID_LEN+IEEE802_11_TA_LEN)
struct ctrl_end_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_end_ack_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t bssid[IEEE802_11_BSSID_LEN];
};
#define CTRL_END_ACK_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_BSSID_LEN)
struct ctrl_ba_hdr_t {
uint16_t fc;
uint16_t duration;
uint8_t ra[IEEE802_11_RA_LEN];
};
#define CTRL_BA_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+IEEE802_11_RA_LEN)
struct ctrl_bar_hdr_t {
uint16_t fc;
uint16_t dur;
uint8_t ra[IEEE802_11_RA_LEN];
uint8_t ta[IEEE802_11_TA_LEN];
uint16_t ctl;
uint16_t seq;
};
#define CTRL_BAR_HDRLEN (IEEE802_11_FC_LEN+IEEE802_11_DUR_LEN+\
IEEE802_11_RA_LEN+IEEE802_11_TA_LEN+\
IEEE802_11_CTL_LEN+IEEE802_11_SEQ_LEN)
struct meshcntl_t {
uint8_t flags;
uint8_t ttl;
uint8_t seq[4];
uint8_t addr4[6];
uint8_t addr5[6];
uint8_t addr6[6];
};
#define IV_IV(iv) ((iv) & 0xFFFFFF)
#define IV_PAD(iv) (((iv) >> 24) & 0x3F)
#define IV_KEYID(iv) (((iv) >> 30) & 0x03)
#define PRINT_SSID(p) \
if (p.ssid_present) { \
ND_PRINT((ndo, " (")); \
fn_print(ndo, p.ssid.ssid, NULL); \
ND_PRINT((ndo, ")")); \
}
#define PRINT_RATE(_sep, _r, _suf) \
ND_PRINT((ndo, "%s%2.1f%s", _sep, (.5 * ((_r) & 0x7f)), _suf))
#define PRINT_RATES(p) \
if (p.rates_present) { \
int z; \
const char *sep = " ["; \
for (z = 0; z < p.rates.length ; z++) { \
PRINT_RATE(sep, p.rates.rate[z], \
(p.rates.rate[z] & 0x80 ? "*" : "")); \
sep = " "; \
} \
if (p.rates.length != 0) \
ND_PRINT((ndo, " Mbit]")); \
}
#define PRINT_DS_CHANNEL(p) \
if (p.ds_present) \
ND_PRINT((ndo, " CH: %u", p.ds.channel)); \
ND_PRINT((ndo, "%s", \
CAPABILITY_PRIVACY(p.capability_info) ? ", PRIVACY" : ""));
#define MAX_MCS_INDEX 76
/*
* Indices are:
*
* the MCS index (0-76);
*
* 0 for 20 MHz, 1 for 40 MHz;
*
* 0 for a long guard interval, 1 for a short guard interval.
*/
static const float ieee80211_float_htrates[MAX_MCS_INDEX+1][2][2] = {
/* MCS 0 */
{ /* 20 Mhz */ { 6.5, /* SGI */ 7.2, },
/* 40 Mhz */ { 13.5, /* SGI */ 15.0, },
},
/* MCS 1 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 2 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 3 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 4 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 5 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 6 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 7 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 8 */
{ /* 20 Mhz */ { 13.0, /* SGI */ 14.4, },
/* 40 Mhz */ { 27.0, /* SGI */ 30.0, },
},
/* MCS 9 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 10 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 11 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 12 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 13 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 14 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 15 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 16 */
{ /* 20 Mhz */ { 19.5, /* SGI */ 21.7, },
/* 40 Mhz */ { 40.5, /* SGI */ 45.0, },
},
/* MCS 17 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 18 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 19 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 20 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 21 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 22 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 23 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 24 */
{ /* 20 Mhz */ { 26.0, /* SGI */ 28.9, },
/* 40 Mhz */ { 54.0, /* SGI */ 60.0, },
},
/* MCS 25 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 26 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 27 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 28 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 29 */
{ /* 20 Mhz */ { 208.0, /* SGI */ 231.1, },
/* 40 Mhz */ { 432.0, /* SGI */ 480.0, },
},
/* MCS 30 */
{ /* 20 Mhz */ { 234.0, /* SGI */ 260.0, },
/* 40 Mhz */ { 486.0, /* SGI */ 540.0, },
},
/* MCS 31 */
{ /* 20 Mhz */ { 260.0, /* SGI */ 288.9, },
/* 40 Mhz */ { 540.0, /* SGI */ 600.0, },
},
/* MCS 32 */
{ /* 20 Mhz */ { 0.0, /* SGI */ 0.0, }, /* not valid */
/* 40 Mhz */ { 6.0, /* SGI */ 6.7, },
},
/* MCS 33 */
{ /* 20 Mhz */ { 39.0, /* SGI */ 43.3, },
/* 40 Mhz */ { 81.0, /* SGI */ 90.0, },
},
/* MCS 34 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 35 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 36 */
{ /* 20 Mhz */ { 58.5, /* SGI */ 65.0, },
/* 40 Mhz */ { 121.5, /* SGI */ 135.0, },
},
/* MCS 37 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 38 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 39 */
{ /* 20 Mhz */ { 52.0, /* SGI */ 57.8, },
/* 40 Mhz */ { 108.0, /* SGI */ 120.0, },
},
/* MCS 40 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 41 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 42 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 43 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 44 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 45 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 46 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 47 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 48 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 49 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 50 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 51 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 52 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 53 */
{ /* 20 Mhz */ { 65.0, /* SGI */ 72.2, },
/* 40 Mhz */ { 135.0, /* SGI */ 150.0, },
},
/* MCS 54 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 55 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 56 */
{ /* 20 Mhz */ { 78.0, /* SGI */ 86.7, },
/* 40 Mhz */ { 162.0, /* SGI */ 180.0, },
},
/* MCS 57 */
{ /* 20 Mhz */ { 91.0, /* SGI */ 101.1, },
/* 40 Mhz */ { 189.0, /* SGI */ 210.0, },
},
/* MCS 58 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 59 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 60 */
{ /* 20 Mhz */ { 104.0, /* SGI */ 115.6, },
/* 40 Mhz */ { 216.0, /* SGI */ 240.0, },
},
/* MCS 61 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 62 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 63 */
{ /* 20 Mhz */ { 130.0, /* SGI */ 144.4, },
/* 40 Mhz */ { 270.0, /* SGI */ 300.0, },
},
/* MCS 64 */
{ /* 20 Mhz */ { 143.0, /* SGI */ 158.9, },
/* 40 Mhz */ { 297.0, /* SGI */ 330.0, },
},
/* MCS 65 */
{ /* 20 Mhz */ { 97.5, /* SGI */ 108.3, },
/* 40 Mhz */ { 202.5, /* SGI */ 225.0, },
},
/* MCS 66 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 67 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 68 */
{ /* 20 Mhz */ { 117.0, /* SGI */ 130.0, },
/* 40 Mhz */ { 243.0, /* SGI */ 270.0, },
},
/* MCS 69 */
{ /* 20 Mhz */ { 136.5, /* SGI */ 151.7, },
/* 40 Mhz */ { 283.5, /* SGI */ 315.0, },
},
/* MCS 70 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 71 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 72 */
{ /* 20 Mhz */ { 156.0, /* SGI */ 173.3, },
/* 40 Mhz */ { 324.0, /* SGI */ 360.0, },
},
/* MCS 73 */
{ /* 20 Mhz */ { 175.5, /* SGI */ 195.0, },
/* 40 Mhz */ { 364.5, /* SGI */ 405.0, },
},
/* MCS 74 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 75 */
{ /* 20 Mhz */ { 195.0, /* SGI */ 216.7, },
/* 40 Mhz */ { 405.0, /* SGI */ 450.0, },
},
/* MCS 76 */
{ /* 20 Mhz */ { 214.5, /* SGI */ 238.3, },
/* 40 Mhz */ { 445.5, /* SGI */ 495.0, },
},
};
static const char *auth_alg_text[]={"Open System","Shared Key","EAP"};
#define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0])
static const char *status_text[] = {
"Successful", /* 0 */
"Unspecified failure", /* 1 */
"Reserved", /* 2 */
"Reserved", /* 3 */
"Reserved", /* 4 */
"Reserved", /* 5 */
"Reserved", /* 6 */
"Reserved", /* 7 */
"Reserved", /* 8 */
"Reserved", /* 9 */
"Cannot Support all requested capabilities in the Capability "
"Information field", /* 10 */
"Reassociation denied due to inability to confirm that association "
"exists", /* 11 */
"Association denied due to reason outside the scope of the "
"standard", /* 12 */
"Responding station does not support the specified authentication "
"algorithm ", /* 13 */
"Received an Authentication frame with authentication transaction "
"sequence number out of expected sequence", /* 14 */
"Authentication rejected because of challenge failure", /* 15 */
"Authentication rejected due to timeout waiting for next frame in "
"sequence", /* 16 */
"Association denied because AP is unable to handle additional"
"associated stations", /* 17 */
"Association denied due to requesting station not supporting all of "
"the data rates in BSSBasicRateSet parameter", /* 18 */
"Association denied due to requesting station not supporting "
"short preamble operation", /* 19 */
"Association denied due to requesting station not supporting "
"PBCC encoding", /* 20 */
"Association denied due to requesting station not supporting "
"channel agility", /* 21 */
"Association request rejected because Spectrum Management "
"capability is required", /* 22 */
"Association request rejected because the information in the "
"Power Capability element is unacceptable", /* 23 */
"Association request rejected because the information in the "
"Supported Channels element is unacceptable", /* 24 */
"Association denied due to requesting station not supporting "
"short slot operation", /* 25 */
"Association denied due to requesting station not supporting "
"DSSS-OFDM operation", /* 26 */
"Association denied because the requested STA does not support HT "
"features", /* 27 */
"Reserved", /* 28 */
"Association denied because the requested STA does not support "
"the PCO transition time required by the AP", /* 29 */
"Reserved", /* 30 */
"Reserved", /* 31 */
"Unspecified, QoS-related failure", /* 32 */
"Association denied due to QAP having insufficient bandwidth "
"to handle another QSTA", /* 33 */
"Association denied due to excessive frame loss rates and/or "
"poor conditions on current operating channel", /* 34 */
"Association (with QBSS) denied due to requesting station not "
"supporting the QoS facility", /* 35 */
"Association denied due to requesting station not supporting "
"Block Ack", /* 36 */
"The request has been declined", /* 37 */
"The request has not been successful as one or more parameters "
"have invalid values", /* 38 */
"The TS has not been created because the request cannot be honored. "
"Try again with the suggested changes to the TSPEC", /* 39 */
"Invalid Information Element", /* 40 */
"Group Cipher is not valid", /* 41 */
"Pairwise Cipher is not valid", /* 42 */
"AKMP is not valid", /* 43 */
"Unsupported RSN IE version", /* 44 */
"Invalid RSN IE Capabilities", /* 45 */
"Cipher suite is rejected per security policy", /* 46 */
"The TS has not been created. However, the HC may be capable of "
"creating a TS, in response to a request, after the time indicated "
"in the TS Delay element", /* 47 */
"Direct Link is not allowed in the BSS by policy", /* 48 */
"Destination STA is not present within this QBSS.", /* 49 */
"The Destination STA is not a QSTA.", /* 50 */
};
#define NUM_STATUSES (sizeof status_text / sizeof status_text[0])
static const char *reason_text[] = {
"Reserved", /* 0 */
"Unspecified reason", /* 1 */
"Previous authentication no longer valid", /* 2 */
"Deauthenticated because sending station is leaving (or has left) "
"IBSS or ESS", /* 3 */
"Disassociated due to inactivity", /* 4 */
"Disassociated because AP is unable to handle all currently "
" associated stations", /* 5 */
"Class 2 frame received from nonauthenticated station", /* 6 */
"Class 3 frame received from nonassociated station", /* 7 */
"Disassociated because sending station is leaving "
"(or has left) BSS", /* 8 */
"Station requesting (re)association is not authenticated with "
"responding station", /* 9 */
"Disassociated because the information in the Power Capability "
"element is unacceptable", /* 10 */
"Disassociated because the information in the SupportedChannels "
"element is unacceptable", /* 11 */
"Invalid Information Element", /* 12 */
"Reserved", /* 13 */
"Michael MIC failure", /* 14 */
"4-Way Handshake timeout", /* 15 */
"Group key update timeout", /* 16 */
"Information element in 4-Way Handshake different from (Re)Association"
"Request/Probe Response/Beacon", /* 17 */
"Group Cipher is not valid", /* 18 */
"AKMP is not valid", /* 20 */
"Unsupported RSN IE version", /* 21 */
"Invalid RSN IE Capabilities", /* 22 */
"IEEE 802.1X Authentication failed", /* 23 */
"Cipher suite is rejected per security policy", /* 24 */
"Reserved", /* 25 */
"Reserved", /* 26 */
"Reserved", /* 27 */
"Reserved", /* 28 */
"Reserved", /* 29 */
"Reserved", /* 30 */
"TS deleted because QoS AP lacks sufficient bandwidth for this "
"QoS STA due to a change in BSS service characteristics or "
"operational mode (e.g. an HT BSS change from 40 MHz channel "
"to 20 MHz channel)", /* 31 */
"Disassociated for unspecified, QoS-related reason", /* 32 */
"Disassociated because QoS AP lacks sufficient bandwidth for this "
"QoS STA", /* 33 */
"Disassociated because of excessive number of frames that need to be "
"acknowledged, but are not acknowledged for AP transmissions "
"and/or poor channel conditions", /* 34 */
"Disassociated because STA is transmitting outside the limits "
"of its TXOPs", /* 35 */
"Requested from peer STA as the STA is leaving the BSS "
"(or resetting)", /* 36 */
"Requested from peer STA as it does not want to use the "
"mechanism", /* 37 */
"Requested from peer STA as the STA received frames using the "
"mechanism for which a set up is required", /* 38 */
"Requested from peer STA due to time out", /* 39 */
"Reserved", /* 40 */
"Reserved", /* 41 */
"Reserved", /* 42 */
"Reserved", /* 43 */
"Reserved", /* 44 */
"Peer STA does not support the requested cipher suite", /* 45 */
"Association denied due to requesting STA not supporting HT "
"features", /* 46 */
};
#define NUM_REASONS (sizeof reason_text / sizeof reason_text[0])
static int
wep_print(netdissect_options *ndo,
const u_char *p)
{
uint32_t iv;
if (!ND_TTEST2(*p, IEEE802_11_IV_LEN + IEEE802_11_KID_LEN))
return 0;
iv = EXTRACT_LE_32BITS(p);
ND_PRINT((ndo, " IV:%3x Pad %x KeyID %x", IV_IV(iv), IV_PAD(iv),
IV_KEYID(iv)));
return 1;
}
static int
parse_elements(netdissect_options *ndo,
struct mgmt_body_t *pbody, const u_char *p, int offset,
u_int length)
{
u_int elementlen;
struct ssid_t ssid;
struct challenge_t challenge;
struct rates_t rates;
struct ds_t ds;
struct cf_t cf;
struct tim_t tim;
/*
* We haven't seen any elements yet.
*/
pbody->challenge_present = 0;
pbody->ssid_present = 0;
pbody->rates_present = 0;
pbody->ds_present = 0;
pbody->cf_present = 0;
pbody->tim_present = 0;
while (length != 0) {
/* Make sure we at least have the element ID and length. */
if (!ND_TTEST2(*(p + offset), 2))
return 0;
if (length < 2)
return 0;
elementlen = *(p + offset + 1);
/* Make sure we have the entire element. */
if (!ND_TTEST2(*(p + offset + 2), elementlen))
return 0;
if (length < elementlen + 2)
return 0;
switch (*(p + offset)) {
case E_SSID:
memcpy(&ssid, p + offset, 2);
offset += 2;
length -= 2;
if (ssid.length != 0) {
if (ssid.length > sizeof(ssid.ssid) - 1)
return 0;
memcpy(&ssid.ssid, p + offset, ssid.length);
offset += ssid.length;
length -= ssid.length;
}
ssid.ssid[ssid.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen an SSID IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ssid_present) {
pbody->ssid = ssid;
pbody->ssid_present = 1;
}
break;
case E_CHALLENGE:
memcpy(&challenge, p + offset, 2);
offset += 2;
length -= 2;
if (challenge.length != 0) {
if (challenge.length >
sizeof(challenge.text) - 1)
return 0;
memcpy(&challenge.text, p + offset,
challenge.length);
offset += challenge.length;
length -= challenge.length;
}
challenge.text[challenge.length] = '\0';
/*
* Present and not truncated.
*
* If we haven't already seen a challenge IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->challenge_present) {
pbody->challenge = challenge;
pbody->challenge_present = 1;
}
break;
case E_RATES:
memcpy(&rates, p + offset, 2);
offset += 2;
length -= 2;
if (rates.length != 0) {
if (rates.length > sizeof rates.rate)
return 0;
memcpy(&rates.rate, p + offset, rates.length);
offset += rates.length;
length -= rates.length;
}
/*
* Present and not truncated.
*
* If we haven't already seen a rates IE,
* copy this one if it's not zero-length,
* otherwise ignore this one, so we later
* report the first one we saw.
*
* We ignore zero-length rates IEs as some
* devices seem to put a zero-length rates
* IE, followed by an SSID IE, followed by
* a non-zero-length rates IE into frames,
* even though IEEE Std 802.11-2007 doesn't
* seem to indicate that a zero-length rates
* IE is valid.
*/
if (!pbody->rates_present && rates.length != 0) {
pbody->rates = rates;
pbody->rates_present = 1;
}
break;
case E_DS:
memcpy(&ds, p + offset, 2);
offset += 2;
length -= 2;
if (ds.length != 1) {
offset += ds.length;
length -= ds.length;
break;
}
ds.channel = *(p + offset);
offset += 1;
length -= 1;
/*
* Present and not truncated.
*
* If we haven't already seen a DS IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->ds_present) {
pbody->ds = ds;
pbody->ds_present = 1;
}
break;
case E_CF:
memcpy(&cf, p + offset, 2);
offset += 2;
length -= 2;
if (cf.length != 6) {
offset += cf.length;
length -= cf.length;
break;
}
memcpy(&cf.count, p + offset, 6);
offset += 6;
length -= 6;
/*
* Present and not truncated.
*
* If we haven't already seen a CF IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->cf_present) {
pbody->cf = cf;
pbody->cf_present = 1;
}
break;
case E_TIM:
memcpy(&tim, p + offset, 2);
offset += 2;
length -= 2;
if (tim.length <= 3) {
offset += tim.length;
length -= tim.length;
break;
}
if (tim.length - 3 > (int)sizeof tim.bitmap)
return 0;
memcpy(&tim.count, p + offset, 3);
offset += 3;
length -= 3;
memcpy(tim.bitmap, p + offset, tim.length - 3);
offset += tim.length - 3;
length -= tim.length - 3;
/*
* Present and not truncated.
*
* If we haven't already seen a TIM IE,
* copy this one, otherwise ignore this one,
* so we later report the first one we saw.
*/
if (!pbody->tim_present) {
pbody->tim = tim;
pbody->tim_present = 1;
}
break;
default:
#if 0
ND_PRINT((ndo, "(1) unhandled element_id (%d) ",
*(p + offset)));
#endif
offset += 2 + elementlen;
length -= 2 + elementlen;
break;
}
}
/* No problems found. */
return 1;
}
/*********************************************************************************
* Print Handle functions for the management frame types
*********************************************************************************/
static int
handle_beacon(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
ND_PRINT((ndo, " %s",
CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS"));
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_assoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_assoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN +
IEEE802_11_AID_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.status_code = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_STATUS_LEN;
length -= IEEE802_11_STATUS_LEN;
pbody.aid = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_AID_LEN;
length -= IEEE802_11_AID_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
ND_PRINT((ndo, " AID(%x) :%s: %s", ((uint16_t)(pbody.aid << 2 )) >> 2 ,
CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "",
(pbody.status_code < NUM_STATUSES
? status_text[pbody.status_code]
: "n/a")));
return ret;
}
static int
handle_reassoc_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN))
return 0;
if (length < IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN +
IEEE802_11_AP_LEN)
return 0;
pbody.capability_info = EXTRACT_LE_16BITS(p);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
pbody.listen_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_LISTENINT_LEN;
length -= IEEE802_11_LISTENINT_LEN;
memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN);
offset += IEEE802_11_AP_LEN;
length -= IEEE802_11_AP_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
ND_PRINT((ndo, " AP : %s", etheraddr_string(ndo, pbody.ap )));
return ret;
}
static int
handle_reassoc_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
/* Same as a Association Reponse */
return handle_assoc_response(ndo, p, length);
}
static int
handle_probe_request(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
return ret;
}
static int
handle_probe_response(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN))
return 0;
if (length < IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN +
IEEE802_11_CAPINFO_LEN)
return 0;
memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN);
offset += IEEE802_11_TSTAMP_LEN;
length -= IEEE802_11_TSTAMP_LEN;
pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_BCNINT_LEN;
length -= IEEE802_11_BCNINT_LEN;
pbody.capability_info = EXTRACT_LE_16BITS(p+offset);
offset += IEEE802_11_CAPINFO_LEN;
length -= IEEE802_11_CAPINFO_LEN;
ret = parse_elements(ndo, &pbody, p, offset, length);
PRINT_SSID(pbody);
PRINT_RATES(pbody);
PRINT_DS_CHANNEL(pbody);
return ret;
}
static int
handle_atim(void)
{
/* the frame body for ATIM is null. */
return 1;
}
static int
handle_disassoc(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
ND_PRINT((ndo, ": %s",
(pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved"));
return 1;
}
static int
handle_auth(netdissect_options *ndo,
const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
int offset = 0;
int ret;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, 6))
return 0;
if (length < 6)
return 0;
pbody.auth_alg = EXTRACT_LE_16BITS(p);
offset += 2;
length -= 2;
pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
pbody.status_code = EXTRACT_LE_16BITS(p + offset);
offset += 2;
length -= 2;
ret = parse_elements(ndo, &pbody, p, offset, length);
if ((pbody.auth_alg == 1) &&
((pbody.auth_trans_seq_num == 2) ||
(pbody.auth_trans_seq_num == 3))) {
ND_PRINT((ndo, " (%s)-%x [Challenge Text] %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
((pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a") : "")));
return ret;
}
ND_PRINT((ndo, " (%s)-%x: %s",
(pbody.auth_alg < NUM_AUTH_ALGS)
? auth_alg_text[pbody.auth_alg]
: "Reserved",
pbody.auth_trans_seq_num,
(pbody.auth_trans_seq_num % 2)
? ((pbody.status_code < NUM_STATUSES)
? status_text[pbody.status_code]
: "n/a")
: ""));
return ret;
}
static int
handle_deauth(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
struct mgmt_body_t pbody;
const char *reason = NULL;
memset(&pbody, 0, sizeof(pbody));
if (!ND_TTEST2(*p, IEEE802_11_REASON_LEN))
return 0;
if (length < IEEE802_11_REASON_LEN)
return 0;
pbody.reason_code = EXTRACT_LE_16BITS(p);
reason = (pbody.reason_code < NUM_REASONS)
? reason_text[pbody.reason_code]
: "Reserved";
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": %s", reason));
} else {
ND_PRINT((ndo, " (%s): %s", etheraddr_string(ndo, src), reason));
}
return 1;
}
#define PRINT_HT_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "TxChWidth")) : \
(v) == 1 ? ND_PRINT((ndo, "MIMOPwrSave")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_BA_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "ADDBA Request")) : \
(v) == 1 ? ND_PRINT((ndo, "ADDBA Response")) : \
(v) == 2 ? ND_PRINT((ndo, "DELBA")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHLINK_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPEERING_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Open")) : \
(v) == 1 ? ND_PRINT((ndo, "Confirm")) : \
(v) == 2 ? ND_PRINT((ndo, "Close")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESHPATH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Request")) : \
(v) == 1 ? ND_PRINT((ndo, "Report")) : \
(v) == 2 ? ND_PRINT((ndo, "Error")) : \
(v) == 3 ? ND_PRINT((ndo, "RootAnnouncement")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MESH_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "MeshLink")) : \
(v) == 1 ? ND_PRINT((ndo, "HWMP")) : \
(v) == 2 ? ND_PRINT((ndo, "Gate Announcement")) : \
(v) == 3 ? ND_PRINT((ndo, "Congestion Control")) : \
(v) == 4 ? ND_PRINT((ndo, "MCCA Setup Request")) : \
(v) == 5 ? ND_PRINT((ndo, "MCCA Setup Reply")) : \
(v) == 6 ? ND_PRINT((ndo, "MCCA Advertisement Request")) : \
(v) == 7 ? ND_PRINT((ndo, "MCCA Advertisement")) : \
(v) == 8 ? ND_PRINT((ndo, "MCCA Teardown")) : \
(v) == 9 ? ND_PRINT((ndo, "TBTT Adjustment Request")) : \
(v) == 10 ? ND_PRINT((ndo, "TBTT Adjustment Response")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_MULTIHOP_ACTION(v) (\
(v) == 0 ? ND_PRINT((ndo, "Proxy Update")) : \
(v) == 1 ? ND_PRINT((ndo, "Proxy Update Confirmation")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
#define PRINT_SELFPROT_ACTION(v) (\
(v) == 1 ? ND_PRINT((ndo, "Peering Open")) : \
(v) == 2 ? ND_PRINT((ndo, "Peering Confirm")) : \
(v) == 3 ? ND_PRINT((ndo, "Peering Close")) : \
(v) == 4 ? ND_PRINT((ndo, "Group Key Inform")) : \
(v) == 5 ? ND_PRINT((ndo, "Group Key Acknowledge")) : \
ND_PRINT((ndo, "Act#%d", (v))) \
)
static int
handle_action(netdissect_options *ndo,
const uint8_t *src, const u_char *p, u_int length)
{
if (!ND_TTEST2(*p, 2))
return 0;
if (length < 2)
return 0;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, ": "));
} else {
ND_PRINT((ndo, " (%s): ", etheraddr_string(ndo, src)));
}
switch (p[0]) {
case 0: ND_PRINT((ndo, "Spectrum Management Act#%d", p[1])); break;
case 1: ND_PRINT((ndo, "QoS Act#%d", p[1])); break;
case 2: ND_PRINT((ndo, "DLS Act#%d", p[1])); break;
case 3: ND_PRINT((ndo, "BA ")); PRINT_BA_ACTION(p[1]); break;
case 7: ND_PRINT((ndo, "HT ")); PRINT_HT_ACTION(p[1]); break;
case 13: ND_PRINT((ndo, "MeshAction ")); PRINT_MESH_ACTION(p[1]); break;
case 14:
ND_PRINT((ndo, "MultiohopAction "));
PRINT_MULTIHOP_ACTION(p[1]); break;
case 15:
ND_PRINT((ndo, "SelfprotectAction "));
PRINT_SELFPROT_ACTION(p[1]); break;
case 127: ND_PRINT((ndo, "Vendor Act#%d", p[1])); break;
default:
ND_PRINT((ndo, "Reserved(%d) Act#%d", p[0], p[1]));
break;
}
return 1;
}
/*********************************************************************************
* Print Body funcs
*********************************************************************************/
static int
mgmt_body_print(netdissect_options *ndo,
uint16_t fc, const uint8_t *src, const u_char *p, u_int length)
{
ND_PRINT((ndo, "%s", tok2str(st_str, "Unhandled Management subtype(%x)", FC_SUBTYPE(fc))));
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc))
return wep_print(ndo, p);
switch (FC_SUBTYPE(fc)) {
case ST_ASSOC_REQUEST:
return handle_assoc_request(ndo, p, length);
case ST_ASSOC_RESPONSE:
return handle_assoc_response(ndo, p, length);
case ST_REASSOC_REQUEST:
return handle_reassoc_request(ndo, p, length);
case ST_REASSOC_RESPONSE:
return handle_reassoc_response(ndo, p, length);
case ST_PROBE_REQUEST:
return handle_probe_request(ndo, p, length);
case ST_PROBE_RESPONSE:
return handle_probe_response(ndo, p, length);
case ST_BEACON:
return handle_beacon(ndo, p, length);
case ST_ATIM:
return handle_atim();
case ST_DISASSOC:
return handle_disassoc(ndo, p, length);
case ST_AUTH:
return handle_auth(ndo, p, length);
case ST_DEAUTH:
return handle_deauth(ndo, src, p, length);
case ST_ACTION:
return handle_action(ndo, src, p, length);
default:
return 1;
}
}
/*********************************************************************************
* Handles printing all the control frame types
*********************************************************************************/
static int
ctrl_body_print(netdissect_options *ndo,
uint16_t fc, const u_char *p)
{
ND_PRINT((ndo, "%s", tok2str(ctrl_str, "Unknown Ctrl Subtype", FC_SUBTYPE(fc))));
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
/* XXX - requires special handling */
break;
case CTRL_BAR:
if (!ND_TTEST2(*p, CTRL_BAR_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
if (!ND_TTEST2(*p, CTRL_BA_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
if (!ND_TTEST2(*p, CTRL_PS_POLL_HDRLEN))
return 0;
ND_PRINT((ndo, " AID(%x)",
EXTRACT_LE_16BITS(&(((const struct ctrl_ps_poll_hdr_t *)p)->aid))));
break;
case CTRL_RTS:
if (!ND_TTEST2(*p, CTRL_RTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
if (!ND_TTEST2(*p, CTRL_CTS_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
if (!ND_TTEST2(*p, CTRL_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
if (!ND_TTEST2(*p, CTRL_END_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra)));
break;
case CTRL_END_ACK:
if (!ND_TTEST2(*p, CTRL_END_ACK_HDRLEN))
return 0;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, " RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra)));
break;
}
return 1;
}
/*
* Data Frame - Address field contents
*
* To Ds | From DS | Addr 1 | Addr 2 | Addr 3 | Addr 4
* 0 | 0 | DA | SA | BSSID | n/a
* 0 | 1 | DA | BSSID | SA | n/a
* 1 | 0 | BSSID | SA | DA | n/a
* 1 | 1 | RA | TA | DA | SA
*/
/*
* Function to get source and destination MAC addresses for a data frame.
*/
static void
get_data_src_dst_mac(uint16_t fc, const u_char *p, const uint8_t **srcp,
const uint8_t **dstp)
{
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc)) {
if (!FC_FROM_DS(fc)) {
/* not To DS and not From DS */
*srcp = ADDR2;
*dstp = ADDR1;
} else {
/* not To DS and From DS */
*srcp = ADDR3;
*dstp = ADDR1;
}
} else {
if (!FC_FROM_DS(fc)) {
/* From DS and not To DS */
*srcp = ADDR2;
*dstp = ADDR3;
} else {
/* To DS and From DS */
*srcp = ADDR4;
*dstp = ADDR3;
}
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
get_mgmt_src_dst_mac(const u_char *p, const uint8_t **srcp, const uint8_t **dstp)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
if (srcp != NULL)
*srcp = hp->sa;
if (dstp != NULL)
*dstp = hp->da;
}
/*
* Print Header funcs
*/
static void
data_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
u_int subtype = FC_SUBTYPE(fc);
if (DATA_FRAME_IS_CF_ACK(subtype) || DATA_FRAME_IS_CF_POLL(subtype) ||
DATA_FRAME_IS_QOS(subtype)) {
ND_PRINT((ndo, "CF "));
if (DATA_FRAME_IS_CF_ACK(subtype)) {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Ack/Poll"));
else
ND_PRINT((ndo, "Ack"));
} else {
if (DATA_FRAME_IS_CF_POLL(subtype))
ND_PRINT((ndo, "Poll"));
}
if (DATA_FRAME_IS_QOS(subtype))
ND_PRINT((ndo, "+QoS"));
ND_PRINT((ndo, " "));
}
#define ADDR1 (p + 4)
#define ADDR2 (p + 10)
#define ADDR3 (p + 16)
#define ADDR4 (p + 24)
if (!FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s SA:%s BSSID:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (!FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "DA:%s BSSID:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && !FC_FROM_DS(fc)) {
ND_PRINT((ndo, "BSSID:%s SA:%s DA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3)));
} else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) {
ND_PRINT((ndo, "RA:%s TA:%s DA:%s SA:%s ",
etheraddr_string(ndo, ADDR1), etheraddr_string(ndo, ADDR2),
etheraddr_string(ndo, ADDR3), etheraddr_string(ndo, ADDR4)));
}
#undef ADDR1
#undef ADDR2
#undef ADDR3
#undef ADDR4
}
static void
mgmt_header_print(netdissect_options *ndo, const u_char *p)
{
const struct mgmt_header_t *hp = (const struct mgmt_header_t *) p;
ND_PRINT((ndo, "BSSID:%s DA:%s SA:%s ",
etheraddr_string(ndo, (hp)->bssid), etheraddr_string(ndo, (hp)->da),
etheraddr_string(ndo, (hp)->sa)));
}
static void
ctrl_header_print(netdissect_options *ndo, uint16_t fc, const u_char *p)
{
switch (FC_SUBTYPE(fc)) {
case CTRL_BAR:
ND_PRINT((ndo, " RA:%s TA:%s CTL(%x) SEQ(%u) ",
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_bar_hdr_t *)p)->ta),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->ctl)),
EXTRACT_LE_16BITS(&(((const struct ctrl_bar_hdr_t *)p)->seq))));
break;
case CTRL_BA:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ba_hdr_t *)p)->ra)));
break;
case CTRL_PS_POLL:
ND_PRINT((ndo, "BSSID:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->bssid),
etheraddr_string(ndo, ((const struct ctrl_ps_poll_hdr_t *)p)->ta)));
break;
case CTRL_RTS:
ND_PRINT((ndo, "RA:%s TA:%s ",
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_rts_hdr_t *)p)->ta)));
break;
case CTRL_CTS:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_cts_hdr_t *)p)->ra)));
break;
case CTRL_ACK:
ND_PRINT((ndo, "RA:%s ",
etheraddr_string(ndo, ((const struct ctrl_ack_hdr_t *)p)->ra)));
break;
case CTRL_CF_END:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_hdr_t *)p)->bssid)));
break;
case CTRL_END_ACK:
ND_PRINT((ndo, "RA:%s BSSID:%s ",
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->ra),
etheraddr_string(ndo, ((const struct ctrl_end_ack_hdr_t *)p)->bssid)));
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
}
static int
extract_header_length(netdissect_options *ndo,
uint16_t fc)
{
int len;
switch (FC_TYPE(fc)) {
case T_MGMT:
return MGMT_HDRLEN;
case T_CTRL:
switch (FC_SUBTYPE(fc)) {
case CTRL_CONTROL_WRAPPER:
return CTRL_CONTROL_WRAPPER_HDRLEN;
case CTRL_BAR:
return CTRL_BAR_HDRLEN;
case CTRL_BA:
return CTRL_BA_HDRLEN;
case CTRL_PS_POLL:
return CTRL_PS_POLL_HDRLEN;
case CTRL_RTS:
return CTRL_RTS_HDRLEN;
case CTRL_CTS:
return CTRL_CTS_HDRLEN;
case CTRL_ACK:
return CTRL_ACK_HDRLEN;
case CTRL_CF_END:
return CTRL_END_HDRLEN;
case CTRL_END_ACK:
return CTRL_END_ACK_HDRLEN;
default:
ND_PRINT((ndo, "unknown 802.11 ctrl frame subtype (%d)", FC_SUBTYPE(fc)));
return 0;
}
case T_DATA:
len = (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24;
if (DATA_FRAME_IS_QOS(FC_SUBTYPE(fc)))
len += 2;
return len;
default:
ND_PRINT((ndo, "unknown 802.11 frame type (%d)", FC_TYPE(fc)));
return 0;
}
}
static int
extract_mesh_header_length(const u_char *p)
{
return (p[0] &~ 3) ? 0 : 6*(1 + (p[0] & 3));
}
/*
* Print the 802.11 MAC header.
*/
static void
ieee_802_11_hdr_print(netdissect_options *ndo,
uint16_t fc, const u_char *p, u_int hdrlen,
u_int meshdrlen)
{
if (ndo->ndo_vflag) {
if (FC_MORE_DATA(fc))
ND_PRINT((ndo, "More Data "));
if (FC_MORE_FLAG(fc))
ND_PRINT((ndo, "More Fragments "));
if (FC_POWER_MGMT(fc))
ND_PRINT((ndo, "Pwr Mgmt "));
if (FC_RETRY(fc))
ND_PRINT((ndo, "Retry "));
if (FC_ORDER(fc))
ND_PRINT((ndo, "Strictly Ordered "));
if (FC_PROTECTED(fc))
ND_PRINT((ndo, "Protected "));
if (FC_TYPE(fc) != T_CTRL || FC_SUBTYPE(fc) != CTRL_PS_POLL)
ND_PRINT((ndo, "%dus ",
EXTRACT_LE_16BITS(
&((const struct mgmt_header_t *)p)->duration)));
}
if (meshdrlen != 0) {
const struct meshcntl_t *mc =
(const struct meshcntl_t *)&p[hdrlen - meshdrlen];
int ae = mc->flags & 3;
ND_PRINT((ndo, "MeshData (AE %d TTL %u seq %u", ae, mc->ttl,
EXTRACT_LE_32BITS(mc->seq)));
if (ae > 0)
ND_PRINT((ndo, " A4:%s", etheraddr_string(ndo, mc->addr4)));
if (ae > 1)
ND_PRINT((ndo, " A5:%s", etheraddr_string(ndo, mc->addr5)));
if (ae > 2)
ND_PRINT((ndo, " A6:%s", etheraddr_string(ndo, mc->addr6)));
ND_PRINT((ndo, ") "));
}
switch (FC_TYPE(fc)) {
case T_MGMT:
mgmt_header_print(ndo, p);
break;
case T_CTRL:
ctrl_header_print(ndo, fc, p);
break;
case T_DATA:
data_header_print(ndo, fc, p);
break;
default:
break;
}
}
#ifndef roundup2
#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */
#endif
static const char tstr[] = "[|802.11]";
static u_int
ieee802_11_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int orig_caplen, int pad,
u_int fcslen)
{
uint16_t fc;
u_int caplen, hdrlen, meshdrlen;
struct lladdr_info src, dst;
int llc_hdrlen;
caplen = orig_caplen;
/* Remove FCS, if present */
if (length < fcslen) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
length -= fcslen;
if (caplen > length) {
/* Amount of FCS in actual packet data, if any */
fcslen = caplen - length;
caplen -= fcslen;
ndo->ndo_snapend -= fcslen;
}
if (caplen < IEEE802_11_FC_LEN) {
ND_PRINT((ndo, "%s", tstr));
return orig_caplen;
}
fc = EXTRACT_LE_16BITS(p);
hdrlen = extract_header_length(ndo, fc);
if (hdrlen == 0) {
/* Unknown frame type or control frame subtype; quit. */
return (0);
}
if (pad)
hdrlen = roundup2(hdrlen, 4);
if (ndo->ndo_Hflag && FC_TYPE(fc) == T_DATA &&
DATA_FRAME_IS_QOS(FC_SUBTYPE(fc))) {
meshdrlen = extract_mesh_header_length(p+hdrlen);
hdrlen += meshdrlen;
} else
meshdrlen = 0;
if (caplen < hdrlen) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
if (ndo->ndo_eflag)
ieee_802_11_hdr_print(ndo, fc, p, hdrlen, meshdrlen);
/*
* Go past the 802.11 header.
*/
length -= hdrlen;
caplen -= hdrlen;
p += hdrlen;
src.addr_string = etheraddr_string;
dst.addr_string = etheraddr_string;
switch (FC_TYPE(fc)) {
case T_MGMT:
get_mgmt_src_dst_mac(p - hdrlen, &src.addr, &dst.addr);
if (!mgmt_body_print(ndo, fc, src.addr, p, length)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_CTRL:
if (!ctrl_body_print(ndo, fc, p - hdrlen)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
break;
case T_DATA:
if (DATA_FRAME_IS_NULL(FC_SUBTYPE(fc)))
return hdrlen; /* no-data frame */
/* There may be a problem w/ AP not having this bit set */
if (FC_PROTECTED(fc)) {
ND_PRINT((ndo, "Data"));
if (!wep_print(ndo, p)) {
ND_PRINT((ndo, "%s", tstr));
return hdrlen;
}
} else {
get_data_src_dst_mac(fc, p - hdrlen, &src.addr, &dst.addr);
llc_hdrlen = llc_print(ndo, p, length, caplen, &src, &dst);
if (llc_hdrlen < 0) {
/*
* Some kinds of LLC packet we cannot
* handle intelligently
*/
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
llc_hdrlen = -llc_hdrlen;
}
hdrlen += llc_hdrlen;
}
break;
default:
/* We shouldn't get here - we should already have quit */
break;
}
return hdrlen;
}
/*
* This is the top level routine of the printer. 'p' points
* to the 802.11 header of the packet, 'h->ts' is the timestamp,
* 'h->len' is the length of the packet off the wire, and 'h->caplen'
* is the number of bytes actually captured.
*/
u_int
ieee802_11_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_print(ndo, p, h->len, h->caplen, 0, 0);
}
/* $FreeBSD: src/sys/net80211/ieee80211_radiotap.h,v 1.5 2005/01/22 20:12:05 sam Exp $ */
/* NetBSD: ieee802_11_radio.h,v 1.2 2006/02/26 03:04:03 dyoung Exp */
/*-
* Copyright (c) 2003, 2004 David Young. 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.
* 3. The name of David Young may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY DAVID YOUNG ``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 DAVID
* YOUNG 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.
*/
/* A generic radio capture format is desirable. It must be
* rigidly defined (e.g., units for fields should be given),
* and easily extensible.
*
* The following is an extensible radio capture format. It is
* based on a bitmap indicating which fields are present.
*
* I am trying to describe precisely what the application programmer
* should expect in the following, and for that reason I tell the
* units and origin of each measurement (where it applies), or else I
* use sufficiently weaselly language ("is a monotonically nondecreasing
* function of...") that I cannot set false expectations for lawyerly
* readers.
*/
/*
* The radio capture header precedes the 802.11 header.
*
* Note well: all radiotap fields are little-endian.
*/
struct ieee80211_radiotap_header {
uint8_t it_version; /* Version 0. Only increases
* for drastic changes,
* introduction of compatible
* new fields does not count.
*/
uint8_t it_pad;
uint16_t it_len; /* length of the whole
* header in bytes, including
* it_version, it_pad,
* it_len, and data fields.
*/
uint32_t it_present; /* A bitmap telling which
* fields are present. Set bit 31
* (0x80000000) to extend the
* bitmap by another 32 bits.
* Additional extensions are made
* by setting bit 31.
*/
};
/* Name Data type Units
* ---- --------- -----
*
* IEEE80211_RADIOTAP_TSFT uint64_t microseconds
*
* Value in microseconds of the MAC's 64-bit 802.11 Time
* Synchronization Function timer when the first bit of the
* MPDU arrived at the MAC. For received frames, only.
*
* IEEE80211_RADIOTAP_CHANNEL 2 x uint16_t MHz, bitmap
*
* Tx/Rx frequency in MHz, followed by flags (see below).
* Note that IEEE80211_RADIOTAP_XCHANNEL must be used to
* represent an HT channel as there is not enough room in
* the flags word.
*
* IEEE80211_RADIOTAP_FHSS uint16_t see below
*
* For frequency-hopping radios, the hop set (first byte)
* and pattern (second byte).
*
* IEEE80211_RADIOTAP_RATE uint8_t 500kb/s or index
*
* Tx/Rx data rate. If bit 0x80 is set then it represents an
* an MCS index and not an IEEE rate.
*
* IEEE80211_RADIOTAP_DBM_ANTSIGNAL int8_t decibels from
* one milliwatt (dBm)
*
* RF signal power at the antenna, decibel difference from
* one milliwatt.
*
* IEEE80211_RADIOTAP_DBM_ANTNOISE int8_t decibels from
* one milliwatt (dBm)
*
* RF noise power at the antenna, decibel difference from one
* milliwatt.
*
* IEEE80211_RADIOTAP_DB_ANTSIGNAL uint8_t decibel (dB)
*
* RF signal power at the antenna, decibel difference from an
* arbitrary, fixed reference.
*
* IEEE80211_RADIOTAP_DB_ANTNOISE uint8_t decibel (dB)
*
* RF noise power at the antenna, decibel difference from an
* arbitrary, fixed reference point.
*
* IEEE80211_RADIOTAP_LOCK_QUALITY uint16_t unitless
*
* Quality of Barker code lock. Unitless. Monotonically
* nondecreasing with "better" lock strength. Called "Signal
* Quality" in datasheets. (Is there a standard way to measure
* this?)
*
* IEEE80211_RADIOTAP_TX_ATTENUATION uint16_t unitless
*
* Transmit power expressed as unitless distance from max
* power set at factory calibration. 0 is max power.
* Monotonically nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DB_TX_ATTENUATION uint16_t decibels (dB)
*
* Transmit power expressed as decibel distance from max power
* set at factory calibration. 0 is max power. Monotonically
* nondecreasing with lower power levels.
*
* IEEE80211_RADIOTAP_DBM_TX_POWER int8_t decibels from
* one milliwatt (dBm)
*
* Transmit power expressed as dBm (decibels from a 1 milliwatt
* reference). This is the absolute power level measured at
* the antenna port.
*
* IEEE80211_RADIOTAP_FLAGS uint8_t bitmap
*
* Properties of transmitted and received frames. See flags
* defined below.
*
* IEEE80211_RADIOTAP_ANTENNA uint8_t antenna index
*
* Unitless indication of the Rx/Tx antenna for this packet.
* The first antenna is antenna 0.
*
* IEEE80211_RADIOTAP_RX_FLAGS uint16_t bitmap
*
* Properties of received frames. See flags defined below.
*
* IEEE80211_RADIOTAP_XCHANNEL uint32_t bitmap
* uint16_t MHz
* uint8_t channel number
* uint8_t .5 dBm
*
* Extended channel specification: flags (see below) followed by
* frequency in MHz, the corresponding IEEE channel number, and
* finally the maximum regulatory transmit power cap in .5 dBm
* units. This property supersedes IEEE80211_RADIOTAP_CHANNEL
* and only one of the two should be present.
*
* IEEE80211_RADIOTAP_MCS uint8_t known
* uint8_t flags
* uint8_t mcs
*
* Bitset indicating which fields have known values, followed
* by bitset of flag values, followed by the MCS rate index as
* in IEEE 802.11n.
*
*
* IEEE80211_RADIOTAP_AMPDU_STATUS u32, u16, u8, u8 unitless
*
* Contains the AMPDU information for the subframe.
*
* IEEE80211_RADIOTAP_VHT u16, u8, u8, u8[4], u8, u8, u16
*
* Contains VHT information about this frame.
*
* IEEE80211_RADIOTAP_VENDOR_NAMESPACE
* uint8_t OUI[3]
* uint8_t subspace
* uint16_t length
*
* The Vendor Namespace Field contains three sub-fields. The first
* sub-field is 3 bytes long. It contains the vendor's IEEE 802
* Organizationally Unique Identifier (OUI). The fourth byte is a
* vendor-specific "namespace selector."
*
*/
enum ieee80211_radiotap_type {
IEEE80211_RADIOTAP_TSFT = 0,
IEEE80211_RADIOTAP_FLAGS = 1,
IEEE80211_RADIOTAP_RATE = 2,
IEEE80211_RADIOTAP_CHANNEL = 3,
IEEE80211_RADIOTAP_FHSS = 4,
IEEE80211_RADIOTAP_DBM_ANTSIGNAL = 5,
IEEE80211_RADIOTAP_DBM_ANTNOISE = 6,
IEEE80211_RADIOTAP_LOCK_QUALITY = 7,
IEEE80211_RADIOTAP_TX_ATTENUATION = 8,
IEEE80211_RADIOTAP_DB_TX_ATTENUATION = 9,
IEEE80211_RADIOTAP_DBM_TX_POWER = 10,
IEEE80211_RADIOTAP_ANTENNA = 11,
IEEE80211_RADIOTAP_DB_ANTSIGNAL = 12,
IEEE80211_RADIOTAP_DB_ANTNOISE = 13,
IEEE80211_RADIOTAP_RX_FLAGS = 14,
/* NB: gap for netbsd definitions */
IEEE80211_RADIOTAP_XCHANNEL = 18,
IEEE80211_RADIOTAP_MCS = 19,
IEEE80211_RADIOTAP_AMPDU_STATUS = 20,
IEEE80211_RADIOTAP_VHT = 21,
IEEE80211_RADIOTAP_NAMESPACE = 29,
IEEE80211_RADIOTAP_VENDOR_NAMESPACE = 30,
IEEE80211_RADIOTAP_EXT = 31
};
/* channel attributes */
#define IEEE80211_CHAN_TURBO 0x00010 /* Turbo channel */
#define IEEE80211_CHAN_CCK 0x00020 /* CCK channel */
#define IEEE80211_CHAN_OFDM 0x00040 /* OFDM channel */
#define IEEE80211_CHAN_2GHZ 0x00080 /* 2 GHz spectrum channel. */
#define IEEE80211_CHAN_5GHZ 0x00100 /* 5 GHz spectrum channel */
#define IEEE80211_CHAN_PASSIVE 0x00200 /* Only passive scan allowed */
#define IEEE80211_CHAN_DYN 0x00400 /* Dynamic CCK-OFDM channel */
#define IEEE80211_CHAN_GFSK 0x00800 /* GFSK channel (FHSS PHY) */
#define IEEE80211_CHAN_GSM 0x01000 /* 900 MHz spectrum channel */
#define IEEE80211_CHAN_STURBO 0x02000 /* 11a static turbo channel only */
#define IEEE80211_CHAN_HALF 0x04000 /* Half rate channel */
#define IEEE80211_CHAN_QUARTER 0x08000 /* Quarter rate channel */
#define IEEE80211_CHAN_HT20 0x10000 /* HT 20 channel */
#define IEEE80211_CHAN_HT40U 0x20000 /* HT 40 channel w/ ext above */
#define IEEE80211_CHAN_HT40D 0x40000 /* HT 40 channel w/ ext below */
/* Useful combinations of channel characteristics, borrowed from Ethereal */
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IEEE80211_CHAN_TA \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM | IEEE80211_CHAN_TURBO)
#define IEEE80211_CHAN_TG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN | IEEE80211_CHAN_TURBO)
/* For IEEE80211_RADIOTAP_FLAGS */
#define IEEE80211_RADIOTAP_F_CFP 0x01 /* sent/received
* during CFP
*/
#define IEEE80211_RADIOTAP_F_SHORTPRE 0x02 /* sent/received
* with short
* preamble
*/
#define IEEE80211_RADIOTAP_F_WEP 0x04 /* sent/received
* with WEP encryption
*/
#define IEEE80211_RADIOTAP_F_FRAG 0x08 /* sent/received
* with fragmentation
*/
#define IEEE80211_RADIOTAP_F_FCS 0x10 /* frame includes FCS */
#define IEEE80211_RADIOTAP_F_DATAPAD 0x20 /* frame has padding between
* 802.11 header and payload
* (to 32-bit boundary)
*/
#define IEEE80211_RADIOTAP_F_BADFCS 0x40 /* does not pass FCS check */
/* For IEEE80211_RADIOTAP_RX_FLAGS */
#define IEEE80211_RADIOTAP_F_RX_BADFCS 0x0001 /* frame failed crc check */
#define IEEE80211_RADIOTAP_F_RX_PLCP_CRC 0x0002 /* frame failed PLCP CRC check */
/* For IEEE80211_RADIOTAP_MCS known */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN 0x01
#define IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN 0x02 /* MCS index field */
#define IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN 0x04
#define IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_KNOWN 0x20
#define IEEE80211_RADIOTAP_MCS_NESS_KNOWN 0x40
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_1 0x80
/* For IEEE80211_RADIOTAP_MCS flags */
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK 0x03
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20 0
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 1
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20L 2
#define IEEE80211_RADIOTAP_MCS_BANDWIDTH_20U 3
#define IEEE80211_RADIOTAP_MCS_SHORT_GI 0x04 /* short guard interval */
#define IEEE80211_RADIOTAP_MCS_HT_GREENFIELD 0x08
#define IEEE80211_RADIOTAP_MCS_FEC_LDPC 0x10
#define IEEE80211_RADIOTAP_MCS_STBC_MASK 0x60
#define IEEE80211_RADIOTAP_MCS_STBC_1 1
#define IEEE80211_RADIOTAP_MCS_STBC_2 2
#define IEEE80211_RADIOTAP_MCS_STBC_3 3
#define IEEE80211_RADIOTAP_MCS_STBC_SHIFT 5
#define IEEE80211_RADIOTAP_MCS_NESS_BIT_0 0x80
/* For IEEE80211_RADIOTAP_AMPDU_STATUS */
#define IEEE80211_RADIOTAP_AMPDU_REPORT_ZEROLEN 0x0001
#define IEEE80211_RADIOTAP_AMPDU_IS_ZEROLEN 0x0002
#define IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN 0x0004
#define IEEE80211_RADIOTAP_AMPDU_IS_LAST 0x0008
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR 0x0010
#define IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN 0x0020
/* For IEEE80211_RADIOTAP_VHT known */
#define IEEE80211_RADIOTAP_VHT_STBC_KNOWN 0x0001
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA_KNOWN 0x0002
#define IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN 0x0004
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_DIS_KNOWN 0x0008
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM_KNOWN 0x0010
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED_KNOWN 0x0020
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN 0x0040
#define IEEE80211_RADIOTAP_VHT_GROUP_ID_KNOWN 0x0080
#define IEEE80211_RADIOTAP_VHT_PARTIAL_AID_KNOWN 0x0100
/* For IEEE80211_RADIOTAP_VHT flags */
#define IEEE80211_RADIOTAP_VHT_STBC 0x01
#define IEEE80211_RADIOTAP_VHT_TXOP_PS_NA 0x02
#define IEEE80211_RADIOTAP_VHT_SHORT_GI 0x04
#define IEEE80211_RADIOTAP_VHT_SGI_NSYM_M10_9 0x08
#define IEEE80211_RADIOTAP_VHT_LDPC_EXTRA_OFDM_SYM 0x10
#define IEEE80211_RADIOTAP_VHT_BEAMFORMED 0x20
#define IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK 0x1f
#define IEEE80211_RADIOTAP_VHT_NSS_MASK 0x0f
#define IEEE80211_RADIOTAP_VHT_MCS_MASK 0xf0
#define IEEE80211_RADIOTAP_VHT_MCS_SHIFT 4
#define IEEE80211_RADIOTAP_CODING_LDPC_USERn 0x01
#define IEEE80211_CHAN_FHSS \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_GFSK)
#define IEEE80211_CHAN_A \
(IEEE80211_CHAN_5GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_B \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_CCK)
#define IEEE80211_CHAN_PUREG \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_OFDM)
#define IEEE80211_CHAN_G \
(IEEE80211_CHAN_2GHZ | IEEE80211_CHAN_DYN)
#define IS_CHAN_FHSS(flags) \
((flags & IEEE80211_CHAN_FHSS) == IEEE80211_CHAN_FHSS)
#define IS_CHAN_A(flags) \
((flags & IEEE80211_CHAN_A) == IEEE80211_CHAN_A)
#define IS_CHAN_B(flags) \
((flags & IEEE80211_CHAN_B) == IEEE80211_CHAN_B)
#define IS_CHAN_PUREG(flags) \
((flags & IEEE80211_CHAN_PUREG) == IEEE80211_CHAN_PUREG)
#define IS_CHAN_G(flags) \
((flags & IEEE80211_CHAN_G) == IEEE80211_CHAN_G)
#define IS_CHAN_ANYG(flags) \
(IS_CHAN_PUREG(flags) || IS_CHAN_G(flags))
static void
print_chaninfo(netdissect_options *ndo,
uint16_t freq, int flags, int presentflags)
{
ND_PRINT((ndo, "%u MHz", freq));
if (presentflags & (1 << IEEE80211_RADIOTAP_MCS)) {
/*
* We have the MCS field, so this is 11n, regardless
* of what the channel flags say.
*/
ND_PRINT((ndo, " 11n"));
} else {
if (IS_CHAN_FHSS(flags))
ND_PRINT((ndo, " FHSS"));
if (IS_CHAN_A(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11a/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11a/5Mhz"));
else
ND_PRINT((ndo, " 11a"));
}
if (IS_CHAN_ANYG(flags)) {
if (flags & IEEE80211_CHAN_HALF)
ND_PRINT((ndo, " 11g/10Mhz"));
else if (flags & IEEE80211_CHAN_QUARTER)
ND_PRINT((ndo, " 11g/5Mhz"));
else
ND_PRINT((ndo, " 11g"));
} else if (IS_CHAN_B(flags))
ND_PRINT((ndo, " 11b"));
if (flags & IEEE80211_CHAN_TURBO)
ND_PRINT((ndo, " Turbo"));
}
/*
* These apply to 11n.
*/
if (flags & IEEE80211_CHAN_HT20)
ND_PRINT((ndo, " ht/20"));
else if (flags & IEEE80211_CHAN_HT40D)
ND_PRINT((ndo, " ht/40-"));
else if (flags & IEEE80211_CHAN_HT40U)
ND_PRINT((ndo, " ht/40+"));
ND_PRINT((ndo, " "));
}
static int
print_radiotap_field(netdissect_options *ndo,
struct cpack_state *s, uint32_t bit, uint8_t *flagsp,
uint32_t presentflags)
{
u_int i;
int rc;
switch (bit) {
case IEEE80211_RADIOTAP_TSFT: {
uint64_t tsft;
rc = cpack_uint64(s, &tsft);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%" PRIu64 "us tsft ", tsft));
break;
}
case IEEE80211_RADIOTAP_FLAGS: {
uint8_t flagsval;
rc = cpack_uint8(s, &flagsval);
if (rc != 0)
goto trunc;
*flagsp = flagsval;
if (flagsval & IEEE80211_RADIOTAP_F_CFP)
ND_PRINT((ndo, "cfp "));
if (flagsval & IEEE80211_RADIOTAP_F_SHORTPRE)
ND_PRINT((ndo, "short preamble "));
if (flagsval & IEEE80211_RADIOTAP_F_WEP)
ND_PRINT((ndo, "wep "));
if (flagsval & IEEE80211_RADIOTAP_F_FRAG)
ND_PRINT((ndo, "fragmented "));
if (flagsval & IEEE80211_RADIOTAP_F_BADFCS)
ND_PRINT((ndo, "bad-fcs "));
break;
}
case IEEE80211_RADIOTAP_RATE: {
uint8_t rate;
rc = cpack_uint8(s, &rate);
if (rc != 0)
goto trunc;
/*
* XXX On FreeBSD rate & 0x80 means we have an MCS. On
* Linux and AirPcap it does not. (What about
* Mac OS X, NetBSD, OpenBSD, and DragonFly BSD?)
*
* This is an issue either for proprietary extensions
* to 11a or 11g, which do exist, or for 11n
* implementations that stuff a rate value into
* this field, which also appear to exist.
*
* We currently handle that by assuming that
* if the 0x80 bit is set *and* the remaining
* bits have a value between 0 and 15 it's
* an MCS value, otherwise it's a rate. If
* there are cases where systems that use
* "0x80 + MCS index" for MCS indices > 15,
* or stuff a rate value here between 64 and
* 71.5 Mb/s in here, we'll need a preference
* setting. Such rates do exist, e.g. 11n
* MCS 7 at 20 MHz with a long guard interval.
*/
if (rate >= 0x80 && rate <= 0x8f) {
/*
* XXX - we don't know the channel width
* or guard interval length, so we can't
* convert this to a data rate.
*
* If you want us to show a data rate,
* use the MCS field, not the Rate field;
* the MCS field includes not only the
* MCS index, it also includes bandwidth
* and guard interval information.
*
* XXX - can we get the channel width
* from XChannel and the guard interval
* information from Flags, at least on
* FreeBSD?
*/
ND_PRINT((ndo, "MCS %u ", rate & 0x7f));
} else
ND_PRINT((ndo, "%2.1f Mb/s ", .5 * rate));
break;
}
case IEEE80211_RADIOTAP_CHANNEL: {
uint16_t frequency;
uint16_t flags;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
/*
* If CHANNEL and XCHANNEL are both present, skip
* CHANNEL.
*/
if (presentflags & (1 << IEEE80211_RADIOTAP_XCHANNEL))
break;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_FHSS: {
uint8_t hopset;
uint8_t hoppat;
rc = cpack_uint8(s, &hopset);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &hoppat);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "fhset %d fhpat %d ", hopset, hoppat));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: {
int8_t dbm_antsignal;
rc = cpack_int8(s, &dbm_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm signal ", dbm_antsignal));
break;
}
case IEEE80211_RADIOTAP_DBM_ANTNOISE: {
int8_t dbm_antnoise;
rc = cpack_int8(s, &dbm_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm noise ", dbm_antnoise));
break;
}
case IEEE80211_RADIOTAP_LOCK_QUALITY: {
uint16_t lock_quality;
rc = cpack_uint16(s, &lock_quality);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%u sq ", lock_quality));
break;
}
case IEEE80211_RADIOTAP_TX_ATTENUATION: {
uint16_t tx_attenuation;
rc = cpack_uint16(s, &tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%d tx power ", -(int)tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: {
uint8_t db_tx_attenuation;
rc = cpack_uint8(s, &db_tx_attenuation);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB tx attenuation ", -(int)db_tx_attenuation));
break;
}
case IEEE80211_RADIOTAP_DBM_TX_POWER: {
int8_t dbm_tx_power;
rc = cpack_int8(s, &dbm_tx_power);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddBm tx power ", dbm_tx_power));
break;
}
case IEEE80211_RADIOTAP_ANTENNA: {
uint8_t antenna;
rc = cpack_uint8(s, &antenna);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "antenna %u ", antenna));
break;
}
case IEEE80211_RADIOTAP_DB_ANTSIGNAL: {
uint8_t db_antsignal;
rc = cpack_uint8(s, &db_antsignal);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB signal ", db_antsignal));
break;
}
case IEEE80211_RADIOTAP_DB_ANTNOISE: {
uint8_t db_antnoise;
rc = cpack_uint8(s, &db_antnoise);
if (rc != 0)
goto trunc;
ND_PRINT((ndo, "%ddB noise ", db_antnoise));
break;
}
case IEEE80211_RADIOTAP_RX_FLAGS: {
uint16_t rx_flags;
rc = cpack_uint16(s, &rx_flags);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_XCHANNEL: {
uint32_t flags;
uint16_t frequency;
uint8_t channel;
uint8_t maxpower;
rc = cpack_uint32(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &frequency);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &channel);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &maxpower);
if (rc != 0)
goto trunc;
print_chaninfo(ndo, frequency, flags, presentflags);
break;
}
case IEEE80211_RADIOTAP_MCS: {
uint8_t known;
uint8_t flags;
uint8_t mcs_index;
static const char *ht_bandwidth[4] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)"
};
float htrate;
rc = cpack_uint8(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &mcs_index);
if (rc != 0)
goto trunc;
if (known & IEEE80211_RADIOTAP_MCS_MCS_INDEX_KNOWN) {
/*
* We know the MCS index.
*/
if (mcs_index <= MAX_MCS_INDEX) {
/*
* And it's in-range.
*/
if (known & (IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN|IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN)) {
/*
* And we know both the bandwidth and
* the guard interval, so we can look
* up the rate.
*/
htrate =
ieee80211_float_htrates \
[mcs_index] \
[((flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK) == IEEE80211_RADIOTAP_MCS_BANDWIDTH_40 ? 1 : 0)] \
[((flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ? 1 : 0)];
} else {
/*
* We don't know both the bandwidth
* and the guard interval, so we can
* only report the MCS index.
*/
htrate = 0.0;
}
} else {
/*
* The MCS value is out of range.
*/
htrate = 0.0;
}
if (htrate != 0.0) {
/*
* We have the rate.
* Print it.
*/
ND_PRINT((ndo, "%.1f Mb/s MCS %u ", htrate, mcs_index));
} else {
/*
* We at least have the MCS index.
* Print it.
*/
ND_PRINT((ndo, "MCS %u ", mcs_index));
}
}
if (known & IEEE80211_RADIOTAP_MCS_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
ht_bandwidth[flags & IEEE80211_RADIOTAP_MCS_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_MCS_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_MCS_SHORT_GI) ?
"short" : "long"));
}
if (known & IEEE80211_RADIOTAP_MCS_HT_FORMAT_KNOWN) {
ND_PRINT((ndo, "%s ",
(flags & IEEE80211_RADIOTAP_MCS_HT_GREENFIELD) ?
"greenfield" : "mixed"));
}
if (known & IEEE80211_RADIOTAP_MCS_FEC_TYPE_KNOWN) {
ND_PRINT((ndo, "%s FEC ",
(flags & IEEE80211_RADIOTAP_MCS_FEC_LDPC) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_MCS_STBC_KNOWN) {
ND_PRINT((ndo, "RX-STBC%u ",
(flags & IEEE80211_RADIOTAP_MCS_STBC_MASK) >> IEEE80211_RADIOTAP_MCS_STBC_SHIFT));
}
break;
}
case IEEE80211_RADIOTAP_AMPDU_STATUS: {
uint32_t reference_num;
uint16_t flags;
uint8_t delim_crc;
uint8_t reserved;
rc = cpack_uint32(s, &reference_num);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &delim_crc);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &reserved);
if (rc != 0)
goto trunc;
/* Do nothing for now */
break;
}
case IEEE80211_RADIOTAP_VHT: {
uint16_t known;
uint8_t flags;
uint8_t bandwidth;
uint8_t mcs_nss[4];
uint8_t coding;
uint8_t group_id;
uint16_t partial_aid;
static const char *vht_bandwidth[32] = {
"20 MHz",
"40 MHz",
"20 MHz (L)",
"20 MHz (U)",
"80 MHz",
"80 MHz (L)",
"80 MHz (U)",
"80 MHz (LL)",
"80 MHz (LU)",
"80 MHz (UL)",
"80 MHz (UU)",
"160 MHz",
"160 MHz (L)",
"160 MHz (U)",
"160 MHz (LL)",
"160 MHz (LU)",
"160 MHz (UL)",
"160 MHz (UU)",
"160 MHz (LLL)",
"160 MHz (LLU)",
"160 MHz (LUL)",
"160 MHz (UUU)",
"160 MHz (ULL)",
"160 MHz (ULU)",
"160 MHz (UUL)",
"160 MHz (UUU)",
"unknown (26)",
"unknown (27)",
"unknown (28)",
"unknown (29)",
"unknown (30)",
"unknown (31)"
};
rc = cpack_uint16(s, &known);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &flags);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &bandwidth);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
rc = cpack_uint8(s, &mcs_nss[i]);
if (rc != 0)
goto trunc;
}
rc = cpack_uint8(s, &coding);
if (rc != 0)
goto trunc;
rc = cpack_uint8(s, &group_id);
if (rc != 0)
goto trunc;
rc = cpack_uint16(s, &partial_aid);
if (rc != 0)
goto trunc;
for (i = 0; i < 4; i++) {
u_int nss, mcs;
nss = mcs_nss[i] & IEEE80211_RADIOTAP_VHT_NSS_MASK;
mcs = (mcs_nss[i] & IEEE80211_RADIOTAP_VHT_MCS_MASK) >> IEEE80211_RADIOTAP_VHT_MCS_SHIFT;
if (nss == 0)
continue;
ND_PRINT((ndo, "User %u MCS %u ", i, mcs));
ND_PRINT((ndo, "%s FEC ",
(coding & (IEEE80211_RADIOTAP_CODING_LDPC_USERn << i)) ?
"LDPC" : "BCC"));
}
if (known & IEEE80211_RADIOTAP_VHT_BANDWIDTH_KNOWN) {
ND_PRINT((ndo, "%s ",
vht_bandwidth[bandwidth & IEEE80211_RADIOTAP_VHT_BANDWIDTH_MASK]));
}
if (known & IEEE80211_RADIOTAP_VHT_GUARD_INTERVAL_KNOWN) {
ND_PRINT((ndo, "%s GI ",
(flags & IEEE80211_RADIOTAP_VHT_SHORT_GI) ?
"short" : "long"));
}
break;
}
default:
/* this bit indicates a field whose
* size we do not know, so we cannot
* proceed. Just print the bit number.
*/
ND_PRINT((ndo, "[bit %u] ", bit));
return -1;
}
return 0;
trunc:
ND_PRINT((ndo, "%s", tstr));
return rc;
}
static int
print_in_radiotap_namespace(netdissect_options *ndo,
struct cpack_state *s, uint8_t *flags,
uint32_t presentflags, int bit0)
{
#define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x)))
#define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x)))
#define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x)))
#define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x)))
#define BITNO_2(x) (((x) & 2) ? 1 : 0)
uint32_t present, next_present;
int bitno;
enum ieee80211_radiotap_type bit;
int rc;
for (present = presentflags; present; present = next_present) {
/*
* Clear the least significant bit that is set.
*/
next_present = present & (present - 1);
/*
* Get the bit number, within this presence word,
* of the remaining least significant bit that
* is set.
*/
bitno = BITNO_32(present ^ next_present);
/*
* Stop if this is one of the "same meaning
* in all presence flags" bits.
*/
if (bitno >= IEEE80211_RADIOTAP_NAMESPACE)
break;
/*
* Get the radiotap bit number of that bit.
*/
bit = (enum ieee80211_radiotap_type)(bit0 + bitno);
rc = print_radiotap_field(ndo, s, bit, flags, presentflags);
if (rc != 0)
return rc;
}
return 0;
}
u_int
ieee802_11_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
#define BIT(n) (1U << n)
#define IS_EXTENDED(__p) \
(EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0
struct cpack_state cpacker;
const struct ieee80211_radiotap_header *hdr;
uint32_t presentflags;
const uint32_t *presentp, *last_presentp;
int vendor_namespace;
uint8_t vendor_oui[3];
uint8_t vendor_subnamespace;
uint16_t skip_length;
int bit0;
u_int len;
uint8_t flags;
int pad;
u_int fcslen;
if (caplen < sizeof(*hdr)) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
hdr = (const struct ieee80211_radiotap_header *)p;
len = EXTRACT_LE_16BITS(&hdr->it_len);
if (len < sizeof(*hdr)) {
/*
* The length is the length of the entire header, so
* it must be as large as the fixed-length part of
* the header.
*/
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
/*
* If we don't have the entire radiotap header, just give up.
*/
if (caplen < len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
cpack_init(&cpacker, (const uint8_t *)hdr, len); /* align against header start */
cpack_advance(&cpacker, sizeof(*hdr)); /* includes the 1st bitmap */
for (last_presentp = &hdr->it_present;
(const u_char*)(last_presentp + 1) <= p + len &&
IS_EXTENDED(last_presentp);
last_presentp++)
cpack_advance(&cpacker, sizeof(hdr->it_present)); /* more bitmaps */
/* are there more bitmap extensions than bytes in header? */
if ((const u_char*)(last_presentp + 1) > p + len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
/*
* Start out at the beginning of the default radiotap namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
/* Assume no flags */
flags = 0;
/* Assume no Atheros padding between 802.11 header and body */
pad = 0;
/* Assume no FCS at end of frame */
fcslen = 0;
for (presentp = &hdr->it_present; presentp <= last_presentp;
presentp++) {
presentflags = EXTRACT_LE_32BITS(presentp);
/*
* If this is a vendor namespace, we don't handle it.
*/
if (vendor_namespace) {
/*
* Skip past the stuff we don't understand.
* If we add support for any vendor namespaces,
* it'd be added here; use vendor_oui and
* vendor_subnamespace to interpret the fields.
*/
if (cpack_advance(&cpacker, skip_length) != 0) {
/*
* Ran out of space in the packet.
*/
break;
}
/*
* We've skipped it all; nothing more to
* skip.
*/
skip_length = 0;
} else {
if (print_in_radiotap_namespace(ndo, &cpacker,
&flags, presentflags, bit0) != 0) {
/*
* Fatal error - can't process anything
* more in the radiotap header.
*/
break;
}
}
/*
* Handle the namespace switch bits; we've already handled
* the extension bit in all but the last word above.
*/
switch (presentflags &
(BIT(IEEE80211_RADIOTAP_NAMESPACE)|BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE))) {
case 0:
/*
* We're not changing namespaces.
* advance to the next 32 bits in the current
* namespace.
*/
bit0 += 32;
break;
case BIT(IEEE80211_RADIOTAP_NAMESPACE):
/*
* We're switching to the radiotap namespace.
* Reset the presence-bitmap index to 0, and
* reset the namespace to the default radiotap
* namespace.
*/
bit0 = 0;
vendor_namespace = 0;
memset(vendor_oui, 0, 3);
vendor_subnamespace = 0;
skip_length = 0;
break;
case BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE):
/*
* We're switching to a vendor namespace.
* Reset the presence-bitmap index to 0,
* note that we're in a vendor namespace,
* and fetch the fields of the Vendor Namespace
* item.
*/
bit0 = 0;
vendor_namespace = 1;
if ((cpack_align_and_reserve(&cpacker, 2)) == NULL) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[0]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[1]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_oui[2]) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint8(&cpacker, &vendor_subnamespace) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
if (cpack_uint16(&cpacker, &skip_length) != 0) {
ND_PRINT((ndo, "%s", tstr));
break;
}
break;
default:
/*
* Illegal combination. The behavior in this
* case is undefined by the radiotap spec; we
* just ignore both bits.
*/
break;
}
}
if (flags & IEEE80211_RADIOTAP_F_DATAPAD)
pad = 1; /* Atheros padding */
if (flags & IEEE80211_RADIOTAP_F_FCS)
fcslen = 4; /* FCS at end of packet */
return len + ieee802_11_print(ndo, p + len, length - len, caplen - len, pad,
fcslen);
#undef BITNO_32
#undef BITNO_16
#undef BITNO_8
#undef BITNO_4
#undef BITNO_2
#undef BIT
}
static u_int
ieee802_11_avs_radio_print(netdissect_options *ndo,
const u_char *p, u_int length, u_int caplen)
{
uint32_t caphdr_len;
if (caplen < 8) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
caphdr_len = EXTRACT_32BITS(p + 4);
if (caphdr_len < 8) {
/*
* Yow! The capture header length is claimed not
* to be large enough to include even the version
* cookie or capture header length!
*/
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
if (caplen < caphdr_len) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return caphdr_len + ieee802_11_print(ndo, p + caphdr_len,
length - caphdr_len, caplen - caphdr_len, 0, 0);
}
#define PRISM_HDR_LEN 144
#define WLANCAP_MAGIC_COOKIE_BASE 0x80211000
#define WLANCAP_MAGIC_COOKIE_V1 0x80211001
#define WLANCAP_MAGIC_COOKIE_V2 0x80211002
/*
* For DLT_PRISM_HEADER; like DLT_IEEE802_11, but with an extra header,
* containing information such as radio information, which we
* currently ignore.
*
* If, however, the packet begins with WLANCAP_MAGIC_COOKIE_V1 or
* WLANCAP_MAGIC_COOKIE_V2, it's really DLT_IEEE802_11_RADIO_AVS
* (currently, on Linux, there's no ARPHRD_ type for
* DLT_IEEE802_11_RADIO_AVS, as there is a ARPHRD_IEEE80211_PRISM
* for DLT_PRISM_HEADER, so ARPHRD_IEEE80211_PRISM is used for
* the AVS header, and the first 4 bytes of the header are used to
* indicate whether it's a Prism header or an AVS header).
*/
u_int
prism_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int length = h->len;
uint32_t msgcode;
if (caplen < 4) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
msgcode = EXTRACT_32BITS(p);
if (msgcode == WLANCAP_MAGIC_COOKIE_V1 ||
msgcode == WLANCAP_MAGIC_COOKIE_V2)
return ieee802_11_avs_radio_print(ndo, p, length, caplen);
if (caplen < PRISM_HDR_LEN) {
ND_PRINT((ndo, "%s", tstr));
return caplen;
}
return PRISM_HDR_LEN + ieee802_11_print(ndo, p + PRISM_HDR_LEN,
length - PRISM_HDR_LEN, caplen - PRISM_HDR_LEN, 0, 0);
}
/*
* For DLT_IEEE802_11_RADIO; like DLT_IEEE802_11, but with an extra
* header, containing information such as radio information.
*/
u_int
ieee802_11_radio_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_radio_print(ndo, p, h->len, h->caplen);
}
/*
* For DLT_IEEE802_11_RADIO_AVS; like DLT_IEEE802_11, but with an
* extra header, containing information such as radio information,
* which we currently ignore.
*/
u_int
ieee802_11_radio_avs_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
return ieee802_11_avs_radio_print(ndo, p, h->len, h->caplen);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_328_0 |
crossvul-cpp_data_bad_17_0 | /*
* Copyright (C) 2015 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
* Copyright (C) 2013 Sourcefire, Inc.
*
* Authors: Steven Morgan <smorgan@sourcefire.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* 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., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#if HAVE_CONFIG_H
#include "clamav-config.h"
#endif
#include <errno.h>
#include "xar.h"
#include "fmap.h"
#if HAVE_LIBXML2
#ifdef _WIN32
#ifndef LIBXML_WRITER_ENABLED
#define LIBXML_WRITER_ENABLED 1
#endif
#endif
#include <libxml/xmlreader.h>
#include "clamav.h"
#include "str.h"
#include "scanners.h"
#include "inflate64.h"
#include "lzma_iface.h"
/*
xar_cleanup_temp_file - cleanup after cli_gentempfd
parameters:
ctx - cli_ctx context pointer
fd - fd to close
tmpname - name of file to unlink, address of storage to free
returns - CL_SUCCESS or CL_EUNLINK
*/
static int xar_cleanup_temp_file(cli_ctx *ctx, int fd, char * tmpname)
{
int rc = CL_SUCCESS;
if (fd > -1)
close(fd);
if (tmpname != NULL) {
if (!ctx->engine->keeptmp) {
if (cli_unlink(tmpname)) {
cli_dbgmsg("cli_scanxar: error unlinking tmpfile %s\n", tmpname);
rc = CL_EUNLINK;
}
}
free(tmpname);
}
return rc;
}
/*
xar_get_numeric_from_xml_element - extract xml element value as numeric
parameters:
reader - xmlTextReaderPtr
value - pointer to long to contain the returned value
returns - CL_SUCCESS or CL_EFORMAT
*/
static int xar_get_numeric_from_xml_element(xmlTextReaderPtr reader, long * value)
{
const xmlChar * numstr;
if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {
numstr = xmlTextReaderConstValue(reader);
if (numstr) {
*value = atol((const char *)numstr);
if (*value < 0) {
cli_dbgmsg("cli_scanxar: XML element value %li\n", *value);
return CL_EFORMAT;
}
return CL_SUCCESS;
}
}
cli_dbgmsg("cli_scanxar: No text for XML element\n");
return CL_EFORMAT;
}
/*
xar_get_checksum_values - extract checksum and hash algorithm from xml element
parameters:
reader - xmlTextReaderPtr
cksum - pointer to char* for returning checksum value.
hash - pointer to int for returning checksum algorithm.
returns - void
*/
static void xar_get_checksum_values(xmlTextReaderPtr reader, unsigned char ** cksum, int * hash)
{
xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)"style");
const xmlChar * xmlval;
*hash = XAR_CKSUM_NONE;
if (style == NULL) {
cli_dbgmsg("cli_scaxar: xmlTextReaderGetAttribute no style attribute "
"for checksum element\n");
} else {
cli_dbgmsg("cli_scanxar: checksum algorithm is %s.\n", style);
if (0 == xmlStrcasecmp(style, (const xmlChar *)"sha1")) {
*hash = XAR_CKSUM_SHA1;
} else if (0 == xmlStrcasecmp(style, (const xmlChar *)"md5")) {
*hash = XAR_CKSUM_MD5;
} else {
cli_dbgmsg("cli_scanxar: checksum algorithm %s is unsupported.\n", style);
*hash = XAR_CKSUM_OTHER;
}
}
if (style != NULL)
xmlFree(style);
if (xmlTextReaderRead(reader) == 1 && xmlTextReaderNodeType(reader) == XML_READER_TYPE_TEXT) {
xmlval = xmlTextReaderConstValue(reader);
if (xmlval) {
*cksum = xmlStrdup(xmlval);
cli_dbgmsg("cli_scanxar: checksum value is %s.\n", *cksum);
} else {
*cksum = NULL;
cli_dbgmsg("cli_scanxar: xmlTextReaderConstValue() returns NULL for checksum value.\n");
}
}
else
cli_dbgmsg("cli_scanxar: No text for XML checksum element.\n");
}
/*
xar_get_toc_data_values - return the values of a <data> or <ea> xml element that represent
an extent of data on the heap.
parameters:
reader - xmlTextReaderPtr
length - pointer to long for returning value of the <length> element.
offset - pointer to long for returning value of the <offset> element.
size - pointer to long for returning value of the <size> element.
encoding - pointer to int for returning indication of the <encoding> style attribute.
a_cksum - pointer to char* for return archived checksum value.
a_hash - pointer to int for returning archived checksum algorithm.
e_cksum - pointer to char* for return extracted checksum value.
e_hash - pointer to int for returning extracted checksum algorithm.
returns - CL_FORMAT, CL_SUCCESS, CL_BREAK. CL_BREAK indicates no more <data>/<ea> element.
*/
static int xar_get_toc_data_values(xmlTextReaderPtr reader, long *length, long *offset, long *size, int *encoding,
unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)
{
const xmlChar *name;
int indata = 0, inea = 0;
int rc, gotoffset=0, gotlength=0, gotsize=0;
*a_cksum = NULL;
*a_hash = XAR_CKSUM_NONE;
*e_cksum = NULL;
*e_hash = XAR_CKSUM_NONE;
*encoding = CL_TYPE_ANY;
rc = xmlTextReaderRead(reader);
while (rc == 1) {
name = xmlTextReaderConstLocalName(reader);
if (indata || inea) {
/* cli_dbgmsg("cli_scanxar: xmlTextReaderRead read %s\n", name); */
if (xmlStrEqual(name, (const xmlChar *)"offset") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))
gotoffset=1;
} else if (xmlStrEqual(name, (const xmlChar *)"length") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))
gotlength=1;
} else if (xmlStrEqual(name, (const xmlChar *)"size") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))
gotsize=1;
} else if (xmlStrEqual(name, (const xmlChar *)"archived-checksum") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <archived-checksum>:\n");
xar_get_checksum_values(reader, a_cksum, a_hash);
} else if ((xmlStrEqual(name, (const xmlChar *)"extracted-checksum") ||
xmlStrEqual(name, (const xmlChar *)"unarchived-checksum")) &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
cli_dbgmsg("cli_scanxar: <extracted-checksum>:\n");
xar_get_checksum_values(reader, e_cksum, e_hash);
} else if (xmlStrEqual(name, (const xmlChar *)"encoding") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)"style");
if (style == NULL) {
cli_dbgmsg("cli_scaxar: xmlTextReaderGetAttribute no style attribute "
"for encoding element\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-gzip")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-gzip.\n");
*encoding = CL_TYPE_GZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/octet-stream")) {
cli_dbgmsg("cli_scanxar: encoding = application/octet-stream.\n");
*encoding = CL_TYPE_ANY;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-bzip2")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-bzip2.\n");
*encoding = CL_TYPE_BZ;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-lzma")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-lzma.\n");
*encoding = CL_TYPE_7Z;
} else if (xmlStrEqual(style, (const xmlChar *)"application/x-xz")) {
cli_dbgmsg("cli_scanxar: encoding = application/x-xz.\n");
*encoding = CL_TYPE_XZ;
} else {
cli_dbgmsg("cli_scaxar: unknown style value=%s for encoding element\n", style);
*encoding = CL_TYPE_ANY;
}
if (style != NULL)
xmlFree(style);
} else if (indata && xmlStrEqual(name, (const xmlChar *)"data") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
} else if (inea && xmlStrEqual(name, (const xmlChar *)"ea") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
break;
}
} else {
if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
if (xmlStrEqual(name, (const xmlChar *)"data")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <data>\n");
indata = 1;
} else if (xmlStrEqual(name, (const xmlChar *)"ea")) {
cli_dbgmsg("cli_scanxar: xmlTextReaderRead read <ea>\n");
inea = 1;
}
} else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&
xmlStrEqual(name, (const xmlChar *)"xar")) {
cli_dbgmsg("cli_scanxar: finished parsing xar TOC.\n");
break;
}
}
rc = xmlTextReaderRead(reader);
}
if (gotoffset && gotlength && gotsize) {
rc = CL_SUCCESS;
}
else if (0 == gotoffset + gotlength + gotsize)
rc = CL_BREAK;
else
rc = CL_EFORMAT;
return rc;
}
/*
xar_process_subdocument - check TOC for xml subdocument. If found, extract and
scan in memory.
Parameters:
reader - xmlTextReaderPtr
ctx - pointer to cli_ctx
Returns:
CL_SUCCESS - subdoc found and clean scan (or virus found and SCAN_ALL), or no subdocument
other - error return code from cli_mem_scandesc()
*/
static int xar_scan_subdocuments(xmlTextReaderPtr reader, cli_ctx *ctx)
{
int rc = CL_SUCCESS, subdoc_len, fd;
xmlChar * subdoc;
const xmlChar *name;
char * tmpname;
while (xmlTextReaderRead(reader) == 1) {
name = xmlTextReaderConstLocalName(reader);
if (name == NULL) {
cli_dbgmsg("cli_scanxar: xmlTextReaderConstLocalName() no name.\n");
rc = CL_EFORMAT;
break;
}
if (xmlStrEqual(name, (const xmlChar *)"toc") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT)
return CL_SUCCESS;
if (xmlStrEqual(name, (const xmlChar *)"subdoc") &&
xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
subdoc = xmlTextReaderReadInnerXml(reader);
if (subdoc == NULL) {
cli_dbgmsg("cli_scanxar: no content in subdoc element.\n");
xmlTextReaderNext(reader);
continue;
}
subdoc_len = xmlStrlen(subdoc);
cli_dbgmsg("cli_scanxar: in-memory scan of xml subdocument, len %i.\n", subdoc_len);
rc = cli_mem_scandesc(subdoc, subdoc_len, ctx);
if (rc == CL_VIRUS && SCAN_ALL)
rc = CL_SUCCESS;
/* make a file to leave if --leave-temps in effect */
if(ctx->engine->keeptmp) {
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't create temporary file for subdocument.\n");
} else {
cli_dbgmsg("cli_scanxar: Writing subdoc to temp file %s.\n", tmpname);
if (cli_writen(fd, subdoc, subdoc_len) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing subdoc temporary file.\n");
rc = CL_EWRITE;
}
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
}
}
xmlFree(subdoc);
if (rc != CL_SUCCESS)
return rc;
xmlTextReaderNext(reader);
}
}
return rc;
}
static void * xar_hash_init(int hash, void **sc, void **mc)
{
if (!sc && !mc)
return NULL;
switch (hash) {
case XAR_CKSUM_SHA1:
*sc = cl_hash_init("sha1");
if (!(*sc)) {
return NULL;
}
return *sc;
case XAR_CKSUM_MD5:
*mc = cl_hash_init("md5");
if (!(*mc)) {
return NULL;
}
return *mc;
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
default:
return NULL;
}
}
static void xar_hash_update(void * hash_ctx, void * data, unsigned long size, int hash)
{
if (!hash_ctx || !data || !size)
return;
switch (hash) {
case XAR_CKSUM_NONE:
case XAR_CKSUM_OTHER:
return;
}
cl_update_hash(hash_ctx, data, size);
}
static void xar_hash_final(void * hash_ctx, void * result, int hash)
{
if (!hash_ctx || !result)
return;
switch (hash) {
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
return;
}
cl_finish_hash(hash_ctx, result);
}
static int xar_hash_check(int hash, const void * result, const void * expected)
{
int len;
if (!result || !expected)
return 1;
switch (hash) {
case XAR_CKSUM_SHA1:
len = SHA1_HASH_SIZE;
break;
case XAR_CKSUM_MD5:
len = CLI_HASH_MD5;
break;
case XAR_CKSUM_OTHER:
case XAR_CKSUM_NONE:
default:
return 1;
}
return memcmp(result, expected, len);
}
#endif
/*
cli_scanxar - scan an xar archive.
Parameters:
ctx - pointer to cli_ctx.
returns - CL_SUCCESS or CL_ error code.
*/
int cli_scanxar(cli_ctx *ctx)
{
int rc = CL_SUCCESS;
unsigned int cksum_fails = 0;
unsigned int extract_errors = 0;
#if HAVE_LIBXML2
int fd = -1;
struct xar_header hdr;
fmap_t *map = *ctx->fmap;
long length, offset, size, at;
int encoding;
z_stream strm;
char *toc, *tmpname;
xmlTextReaderPtr reader = NULL;
int a_hash, e_hash;
unsigned char *a_cksum = NULL, *e_cksum = NULL;
void *a_hash_ctx = NULL, *e_hash_ctx = NULL;
char result[SHA1_HASH_SIZE];
memset(&strm, 0x00, sizeof(z_stream));
/* retrieve xar header */
if (fmap_readn(*ctx->fmap, &hdr, 0, sizeof(hdr)) != sizeof(hdr)) {
cli_dbgmsg("cli_scanxar: Invalid header, too short.\n");
return CL_EFORMAT;
}
hdr.magic = be32_to_host(hdr.magic);
if (hdr.magic == XAR_HEADER_MAGIC) {
cli_dbgmsg("cli_scanxar: Matched magic\n");
}
else {
cli_dbgmsg("cli_scanxar: Invalid magic\n");
return CL_EFORMAT;
}
hdr.size = be16_to_host(hdr.size);
hdr.version = be16_to_host(hdr.version);
hdr.toc_length_compressed = be64_to_host(hdr.toc_length_compressed);
hdr.toc_length_decompressed = be64_to_host(hdr.toc_length_decompressed);
hdr.chksum_alg = be32_to_host(hdr.chksum_alg);
/* cli_dbgmsg("hdr.magic %x\n", hdr.magic); */
/* cli_dbgmsg("hdr.size %i\n", hdr.size); */
/* cli_dbgmsg("hdr.version %i\n", hdr.version); */
/* cli_dbgmsg("hdr.toc_length_compressed %lu\n", hdr.toc_length_compressed); */
/* cli_dbgmsg("hdr.toc_length_decompressed %lu\n", hdr.toc_length_decompressed); */
/* cli_dbgmsg("hdr.chksum_alg %i\n", hdr.chksum_alg); */
/* Uncompress TOC */
strm.next_in = (unsigned char *)fmap_need_off_once(*ctx->fmap, hdr.size, hdr.toc_length_compressed);
if (strm.next_in == NULL) {
cli_dbgmsg("cli_scanxar: fmap_need_off_once fails on TOC.\n");
return CL_EREAD;
}
strm.avail_in = hdr.toc_length_compressed;
toc = cli_malloc(hdr.toc_length_decompressed+1);
if (toc == NULL) {
cli_dbgmsg("cli_scanxar: cli_malloc fails on TOC decompress buffer.\n");
return CL_EMEM;
}
toc[hdr.toc_length_decompressed] = '\0';
strm.avail_out = hdr.toc_length_decompressed;
strm.next_out = (unsigned char *)toc;
rc = inflateInit(&strm);
if (rc != Z_OK) {
cli_dbgmsg("cli_scanxar:inflateInit error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
rc = inflate(&strm, Z_SYNC_FLUSH);
if (rc != Z_OK && rc != Z_STREAM_END) {
cli_dbgmsg("cli_scanxar:inflate error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
rc = inflateEnd(&strm);
if (rc != Z_OK) {
cli_dbgmsg("cli_scanxar:inflateEnd error %i \n", rc);
rc = CL_EFORMAT;
goto exit_toc;
}
/* cli_dbgmsg("cli_scanxar: TOC xml:\n%s\n", toc); */
/* printf("cli_scanxar: TOC xml:\n%s\n", toc); */
/* cli_dbgmsg("cli_scanxar: TOC end:\n"); */
/* printf("cli_scanxar: TOC end:\n"); */
/* scan the xml */
cli_dbgmsg("cli_scanxar: scanning xar TOC xml in memory.\n");
rc = cli_mem_scandesc(toc, hdr.toc_length_decompressed, ctx);
if (rc != CL_SUCCESS) {
if (rc != CL_VIRUS || !SCAN_ALL)
goto exit_toc;
}
/* make a file to leave if --leave-temps in effect */
if(ctx->engine->keeptmp) {
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't create temporary file for TOC.\n");
goto exit_toc;
}
if (cli_writen(fd, toc, hdr.toc_length_decompressed) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing TOC.\n");
rc = CL_EWRITE;
xar_cleanup_temp_file(ctx, fd, tmpname);
goto exit_toc;
}
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
if (rc != CL_SUCCESS)
goto exit_toc;
}
reader = xmlReaderForMemory(toc, hdr.toc_length_decompressed, "noname.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS);
if (reader == NULL) {
cli_dbgmsg("cli_scanxar: xmlReaderForMemory error for TOC\n");
goto exit_toc;
}
rc = xar_scan_subdocuments(reader, ctx);
if (rc != CL_SUCCESS) {
cli_dbgmsg("xar_scan_subdocuments returns %i.\n", rc);
goto exit_reader;
}
/* Walk the TOC XML and extract files */
fd = -1;
tmpname = NULL;
while (CL_SUCCESS == (rc = xar_get_toc_data_values(reader, &length, &offset, &size, &encoding,
&a_cksum, &a_hash, &e_cksum, &e_hash))) {
int do_extract_cksum = 1;
unsigned char * blockp;
void *a_sc, *e_sc;
void *a_mc, *e_mc;
char * expected;
/* clean up temp file from previous loop iteration */
if (fd > -1 && tmpname) {
rc = xar_cleanup_temp_file(ctx, fd, tmpname);
if (rc != CL_SUCCESS)
goto exit_reader;
}
at = offset + hdr.toc_length_compressed + hdr.size;
if ((rc = cli_gentempfd(ctx->engine->tmpdir, &tmpname, &fd)) != CL_SUCCESS) {
cli_dbgmsg("cli_scanxar: Can't generate temporary file.\n");
goto exit_reader;
}
cli_dbgmsg("cli_scanxar: decompress into temp file:\n%s, size %li,\n"
"from xar heap offset %li length %li\n",
tmpname, size, offset, length);
a_hash_ctx = xar_hash_init(a_hash, &a_sc, &a_mc);
e_hash_ctx = xar_hash_init(e_hash, &e_sc, &e_mc);
switch (encoding) {
case CL_TYPE_GZ:
/* inflate gzip directly because file segments do not contain magic */
memset(&strm, 0, sizeof(strm));
if ((rc = inflateInit(&strm)) != Z_OK) {
cli_dbgmsg("cli_scanxar: InflateInit failed: %d\n", rc);
rc = CL_EFORMAT;
extract_errors++;
break;
}
while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {
unsigned long avail_in;
void * next_in;
unsigned int bytes = MIN(map->len - at, map->pgsz);
bytes = MIN(length, bytes);
if(!(strm.next_in = next_in = (void*)fmap_need_off_once(map, at, bytes))) {
cli_dbgmsg("cli_scanxar: Can't read %u bytes @ %lu.\n", bytes, (long unsigned)at);
inflateEnd(&strm);
rc = CL_EREAD;
goto exit_tmpfile;
}
at += bytes;
strm.avail_in = avail_in = bytes;
do {
int inf, outsize = 0;
unsigned char buff[FILEBUFF];
strm.avail_out = sizeof(buff);
strm.next_out = buff;
inf = inflate(&strm, Z_SYNC_FLUSH);
if (inf != Z_OK && inf != Z_STREAM_END && inf != Z_BUF_ERROR) {
cli_dbgmsg("cli_scanxar: inflate error %i %s.\n", inf, strm.msg?strm.msg:"");
rc = CL_EFORMAT;
extract_errors++;
break;
}
bytes = sizeof(buff) - strm.avail_out;
if (e_hash_ctx != NULL)
xar_hash_update(e_hash_ctx, buff, bytes, e_hash);
if (cli_writen(fd, buff, bytes) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error file %s.\n", tmpname);
inflateEnd(&strm);
rc = CL_EWRITE;
goto exit_tmpfile;
}
outsize += sizeof(buff) - strm.avail_out;
if (cli_checklimits("cli_scanxar", ctx, outsize, 0, 0) != CL_CLEAN) {
break;
}
if (inf == Z_STREAM_END) {
break;
}
} while (strm.avail_out == 0);
if (rc != CL_SUCCESS)
break;
avail_in -= strm.avail_in;
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, next_in, avail_in, a_hash);
}
inflateEnd(&strm);
break;
case CL_TYPE_7Z:
#define CLI_LZMA_OBUF_SIZE 1024*1024
#define CLI_LZMA_HDR_SIZE LZMA_PROPS_SIZE+8
#define CLI_LZMA_IBUF_SIZE CLI_LZMA_OBUF_SIZE>>2 /* estimated compression ratio 25% */
{
struct CLI_LZMA lz;
unsigned long in_remaining = length;
unsigned long out_size = 0;
unsigned char * buff = __lzma_wrap_alloc(NULL, CLI_LZMA_OBUF_SIZE);
int lret;
memset(&lz, 0, sizeof(lz));
if (buff == NULL) {
cli_dbgmsg("cli_scanxar: memory request for lzma decompression buffer fails.\n");
rc = CL_EMEM;
goto exit_tmpfile;
}
blockp = (void*)fmap_need_off_once(map, at, CLI_LZMA_HDR_SIZE);
if (blockp == NULL) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %li bytes @ %li, errno:%s.\n",
length, at, errbuff);
rc = CL_EREAD;
__lzma_wrap_free(NULL, buff);
goto exit_tmpfile;
}
lz.next_in = blockp;
lz.avail_in = CLI_LZMA_HDR_SIZE;
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, blockp, CLI_LZMA_HDR_SIZE, a_hash);
lret = cli_LzmaInit(&lz, 0);
if (lret != LZMA_RESULT_OK) {
cli_dbgmsg("cli_scanxar: cli_LzmaInit() fails: %i.\n", lret);
rc = CL_EFORMAT;
__lzma_wrap_free(NULL, buff);
extract_errors++;
break;
}
at += CLI_LZMA_HDR_SIZE;
in_remaining -= CLI_LZMA_HDR_SIZE;
while ((size_t)at < map->len && (unsigned long)at < offset+hdr.toc_length_compressed+hdr.size+length) {
SizeT avail_in;
SizeT avail_out;
void * next_in;
unsigned long in_consumed;
lz.next_out = buff;
lz.avail_out = CLI_LZMA_OBUF_SIZE;
lz.avail_in = avail_in = MIN(CLI_LZMA_IBUF_SIZE, in_remaining);
lz.next_in = next_in = (void*)fmap_need_off_once(map, at, lz.avail_in);
if (lz.next_in == NULL) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %li bytes @ %li, errno: %s.\n",
length, at, errbuff);
rc = CL_EREAD;
__lzma_wrap_free(NULL, buff);
cli_LzmaShutdown(&lz);
goto exit_tmpfile;
}
lret = cli_LzmaDecode(&lz);
if (lret != LZMA_RESULT_OK && lret != LZMA_STREAM_END) {
cli_dbgmsg("cli_scanxar: cli_LzmaDecode() fails: %i.\n", lret);
rc = CL_EFORMAT;
extract_errors++;
break;
}
in_consumed = avail_in - lz.avail_in;
in_remaining -= in_consumed;
at += in_consumed;
avail_out = CLI_LZMA_OBUF_SIZE - lz.avail_out;
if (avail_out == 0)
cli_dbgmsg("cli_scanxar: cli_LzmaDecode() produces no output for "
"avail_in %llu, avail_out %llu.\n",
(long long unsigned)avail_in, (long long unsigned)avail_out);
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, next_in, in_consumed, a_hash);
if (e_hash_ctx != NULL)
xar_hash_update(e_hash_ctx, buff, avail_out, e_hash);
/* Write a decompressed block. */
/* cli_dbgmsg("Writing %li bytes to LZMA decompress temp file, " */
/* "consumed %li of %li available compressed bytes.\n", */
/* avail_out, in_consumed, avail_in); */
if (cli_writen(fd, buff, avail_out) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error writing lzma temp file for %llu bytes.\n",
(long long unsigned)avail_out);
__lzma_wrap_free(NULL, buff);
cli_LzmaShutdown(&lz);
rc = CL_EWRITE;
goto exit_tmpfile;
}
/* Check file size limitation. */
out_size += avail_out;
if (cli_checklimits("cli_scanxar", ctx, out_size, 0, 0) != CL_CLEAN) {
break;
}
if (lret == LZMA_STREAM_END)
break;
}
cli_LzmaShutdown(&lz);
__lzma_wrap_free(NULL, buff);
}
break;
case CL_TYPE_ANY:
default:
case CL_TYPE_BZ:
case CL_TYPE_XZ:
/* for uncompressed, bzip2, xz, and unknown, just pull the file, cli_magic_scandesc does the rest */
do_extract_cksum = 0;
{
unsigned long write_len;
if (ctx->engine->maxfilesize)
write_len = MIN((size_t)(ctx->engine->maxfilesize), (size_t)length);
else
write_len = length;
if (!(blockp = (void*)fmap_need_off_once(map, at, length))) {
char errbuff[128];
cli_strerror(errno, errbuff, sizeof(errbuff));
cli_dbgmsg("cli_scanxar: Can't read %li bytes @ %li, errno:%s.\n",
length, at, errbuff);
rc = CL_EREAD;
goto exit_tmpfile;
}
if (a_hash_ctx != NULL)
xar_hash_update(a_hash_ctx, blockp, length, a_hash);
if (cli_writen(fd, blockp, write_len) < 0) {
cli_dbgmsg("cli_scanxar: cli_writen error %li bytes @ %li.\n", length, at);
rc = CL_EWRITE;
goto exit_tmpfile;
}
/*break;*/
}
}
if (rc == CL_SUCCESS) {
if (a_hash_ctx != NULL) {
xar_hash_final(a_hash_ctx, result, a_hash);
a_hash_ctx = NULL;
} else {
cli_dbgmsg("cli_scanxar: archived-checksum missing.\n");
cksum_fails++;
}
if (a_cksum != NULL) {
expected = cli_hex2str((char *)a_cksum);
if (xar_hash_check(a_hash, result, expected) != 0) {
cli_dbgmsg("cli_scanxar: archived-checksum mismatch.\n");
cksum_fails++;
} else {
cli_dbgmsg("cli_scanxar: archived-checksum matched.\n");
}
free(expected);
}
if (e_hash_ctx != NULL) {
xar_hash_final(e_hash_ctx, result, e_hash);
e_hash_ctx = NULL;
} else {
cli_dbgmsg("cli_scanxar: extracted-checksum(unarchived-checksum) missing.\n");
cksum_fails++;
}
if (e_cksum != NULL) {
if (do_extract_cksum) {
expected = cli_hex2str((char *)e_cksum);
if (xar_hash_check(e_hash, result, expected) != 0) {
cli_dbgmsg("cli_scanxar: extracted-checksum mismatch.\n");
cksum_fails++;
} else {
cli_dbgmsg("cli_scanxar: extracted-checksum matched.\n");
}
free(expected);
}
}
rc = cli_magic_scandesc(fd, ctx);
if (rc != CL_SUCCESS) {
if (rc == CL_VIRUS) {
cli_dbgmsg("cli_scanxar: Infected with %s\n", cli_get_last_virus(ctx));
if (!SCAN_ALL)
goto exit_tmpfile;
} else if (rc != CL_BREAK) {
cli_dbgmsg("cli_scanxar: cli_magic_scandesc error %i\n", rc);
goto exit_tmpfile;
}
}
}
if (a_cksum != NULL) {
xmlFree(a_cksum);
a_cksum = NULL;
}
if (e_cksum != NULL) {
xmlFree(e_cksum);
e_cksum = NULL;
}
}
exit_tmpfile:
xar_cleanup_temp_file(ctx, fd, tmpname);
if (a_hash_ctx != NULL)
xar_hash_final(a_hash_ctx, result, a_hash);
if (e_hash_ctx != NULL)
xar_hash_final(e_hash_ctx, result, e_hash);
exit_reader:
if (a_cksum != NULL)
xmlFree(a_cksum);
if (e_cksum != NULL)
xmlFree(e_cksum);
xmlTextReaderClose(reader);
xmlFreeTextReader(reader);
exit_toc:
free(toc);
if (rc == CL_BREAK)
rc = CL_SUCCESS;
#else
cli_dbgmsg("cli_scanxar: can't scan xar files, need libxml2.\n");
#endif
if (cksum_fails + extract_errors != 0) {
cli_warnmsg("cli_scanxar: %u checksum errors and %u extraction errors, use --debug for more info.\n",
cksum_fails, extract_errors);
}
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_17_0 |
crossvul-cpp_data_bad_2910_0 | /*
* (Tentative) USB Audio Driver for ALSA
*
* Copyright (c) 2002 by Takashi Iwai <tiwai@suse.de>
*
* Many codes borrowed from audio.c by
* Alan Cox (alan@lxorguk.ukuu.org.uk)
* Thomas Sailer (sailer@ife.ee.ethz.ch)
*
*
* 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
*
*
* NOTES:
*
* - the linked URBs would be preferred but not used so far because of
* the instability of unlinking.
* - type II is not supported properly. there is no device which supports
* this type *correctly*. SB extigy looks as if it supports, but it's
* indeed an AC3 stream packed in SPDIF frames (i.e. no real AC3 stream).
*/
#include <linux/bitops.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/usb.h>
#include <linux/moduleparam.h>
#include <linux/mutex.h>
#include <linux/usb/audio.h>
#include <linux/usb/audio-v2.h>
#include <linux/module.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/initval.h>
#include "usbaudio.h"
#include "card.h"
#include "midi.h"
#include "mixer.h"
#include "proc.h"
#include "quirks.h"
#include "endpoint.h"
#include "helper.h"
#include "debug.h"
#include "pcm.h"
#include "format.h"
#include "power.h"
#include "stream.h"
MODULE_AUTHOR("Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("USB Audio");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Generic,USB Audio}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;/* Enable this card */
/* Vendor/product IDs for this card */
static int vid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
static int pid[SNDRV_CARDS] = { [0 ... (SNDRV_CARDS-1)] = -1 };
static int device_setup[SNDRV_CARDS]; /* device parameter for this card */
static bool ignore_ctl_error;
static bool autoclock = true;
static char *quirk_alias[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the USB audio adapter.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the USB audio adapter.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable USB audio adapter.");
module_param_array(vid, int, NULL, 0444);
MODULE_PARM_DESC(vid, "Vendor ID for the USB audio device.");
module_param_array(pid, int, NULL, 0444);
MODULE_PARM_DESC(pid, "Product ID for the USB audio device.");
module_param_array(device_setup, int, NULL, 0444);
MODULE_PARM_DESC(device_setup, "Specific device setup (if needed).");
module_param(ignore_ctl_error, bool, 0444);
MODULE_PARM_DESC(ignore_ctl_error,
"Ignore errors from USB controller for mixer interfaces.");
module_param(autoclock, bool, 0444);
MODULE_PARM_DESC(autoclock, "Enable auto-clock selection for UAC2 devices (default: yes).");
module_param_array(quirk_alias, charp, NULL, 0444);
MODULE_PARM_DESC(quirk_alias, "Quirk aliases, e.g. 0123abcd:5678beef.");
/*
* we keep the snd_usb_audio_t instances by ourselves for merging
* the all interfaces on the same card as one sound device.
*/
static DEFINE_MUTEX(register_mutex);
static struct snd_usb_audio *usb_chip[SNDRV_CARDS];
static struct usb_driver usb_audio_driver;
/*
* disconnect streams
* called from usb_audio_disconnect()
*/
static void snd_usb_stream_disconnect(struct snd_usb_stream *as)
{
int idx;
struct snd_usb_substream *subs;
for (idx = 0; idx < 2; idx++) {
subs = &as->substream[idx];
if (!subs->num_formats)
continue;
subs->interface = -1;
subs->data_endpoint = NULL;
subs->sync_endpoint = NULL;
}
}
static int snd_usb_create_stream(struct snd_usb_audio *chip, int ctrlif, int interface)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
struct usb_interface *iface = usb_ifnum_to_if(dev, interface);
if (!iface) {
dev_err(&dev->dev, "%u:%d : does not exist\n",
ctrlif, interface);
return -EINVAL;
}
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
/*
* Android with both accessory and audio interfaces enabled gets the
* interface numbers wrong.
*/
if ((chip->usb_id == USB_ID(0x18d1, 0x2d04) ||
chip->usb_id == USB_ID(0x18d1, 0x2d05)) &&
interface == 0 &&
altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC &&
altsd->bInterfaceSubClass == USB_SUBCLASS_VENDOR_SPEC) {
interface = 2;
iface = usb_ifnum_to_if(dev, interface);
if (!iface)
return -EINVAL;
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
}
if (usb_interface_claimed(iface)) {
dev_dbg(&dev->dev, "%d:%d: skipping, already claimed\n",
ctrlif, interface);
return -EINVAL;
}
if ((altsd->bInterfaceClass == USB_CLASS_AUDIO ||
altsd->bInterfaceClass == USB_CLASS_VENDOR_SPEC) &&
altsd->bInterfaceSubClass == USB_SUBCLASS_MIDISTREAMING) {
int err = __snd_usbmidi_create(chip->card, iface,
&chip->midi_list, NULL,
chip->usb_id);
if (err < 0) {
dev_err(&dev->dev,
"%u:%d: cannot create sequencer device\n",
ctrlif, interface);
return -EINVAL;
}
usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
return 0;
}
if ((altsd->bInterfaceClass != USB_CLASS_AUDIO &&
altsd->bInterfaceClass != USB_CLASS_VENDOR_SPEC) ||
altsd->bInterfaceSubClass != USB_SUBCLASS_AUDIOSTREAMING) {
dev_dbg(&dev->dev,
"%u:%d: skipping non-supported interface %d\n",
ctrlif, interface, altsd->bInterfaceClass);
/* skip non-supported classes */
return -EINVAL;
}
if (snd_usb_get_speed(dev) == USB_SPEED_LOW) {
dev_err(&dev->dev, "low speed audio streaming not supported\n");
return -EINVAL;
}
if (! snd_usb_parse_audio_interface(chip, interface)) {
usb_set_interface(dev, interface, 0); /* reset the current interface */
usb_driver_claim_interface(&usb_audio_driver, iface, (void *)-1L);
}
return 0;
}
/*
* parse audio control descriptor and create pcm/midi streams
*/
static int snd_usb_create_streams(struct snd_usb_audio *chip, int ctrlif)
{
struct usb_device *dev = chip->dev;
struct usb_host_interface *host_iface;
struct usb_interface_descriptor *altsd;
void *control_header;
int i, protocol;
/* find audiocontrol interface */
host_iface = &usb_ifnum_to_if(dev, ctrlif)->altsetting[0];
control_header = snd_usb_find_csint_desc(host_iface->extra,
host_iface->extralen,
NULL, UAC_HEADER);
altsd = get_iface_desc(host_iface);
protocol = altsd->bInterfaceProtocol;
if (!control_header) {
dev_err(&dev->dev, "cannot find UAC_HEADER\n");
return -EINVAL;
}
switch (protocol) {
default:
dev_warn(&dev->dev,
"unknown interface protocol %#02x, assuming v1\n",
protocol);
/* fall through */
case UAC_VERSION_1: {
struct uac1_ac_header_descriptor *h1 = control_header;
if (!h1->bInCollection) {
dev_info(&dev->dev, "skipping empty audio interface (v1)\n");
return -EINVAL;
}
if (h1->bLength < sizeof(*h1) + h1->bInCollection) {
dev_err(&dev->dev, "invalid UAC_HEADER (v1)\n");
return -EINVAL;
}
for (i = 0; i < h1->bInCollection; i++)
snd_usb_create_stream(chip, ctrlif, h1->baInterfaceNr[i]);
break;
}
case UAC_VERSION_2: {
struct usb_interface_assoc_descriptor *assoc =
usb_ifnum_to_if(dev, ctrlif)->intf_assoc;
if (!assoc) {
/*
* Firmware writers cannot count to three. So to find
* the IAD on the NuForce UDH-100, also check the next
* interface.
*/
struct usb_interface *iface =
usb_ifnum_to_if(dev, ctrlif + 1);
if (iface &&
iface->intf_assoc &&
iface->intf_assoc->bFunctionClass == USB_CLASS_AUDIO &&
iface->intf_assoc->bFunctionProtocol == UAC_VERSION_2)
assoc = iface->intf_assoc;
}
if (!assoc) {
dev_err(&dev->dev, "Audio class v2 interfaces need an interface association\n");
return -EINVAL;
}
for (i = 0; i < assoc->bInterfaceCount; i++) {
int intf = assoc->bFirstInterface + i;
if (intf != ctrlif)
snd_usb_create_stream(chip, ctrlif, intf);
}
break;
}
}
return 0;
}
/*
* free the chip instance
*
* here we have to do not much, since pcm and controls are already freed
*
*/
static int snd_usb_audio_free(struct snd_usb_audio *chip)
{
struct snd_usb_endpoint *ep, *n;
list_for_each_entry_safe(ep, n, &chip->ep_list, list)
snd_usb_endpoint_free(ep);
mutex_destroy(&chip->mutex);
if (!atomic_read(&chip->shutdown))
dev_set_drvdata(&chip->dev->dev, NULL);
kfree(chip);
return 0;
}
static int snd_usb_audio_dev_free(struct snd_device *device)
{
struct snd_usb_audio *chip = device->device_data;
return snd_usb_audio_free(chip);
}
/*
* create a chip instance and set its names.
*/
static int snd_usb_audio_create(struct usb_interface *intf,
struct usb_device *dev, int idx,
const struct snd_usb_audio_quirk *quirk,
unsigned int usb_id,
struct snd_usb_audio **rchip)
{
struct snd_card *card;
struct snd_usb_audio *chip;
int err, len;
char component[14];
static struct snd_device_ops ops = {
.dev_free = snd_usb_audio_dev_free,
};
*rchip = NULL;
switch (snd_usb_get_speed(dev)) {
case USB_SPEED_LOW:
case USB_SPEED_FULL:
case USB_SPEED_HIGH:
case USB_SPEED_WIRELESS:
case USB_SPEED_SUPER:
case USB_SPEED_SUPER_PLUS:
break;
default:
dev_err(&dev->dev, "unknown device speed %d\n", snd_usb_get_speed(dev));
return -ENXIO;
}
err = snd_card_new(&intf->dev, index[idx], id[idx], THIS_MODULE,
0, &card);
if (err < 0) {
dev_err(&dev->dev, "cannot create card instance %d\n", idx);
return err;
}
chip = kzalloc(sizeof(*chip), GFP_KERNEL);
if (! chip) {
snd_card_free(card);
return -ENOMEM;
}
mutex_init(&chip->mutex);
init_waitqueue_head(&chip->shutdown_wait);
chip->index = idx;
chip->dev = dev;
chip->card = card;
chip->setup = device_setup[idx];
chip->autoclock = autoclock;
atomic_set(&chip->active, 1); /* avoid autopm during probing */
atomic_set(&chip->usage_count, 0);
atomic_set(&chip->shutdown, 0);
chip->usb_id = usb_id;
INIT_LIST_HEAD(&chip->pcm_list);
INIT_LIST_HEAD(&chip->ep_list);
INIT_LIST_HEAD(&chip->midi_list);
INIT_LIST_HEAD(&chip->mixer_list);
if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops)) < 0) {
snd_usb_audio_free(chip);
snd_card_free(card);
return err;
}
strcpy(card->driver, "USB-Audio");
sprintf(component, "USB%04x:%04x",
USB_ID_VENDOR(chip->usb_id), USB_ID_PRODUCT(chip->usb_id));
snd_component_add(card, component);
/* retrieve the device string as shortname */
if (quirk && quirk->product_name && *quirk->product_name) {
strlcpy(card->shortname, quirk->product_name, sizeof(card->shortname));
} else {
if (!dev->descriptor.iProduct ||
usb_string(dev, dev->descriptor.iProduct,
card->shortname, sizeof(card->shortname)) <= 0) {
/* no name available from anywhere, so use ID */
sprintf(card->shortname, "USB Device %#04x:%#04x",
USB_ID_VENDOR(chip->usb_id),
USB_ID_PRODUCT(chip->usb_id));
}
}
strim(card->shortname);
/* retrieve the vendor and device strings as longname */
if (quirk && quirk->vendor_name && *quirk->vendor_name) {
len = strlcpy(card->longname, quirk->vendor_name, sizeof(card->longname));
} else {
if (dev->descriptor.iManufacturer)
len = usb_string(dev, dev->descriptor.iManufacturer,
card->longname, sizeof(card->longname));
else
len = 0;
/* we don't really care if there isn't any vendor string */
}
if (len > 0) {
strim(card->longname);
if (*card->longname)
strlcat(card->longname, " ", sizeof(card->longname));
}
strlcat(card->longname, card->shortname, sizeof(card->longname));
len = strlcat(card->longname, " at ", sizeof(card->longname));
if (len < sizeof(card->longname))
usb_make_path(dev, card->longname + len, sizeof(card->longname) - len);
switch (snd_usb_get_speed(dev)) {
case USB_SPEED_LOW:
strlcat(card->longname, ", low speed", sizeof(card->longname));
break;
case USB_SPEED_FULL:
strlcat(card->longname, ", full speed", sizeof(card->longname));
break;
case USB_SPEED_HIGH:
strlcat(card->longname, ", high speed", sizeof(card->longname));
break;
case USB_SPEED_SUPER:
strlcat(card->longname, ", super speed", sizeof(card->longname));
break;
case USB_SPEED_SUPER_PLUS:
strlcat(card->longname, ", super speed plus", sizeof(card->longname));
break;
default:
break;
}
snd_usb_audio_create_proc(chip);
*rchip = chip;
return 0;
}
/* look for a matching quirk alias id */
static bool get_alias_id(struct usb_device *dev, unsigned int *id)
{
int i;
unsigned int src, dst;
for (i = 0; i < ARRAY_SIZE(quirk_alias); i++) {
if (!quirk_alias[i] ||
sscanf(quirk_alias[i], "%x:%x", &src, &dst) != 2 ||
src != *id)
continue;
dev_info(&dev->dev,
"device (%04x:%04x): applying quirk alias %04x:%04x\n",
USB_ID_VENDOR(*id), USB_ID_PRODUCT(*id),
USB_ID_VENDOR(dst), USB_ID_PRODUCT(dst));
*id = dst;
return true;
}
return false;
}
static const struct usb_device_id usb_audio_ids[]; /* defined below */
/* look for the corresponding quirk */
static const struct snd_usb_audio_quirk *
get_alias_quirk(struct usb_device *dev, unsigned int id)
{
const struct usb_device_id *p;
for (p = usb_audio_ids; p->match_flags; p++) {
/* FIXME: this checks only vendor:product pair in the list */
if ((p->match_flags & USB_DEVICE_ID_MATCH_DEVICE) ==
USB_DEVICE_ID_MATCH_DEVICE &&
p->idVendor == USB_ID_VENDOR(id) &&
p->idProduct == USB_ID_PRODUCT(id))
return (const struct snd_usb_audio_quirk *)p->driver_info;
}
return NULL;
}
/*
* probe the active usb device
*
* note that this can be called multiple times per a device, when it
* includes multiple audio control interfaces.
*
* thus we check the usb device pointer and creates the card instance
* only at the first time. the successive calls of this function will
* append the pcm interface to the corresponding card.
*/
static int usb_audio_probe(struct usb_interface *intf,
const struct usb_device_id *usb_id)
{
struct usb_device *dev = interface_to_usbdev(intf);
const struct snd_usb_audio_quirk *quirk =
(const struct snd_usb_audio_quirk *)usb_id->driver_info;
struct snd_usb_audio *chip;
int i, err;
struct usb_host_interface *alts;
int ifnum;
u32 id;
alts = &intf->altsetting[0];
ifnum = get_iface_desc(alts)->bInterfaceNumber;
id = USB_ID(le16_to_cpu(dev->descriptor.idVendor),
le16_to_cpu(dev->descriptor.idProduct));
if (get_alias_id(dev, &id))
quirk = get_alias_quirk(dev, id);
if (quirk && quirk->ifnum >= 0 && ifnum != quirk->ifnum)
return -ENXIO;
err = snd_usb_apply_boot_quirk(dev, intf, quirk, id);
if (err < 0)
return err;
/*
* found a config. now register to ALSA
*/
/* check whether it's already registered */
chip = NULL;
mutex_lock(®ister_mutex);
for (i = 0; i < SNDRV_CARDS; i++) {
if (usb_chip[i] && usb_chip[i]->dev == dev) {
if (atomic_read(&usb_chip[i]->shutdown)) {
dev_err(&dev->dev, "USB device is in the shutdown state, cannot create a card instance\n");
err = -EIO;
goto __error;
}
chip = usb_chip[i];
atomic_inc(&chip->active); /* avoid autopm */
break;
}
}
if (! chip) {
/* it's a fresh one.
* now look for an empty slot and create a new card instance
*/
for (i = 0; i < SNDRV_CARDS; i++)
if (enable[i] && ! usb_chip[i] &&
(vid[i] == -1 || vid[i] == USB_ID_VENDOR(id)) &&
(pid[i] == -1 || pid[i] == USB_ID_PRODUCT(id))) {
err = snd_usb_audio_create(intf, dev, i, quirk,
id, &chip);
if (err < 0)
goto __error;
chip->pm_intf = intf;
break;
}
if (!chip) {
dev_err(&dev->dev, "no available usb audio device\n");
err = -ENODEV;
goto __error;
}
}
dev_set_drvdata(&dev->dev, chip);
/*
* For devices with more than one control interface, we assume the
* first contains the audio controls. We might need a more specific
* check here in the future.
*/
if (!chip->ctrl_intf)
chip->ctrl_intf = alts;
chip->txfr_quirk = 0;
err = 1; /* continue */
if (quirk && quirk->ifnum != QUIRK_NO_INTERFACE) {
/* need some special handlings */
err = snd_usb_create_quirk(chip, intf, &usb_audio_driver, quirk);
if (err < 0)
goto __error;
}
if (err > 0) {
/* create normal USB audio interfaces */
err = snd_usb_create_streams(chip, ifnum);
if (err < 0)
goto __error;
err = snd_usb_create_mixer(chip, ifnum, ignore_ctl_error);
if (err < 0)
goto __error;
}
/* we are allowed to call snd_card_register() many times */
err = snd_card_register(chip->card);
if (err < 0)
goto __error;
usb_chip[chip->index] = chip;
chip->num_interfaces++;
usb_set_intfdata(intf, chip);
atomic_dec(&chip->active);
mutex_unlock(®ister_mutex);
return 0;
__error:
if (chip) {
if (!chip->num_interfaces)
snd_card_free(chip->card);
atomic_dec(&chip->active);
}
mutex_unlock(®ister_mutex);
return err;
}
/*
* we need to take care of counter, since disconnection can be called also
* many times as well as usb_audio_probe().
*/
static void usb_audio_disconnect(struct usb_interface *intf)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct snd_card *card;
struct list_head *p;
if (chip == (void *)-1L)
return;
card = chip->card;
mutex_lock(®ister_mutex);
if (atomic_inc_return(&chip->shutdown) == 1) {
struct snd_usb_stream *as;
struct snd_usb_endpoint *ep;
struct usb_mixer_interface *mixer;
/* wait until all pending tasks done;
* they are protected by snd_usb_lock_shutdown()
*/
wait_event(chip->shutdown_wait,
!atomic_read(&chip->usage_count));
snd_card_disconnect(card);
/* release the pcm resources */
list_for_each_entry(as, &chip->pcm_list, list) {
snd_usb_stream_disconnect(as);
}
/* release the endpoint resources */
list_for_each_entry(ep, &chip->ep_list, list) {
snd_usb_endpoint_release(ep);
}
/* release the midi resources */
list_for_each(p, &chip->midi_list) {
snd_usbmidi_disconnect(p);
}
/* release mixer resources */
list_for_each_entry(mixer, &chip->mixer_list, list) {
snd_usb_mixer_disconnect(mixer);
}
}
chip->num_interfaces--;
if (chip->num_interfaces <= 0) {
usb_chip[chip->index] = NULL;
mutex_unlock(®ister_mutex);
snd_card_free_when_closed(card);
} else {
mutex_unlock(®ister_mutex);
}
}
/* lock the shutdown (disconnect) task and autoresume */
int snd_usb_lock_shutdown(struct snd_usb_audio *chip)
{
int err;
atomic_inc(&chip->usage_count);
if (atomic_read(&chip->shutdown)) {
err = -EIO;
goto error;
}
err = snd_usb_autoresume(chip);
if (err < 0)
goto error;
return 0;
error:
if (atomic_dec_and_test(&chip->usage_count))
wake_up(&chip->shutdown_wait);
return err;
}
/* autosuspend and unlock the shutdown */
void snd_usb_unlock_shutdown(struct snd_usb_audio *chip)
{
snd_usb_autosuspend(chip);
if (atomic_dec_and_test(&chip->usage_count))
wake_up(&chip->shutdown_wait);
}
#ifdef CONFIG_PM
int snd_usb_autoresume(struct snd_usb_audio *chip)
{
if (atomic_read(&chip->shutdown))
return -EIO;
if (atomic_inc_return(&chip->active) == 1)
return usb_autopm_get_interface(chip->pm_intf);
return 0;
}
void snd_usb_autosuspend(struct snd_usb_audio *chip)
{
if (atomic_read(&chip->shutdown))
return;
if (atomic_dec_and_test(&chip->active))
usb_autopm_put_interface(chip->pm_intf);
}
static int usb_audio_suspend(struct usb_interface *intf, pm_message_t message)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct snd_usb_stream *as;
struct usb_mixer_interface *mixer;
struct list_head *p;
if (chip == (void *)-1L)
return 0;
chip->autosuspended = !!PMSG_IS_AUTO(message);
if (!chip->autosuspended)
snd_power_change_state(chip->card, SNDRV_CTL_POWER_D3hot);
if (!chip->num_suspended_intf++) {
list_for_each_entry(as, &chip->pcm_list, list) {
snd_pcm_suspend_all(as->pcm);
as->substream[0].need_setup_ep =
as->substream[1].need_setup_ep = true;
}
list_for_each(p, &chip->midi_list)
snd_usbmidi_suspend(p);
list_for_each_entry(mixer, &chip->mixer_list, list)
snd_usb_mixer_suspend(mixer);
}
return 0;
}
static int __usb_audio_resume(struct usb_interface *intf, bool reset_resume)
{
struct snd_usb_audio *chip = usb_get_intfdata(intf);
struct usb_mixer_interface *mixer;
struct list_head *p;
int err = 0;
if (chip == (void *)-1L)
return 0;
if (--chip->num_suspended_intf)
return 0;
atomic_inc(&chip->active); /* avoid autopm */
/*
* ALSA leaves material resumption to user space
* we just notify and restart the mixers
*/
list_for_each_entry(mixer, &chip->mixer_list, list) {
err = snd_usb_mixer_resume(mixer, reset_resume);
if (err < 0)
goto err_out;
}
list_for_each(p, &chip->midi_list) {
snd_usbmidi_resume(p);
}
if (!chip->autosuspended)
snd_power_change_state(chip->card, SNDRV_CTL_POWER_D0);
chip->autosuspended = 0;
err_out:
atomic_dec(&chip->active); /* allow autopm after this point */
return err;
}
static int usb_audio_resume(struct usb_interface *intf)
{
return __usb_audio_resume(intf, false);
}
static int usb_audio_reset_resume(struct usb_interface *intf)
{
return __usb_audio_resume(intf, true);
}
#else
#define usb_audio_suspend NULL
#define usb_audio_resume NULL
#define usb_audio_reset_resume NULL
#endif /* CONFIG_PM */
static const struct usb_device_id usb_audio_ids [] = {
#include "quirks-table.h"
{ .match_flags = (USB_DEVICE_ID_MATCH_INT_CLASS | USB_DEVICE_ID_MATCH_INT_SUBCLASS),
.bInterfaceClass = USB_CLASS_AUDIO,
.bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL },
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE(usb, usb_audio_ids);
/*
* entry point for linux usb interface
*/
static struct usb_driver usb_audio_driver = {
.name = "snd-usb-audio",
.probe = usb_audio_probe,
.disconnect = usb_audio_disconnect,
.suspend = usb_audio_suspend,
.resume = usb_audio_resume,
.reset_resume = usb_audio_reset_resume,
.id_table = usb_audio_ids,
.supports_autosuspend = 1,
};
module_usb_driver(usb_audio_driver);
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2910_0 |
crossvul-cpp_data_good_4019_3 | /* exif-mnote-data-pentax.c
*
* Copyright (c) 2002, 2003 Lutz Mueller <lutz@users.sourceforge.net>
*
* 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 2 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, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include "exif-mnote-data-pentax.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <libexif/exif-byte-order.h>
#include <libexif/exif-utils.h>
#define CHECKOVERFLOW(offset,datasize,structsize) (( offset >= datasize) || (structsize > datasize) || (offset > datasize - structsize ))
static void
exif_mnote_data_pentax_clear (ExifMnoteDataPentax *n)
{
ExifMnoteData *d = (ExifMnoteData *) n;
unsigned int i;
if (!n) return;
if (n->entries) {
for (i = 0; i < n->count; i++)
if (n->entries[i].data) {
exif_mem_free (d->mem, n->entries[i].data);
n->entries[i].data = NULL;
}
exif_mem_free (d->mem, n->entries);
n->entries = NULL;
n->count = 0;
}
}
static void
exif_mnote_data_pentax_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_pentax_clear ((ExifMnoteDataPentax *) n);
}
static char *
exif_mnote_data_pentax_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) d;
if (!n) return NULL;
if (n->count <= i) return NULL;
return mnote_pentax_entry_get_value (&n->entries[i], val, maxlen);
}
/**
* @brief save the MnoteData from ne to buf
*
* @param ne extract the data from this structure
* @param *buf write the mnoteData to this buffer (buffer will be allocated)
* @param buf_size the final size of the buffer
*/
static void
exif_mnote_data_pentax_save (ExifMnoteData *ne,
unsigned char **buf, unsigned int *buf_size)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) ne;
size_t i, datao,
base = 0, /* internal MakerNote tag number offset */
o2 = 4 + 2; /* offset to first tag entry, past header */
if (!n || !buf || !buf_size) return;
datao = n->offset; /* this MakerNote style uses offsets
based on main IFD, not makernote IFD */
/*
* Allocate enough memory for header, the number of entries, entries,
* and next IFD pointer
*/
*buf_size = o2 + 2 + n->count * 12 + 4;
switch (n->version) {
case casioV2:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "QVC");
exif_set_short (*buf + 4, n->order, (ExifShort) 0);
break;
case pentaxV3:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "AOC");
exif_set_short (*buf + 4, n->order, (ExifShort) (
(n->order == EXIF_BYTE_ORDER_INTEL) ?
('I' << 8) | 'I' :
('M' << 8) | 'M'));
break;
case pentaxV2:
base = MNOTE_PENTAX2_TAG_BASE;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
/* Write the magic header */
strcpy ((char *)*buf, "AOC");
exif_set_short (*buf + 4, n->order, (ExifShort) 0);
break;
case pentaxV1:
/* It looks like this format doesn't have a magic header as
* such, just has a fixed number of entries equal to 0x001b */
*buf_size -= 6;
o2 -= 6;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", *buf_size);
return;
}
break;
default:
/* internal error */
return;
}
/* Write the number of entries. */
exif_set_short (*buf + o2, n->order, (ExifShort) n->count);
o2 += 2;
/* Save each entry */
for (i = 0; i < n->count; i++) {
size_t doff; /* offset to current data portion of tag */
size_t s;
unsigned char *t;
size_t o = o2 + i * 12; /* current offset into output buffer */
exif_set_short (*buf + o + 0, n->order,
(ExifShort) (n->entries[i].tag - base));
exif_set_short (*buf + o + 2, n->order,
(ExifShort) n->entries[i].format);
exif_set_long (*buf + o + 4, n->order,
n->entries[i].components);
o += 8;
s = exif_format_get_size (n->entries[i].format) *
n->entries[i].components;
if (s > 65536) {
/* Corrupt data: EXIF data size is limited to the
* maximum size of a JPEG segment (64 kb).
*/
continue;
}
if (s > 4) {
size_t ts = *buf_size + s;
doff = *buf_size;
t = exif_mem_realloc (ne->mem, *buf,
sizeof (char) * ts);
if (!t) {
EXIF_LOG_NO_MEMORY(ne->log, "ExifMnoteDataPentax", ts);
return;
}
*buf = t;
*buf_size = ts;
exif_set_long (*buf + o, n->order, datao + doff);
} else
doff = o;
/* Write the data. */
if (n->entries[i].data) {
memcpy (*buf + doff, n->entries[i].data, s);
} else {
/* Most certainly damaged input file */
memset (*buf + doff, 0, s);
}
}
/* Sanity check the buffer size */
if (*buf_size < (o2 + n->count * 12 + 4)) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifMnoteDataPentax",
"Buffer overflow");
}
/* Reset next IFD pointer */
exif_set_long (*buf + o2 + n->count * 12, n->order, 0);
}
static void
exif_mnote_data_pentax_load (ExifMnoteData *en,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) en;
size_t i, tcount, o, datao, base = 0;
ExifShort c;
if (!n || !buf || !buf_size) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
return;
}
datao = 6 + n->offset;
if (CHECKOVERFLOW(datao, buf_size, 8)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
return;
}
/* Detect variant of Pentax/Casio MakerNote found */
if (!memcmp(buf + datao, "AOC", 4)) {
if ((buf[datao + 4] == 'I') && (buf[datao + 5] == 'I')) {
n->version = pentaxV3;
n->order = EXIF_BYTE_ORDER_INTEL;
} else if ((buf[datao + 4] == 'M') && (buf[datao + 5] == 'M')) {
n->version = pentaxV3;
n->order = EXIF_BYTE_ORDER_MOTOROLA;
} else {
/* Uses Casio v2 tags */
n->version = pentaxV2;
}
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Pentax maker note v%d...", (int)n->version);
datao += 4 + 2;
base = MNOTE_PENTAX2_TAG_BASE;
} else if (!memcmp(buf + datao, "QVC", 4)) {
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Casio maker note v2...");
n->version = casioV2;
base = MNOTE_CASIO2_TAG_BASE;
datao += 4 + 2;
} else {
/* probably assert(!memcmp(buf + datao, "\x00\x1b", 2)) */
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataPentax",
"Parsing Pentax maker note v1...");
n->version = pentaxV1;
}
/* Read the number of tags */
c = exif_get_short (buf + datao, n->order);
datao += 2;
/* Remove any old entries */
exif_mnote_data_pentax_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (en->mem, sizeof (MnotePentaxEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", sizeof (MnotePentaxEntry) * c);
return;
}
/* Parse all c entries, storing ones that are successfully parsed */
tcount = 0;
for (i = c, o = datao; i; --i, o += 12) {
size_t s;
if (CHECKOVERFLOW(o,buf_size,12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Short MakerNote");
break;
}
n->entries[tcount].tag = exif_get_short (buf + o + 0, n->order) + base;
n->entries[tcount].format = exif_get_short (buf + o + 2, n->order);
n->entries[tcount].components = exif_get_long (buf + o + 4, n->order);
n->entries[tcount].order = n->order;
exif_log (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnotePentax",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_pentax_tag_get_name (n->entries[tcount].tag));
/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,
* we will check the buffer sizes closer later. */
if ( exif_format_get_size (n->entries[tcount].format) &&
buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components
) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataPentax", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);
break;
}
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) *
n->entries[tcount].components;
n->entries[tcount].size = s;
if (s) {
size_t dataofs = o + 8;
if (s > 4)
/* The data in this case is merely a pointer */
dataofs = exif_get_long (buf + dataofs, n->order) + 6;
if (CHECKOVERFLOW(dataofs, buf_size, s)) {
exif_log (en->log, EXIF_LOG_CODE_DEBUG,
"ExifMnoteDataPentax", "Tag data past end "
"of buffer (%u > %u)", (unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (en->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataPentax", s);
continue;
}
memcpy (n->entries[tcount].data, buf + dataofs, s);
}
/* Tag was successfully parsed */
++tcount;
}
/* Store the count of successfully parsed tags */
n->count = tcount;
}
static unsigned int
exif_mnote_data_pentax_count (ExifMnoteData *n)
{
return n ? ((ExifMnoteDataPentax *) n)->count : 0;
}
static unsigned int
exif_mnote_data_pentax_get_id (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return 0;
if (note->count <= n) return 0;
return note->entries[n].tag;
}
static const char *
exif_mnote_data_pentax_get_name (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_name (note->entries[n].tag);
}
static const char *
exif_mnote_data_pentax_get_title (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_title (note->entries[n].tag);
}
static const char *
exif_mnote_data_pentax_get_description (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataPentax *note = (ExifMnoteDataPentax *) d;
if (!note) return NULL;
if (note->count <= n) return NULL;
return mnote_pentax_tag_get_description (note->entries[n].tag);
}
static void
exif_mnote_data_pentax_set_offset (ExifMnoteData *d, unsigned int o)
{
if (d) ((ExifMnoteDataPentax *) d)->offset = o;
}
static void
exif_mnote_data_pentax_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataPentax *n = (ExifMnoteDataPentax *) d;
unsigned int i;
if (!n) return;
o_orig = n->order;
n->order = o;
for (i = 0; i < n->count; i++) {
if (n->entries[i].components && (n->entries[i].size/n->entries[i].components < exif_format_get_size (n->entries[i].format)))
continue;
n->entries[i].order = o;
exif_array_set_byte_order (n->entries[i].format, n->entries[i].data,
n->entries[i].components, o_orig, o);
}
}
int
exif_mnote_data_pentax_identify (const ExifData *ed, const ExifEntry *e)
{
(void) ed; /* unused */
if ((e->size >= 8) && !memcmp (e->data, "AOC", 4)) {
if (((e->data[4] == 'I') && (e->data[5] == 'I')) ||
((e->data[4] == 'M') && (e->data[5] == 'M')))
return pentaxV3;
else
/* Uses Casio v2 tags */
return pentaxV2;
}
if ((e->size >= 8) && !memcmp (e->data, "QVC", 4))
return casioV2;
/* This isn't a very robust test, so make sure it's done last */
/* Maybe we should additionally check for a make of Asahi or Pentax */
if ((e->size >= 2) && (e->data[0] == 0x00) && (e->data[1] == 0x1b))
return pentaxV1;
return 0;
}
ExifMnoteData *
exif_mnote_data_pentax_new (ExifMem *mem)
{
ExifMnoteData *d;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataPentax));
if (!d) return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_pentax_free;
d->methods.set_byte_order = exif_mnote_data_pentax_set_byte_order;
d->methods.set_offset = exif_mnote_data_pentax_set_offset;
d->methods.load = exif_mnote_data_pentax_load;
d->methods.save = exif_mnote_data_pentax_save;
d->methods.count = exif_mnote_data_pentax_count;
d->methods.get_id = exif_mnote_data_pentax_get_id;
d->methods.get_name = exif_mnote_data_pentax_get_name;
d->methods.get_title = exif_mnote_data_pentax_get_title;
d->methods.get_description = exif_mnote_data_pentax_get_description;
d->methods.get_value = exif_mnote_data_pentax_get_value;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_4019_3 |
crossvul-cpp_data_good_182_0 | /* radare - LGPL - Copyright 2015 - condret, riq */
/* 6502 info taken from http://unusedino.de/ec64/technical/aay/c64/bchrt651.htm
*
* Mnemonics logic based on:
* http://homepage.ntlworld.com/cyborgsystems/CS_Main/6502/6502.htm
* and:
* http://vice-emu.sourceforge.net/
*/
#include <string.h>
#include <r_types.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
#include "../../asm/arch/snes/snes_op_table.h"
enum {
_6502_FLAGS_C = (1 << 0),
_6502_FLAGS_B = (1 << 1),
_6502_FLAGS_Z = (1 << 2),
_6502_FLAGS_N = (1 << 3),
_6502_FLAGS_NZ = (_6502_FLAGS_Z | _6502_FLAGS_N),
_6502_FLAGS_CNZ = (_6502_FLAGS_C | _6502_FLAGS_Z | _6502_FLAGS_N),
_6502_FLAGS_BNZ = (_6502_FLAGS_B | _6502_FLAGS_Z | _6502_FLAGS_N),
};
static void _6502_anal_update_flags(RAnalOp *op, int flags) {
/* FIXME: $b9 instead of $b8 to prevent the bug triggered by: A = 0 - 0xff - 1 */
if (flags & _6502_FLAGS_B) r_strbuf_append (&op->esil, ",$b9,C,=");
if (flags & _6502_FLAGS_C) r_strbuf_append (&op->esil, ",$c7,C,=");
if (flags & _6502_FLAGS_Z) r_strbuf_append (&op->esil, ",$z,Z,=");
if (flags & _6502_FLAGS_N) r_strbuf_append (&op->esil, ",$s,N,=");
}
/* ORA, AND, EOR, ADC, STA, LDA, CMP and SBC share this pattern */
static void _6502_anal_esil_get_addr_pattern1(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize) {
// turn off bits 5, 6 and 7
switch(data[0] & 0x1f) { // 0x1f = b00111111
case 0x09: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize,"0x%02x", data[1]);
break;
case 0x05: // op $ff
op->cycles = 3;
snprintf (addrbuf, addrsize,"0x%02x", data[1]);
break;
case 0x15: // op $ff,x
op->cycles = 4;
snprintf (addrbuf, addrsize,"x,0x%02x,+", data[1]);
break;
case 0x0d: // op $ffff
op->cycles = 4;
snprintf (addrbuf, addrsize,"0x%04x", data[1] | data[2] << 8);
break;
case 0x1d: // op $ffff,x
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 4;
snprintf (addrbuf, addrsize,"x,0x%04x,+", data[1] | data[2] << 8);
break;
case 0x19: // op $ffff,y
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 4;
snprintf (addrbuf, addrsize,"y,0x%04x,+", data[1] | data[2] << 8);
break;
case 0x01: // op ($ff,x)
op->cycles = 6;
snprintf (addrbuf, addrsize,"x,0x%02x,+,[2]", data[1]);
break;
case 0x11: // op ($ff),y
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 5;
snprintf (addrbuf, addrsize,"y,0x%02x,[2],+", data[1]);
break;
}
}
/* ASL, ROL, LSR, ROR, STX, LDX, DEC and INC share this pattern */
static void _6502_anal_esil_get_addr_pattern2(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize, char reg) {
// turn off bits 5, 6 and 7
switch(data[0] & 0x1f) { // 0x1f = b00111111
case 0x02: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x0a: //op a
op->cycles = 2;
snprintf (addrbuf, addrsize, "a");
break;
case 0x06: // op $ff
op->cycles = 5;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x16: // op $ff,x
op->cycles = 6;
snprintf (addrbuf, addrsize, "%c,0x%02x,+", reg, data[1]);
break;
case 0x0e: // op $ffff
op->cycles = 6;
snprintf (addrbuf, addrsize, "0x%04x", data[1] | data[2] << 8);
break;
case 0x1e: // op $ffff,x
op->cycles = 7;
snprintf (addrbuf, addrsize, "%c,0x%04x,+", reg, data[1] | data[2] << 8);
break;
}
}
/* BIT, JMP, JMP(), STY, LDY, CPY, and CPX share this pattern */
static void _6502_anal_esil_get_addr_pattern3(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize, char reg) {
// turn off bits 5, 6 and 7
switch (data[0] & 0x1f) { // 0x1f = b00111111
case 0x00: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x08: //op a
op->cycles = 2;
snprintf (addrbuf, addrsize, "a");
break;
case 0x04: // op $ff
op->cycles = 5;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x14: // op $ff,x
op->cycles = 6;
snprintf (addrbuf, addrsize, "%c,0x%02x,+", reg, data[1]);
break;
case 0x0c: // op $ffff
op->cycles = 6;
snprintf (addrbuf, addrsize, "0x%04x", data[1] | data[2] << 8);
break;
case 0x1c: // op $ffff,x
op->cycles = 7;
snprintf (addrbuf, addrsize, "%c,0x%04x,+", reg, data[1] | data[2] << 8);
break;
}
}
static void _6502_anal_esil_ccall(RAnalOp *op, ut8 data0)
{
char *flag;
switch(data0) {
case 0x10: // bpl $ffff
flag = "N,!";
break;
case 0x30: // bmi $ffff
flag = "N";
break;
case 0x50: // bvc $ffff
flag = "V,!";
break;
case 0x70: // bvs $ffff
flag = "V";
break;
case 0x90: // bcc $ffff
flag = "C,!";
break;
case 0xb0: // bcs $ffff
flag = "C";
break;
case 0xd0: // bne $ffff
flag = "Z,!";
break;
case 0xf0: // beq $ffff
flag = "Z";
break;
default:
// FIXME: should not happen
flag = "unk";
break;
}
r_strbuf_setf (&op->esil, "%s,?{,0x%04x,pc,=,}", flag, (op->jump & 0xffff));
}
// inc register
static void _6502_anal_esil_inc_reg(RAnalOp *op, ut8 data0, char* sign)
{
char* reg = NULL;
switch(data0) {
case 0xe8: // inx
case 0xca: // dex
reg = "x";
break;
case 0xc8: // iny
case 0x88: // dey
reg = "y";
break;
}
r_strbuf_setf (&op->esil, "%s,%s%s=", reg, sign, sign);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_mov(RAnalOp *op, ut8 data0) {
const char* src="unk";
const char* dst="unk";
switch(data0) {
case 0xaa: // tax
src="a";
dst="x";
break;
case 0x8a: // txa
src="x";
dst="a";
break;
case 0xa8: // tay
src="a";
dst="y";
break;
case 0x98: // tya
src="y";
dst="a";
break;
case 0x9a: // txs
src="x";
dst="sp";
break;
case 0xba: // tsx
src="sp";
dst="x";
break;
default:
// FIXME: should not happen
break;
}
r_strbuf_setf (&op->esil, "%s,%s,=",src,dst);
// don't update NZ on txs
if (data0 != 0x9a) _6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_push(RAnalOp *op, ut8 data0) {
// case 0x08: // php
// case 0x48: // pha
char *reg = (data0==0x08) ? "flags" : "a";
// stack is on page one: sp + 0x100
r_strbuf_setf (&op->esil, "%s,sp,0x100,+,=[1],sp,--=", reg);
}
static void _6502_anal_esil_pop(RAnalOp *op, ut8 data0) {
// case 0x28: // plp
// case 0x68: // pla
char *reg = (data0==0x28) ? "flags" : "a";
// stack is on page one: sp + 0x100
r_strbuf_setf (&op->esil, "sp,++=,sp,0x100,+,[1],%s,=", reg);
if (data0==0x68) _6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_flags(RAnalOp *op, ut8 data0) {
int enabled=0;
char flag ='u';
switch(data0) {
case 0x78: // sei
enabled = 1;
flag = 'I';
break;
case 0x58: // cli
enabled = 0;
flag = 'I';
break;
case 0x38: // sec
enabled = 1;
flag = 'C';
break;
case 0x18: // clc
enabled = 0;
flag = 'C';
break;
case 0xf8: // sed
enabled = 1;
flag = 'D';
break;
case 0xd8: // cld
enabled = 0;
flag = 'D';
break;
case 0xb8: // clv
enabled = 0;
flag = 'V';
break;
break;
}
r_strbuf_setf (&op->esil, "%d,%c,=", enabled, flag);
}
static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
// undocumented or not-implemented opcodes for 6502.
// some of them might be implemented in 65816
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
// BRK
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
// override 65816 code which seems to be wrong: size is 1, but pc = pc + 2
op->size = 1;
// PC + 2 to Stack, P to Stack B=1 D=0 I=1. "B" is not a flag. Only its bit is pushed on the stack
// PC was already incremented by one at this point. Needs to incremented once more
// New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502)
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
// FLAGS
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
// FIXME: what opcode for this?
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
// BIT
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
// ADC
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
// fix Z
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
// SBC
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// fix Z and revert C
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
// ORA
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// AND
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// EOR
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ASL
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LSR
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROL
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROR
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
// uses N as temporary to hold C value. but in fact,
// it is not temporary since in all ROR ops, N will have the value of C
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INC
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// DEC
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INX, INY
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
// DEX, DEY
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
// CMP
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPX
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPY
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// BRANCHES
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
// FIXME: Add 1 if branch occurs to same page.
// FIXME: Add 2 if branch occurs to different page
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (len > 1) {
if (data[1] <= 127) {
op->jump = addr + data[1] + op->size;
} else {
op->jump = addr - (256 - data[1]) + op->size;
}
} else {
op->jump = addr;
}
op->fail = addr + op->size;
// FIXME: add a type of conditional
// op->cond = R_ANAL_COND_LE;
_6502_anal_esil_ccall (op, data[0]);
break;
// JSR
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
// JSR pushes the address-1 of the next operation on to the stack before transferring program
// control to the following address
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
// JMP
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
// FIXME: how to read memory?
// op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
// RTS
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
// Operation: PC from Stack, PC + 1 -> PC
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
// RTI
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
// Operation: P from Stack, PC from Stack
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
// NOP
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
// LDA
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDX
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDY
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// STA
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
// STX
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
// STY
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
// PHP/PHA
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
// PLP,PLA
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
// TAX,TYA,...
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
// FIXME: should I get register X a place it here?
// op->stackptr = get_register_x();
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
}
static int set_reg_profile(RAnal *anal) {
char *p =
"=PC pc\n"
"=SP sp\n"
"gpr a .8 0 0\n"
"gpr x .8 1 0\n"
"gpr y .8 2 0\n"
"gpr flags .8 3 0\n"
"gpr C .1 .24 0\n"
"gpr Z .1 .25 0\n"
"gpr I .1 .26 0\n"
"gpr D .1 .27 0\n"
// bit 4 (.28) is NOT a real flag.
// "gpr B .1 .28 0\n"
// bit 5 (.29) is not used
"gpr V .1 .30 0\n"
"gpr N .1 .31 0\n"
"gpr sp .8 4 0\n"
"gpr pc .16 5 0\n";
return r_reg_set_profile_string (anal->reg, p);
}
static int esil_6502_init (RAnalEsil *esil) {
if (esil->anal && esil->anal->reg) { //initial values
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "pc", -1), 0x0000);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "sp", -1), 0xff);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "a", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "x", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "y", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "flags", -1), 0x00);
}
return true;
}
static int esil_6502_fini (RAnalEsil *esil) {
return true;
}
RAnalPlugin r_anal_plugin_6502 = {
.name = "6502",
.desc = "6502/NES analysis plugin",
.license = "LGPL3",
.arch = "6502",
.bits = 8,
.op = &_6502_op,
.set_reg_profile = &set_reg_profile,
.esil = true,
.esil_init = esil_6502_init,
.esil_fini = esil_6502_fini,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_6502,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_182_0 |
crossvul-cpp_data_good_3369_0 | // imagew-jpeg.c
// Part of ImageWorsener, Copyright (c) 2011 by Jason Summers.
// For more information, see the readme.txt file.
#include "imagew-config.h"
#if IW_SUPPORT_JPEG == 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <setjmp.h>
#include <jpeglib.h>
#include <jerror.h>
#define IW_INCLUDE_UTIL_FUNCTIONS
#include "imagew.h"
#if BITS_IN_JSAMPLE != 8
#error "Wrong JSAMPLE size"
#endif
struct my_error_mgr {
struct jpeg_error_mgr pub;
jmp_buf setjmp_buffer;
};
static void my_error_exit(j_common_ptr cinfo)
{
struct my_error_mgr* myerr = (struct my_error_mgr*)cinfo->err;
longjmp(myerr->setjmp_buffer, 1);
}
// If we don't make our own output_message function, libjpeg will
// print warnings to stderr.
static void my_output_message(j_common_ptr cinfo)
{
return;
}
struct iwjpegrcontext {
struct jpeg_source_mgr pub; // This field must be first.
struct iw_context *ctx;
struct iw_iodescr *iodescr;
JOCTET *buffer;
size_t buffer_len;
int is_jfif;
unsigned int exif_orientation; // 0 means not set
double exif_density_x, exif_density_y; // -1.0 means not set.
unsigned int exif_density_unit; // 0 means not set
};
struct iw_exif_state {
int endian;
const iw_byte *d;
size_t d_len;
};
static unsigned int get_exif_ui16(struct iw_exif_state *e, unsigned int pos)
{
if(e->d_len<2 || pos>e->d_len-2) return 0;
return iw_get_ui16_e(&e->d[pos], e->endian);
}
static unsigned int get_exif_ui32(struct iw_exif_state *e, unsigned int pos)
{
if(e->d_len<4 || pos>e->d_len-4) return 0;
return iw_get_ui32_e(&e->d[pos], e->endian);
}
// Try to read an Exif tag into an integer.
// Returns zero on failure.
static int get_exif_tag_int_value(struct iw_exif_state *e, unsigned int tag_pos,
unsigned int *pv)
{
unsigned int field_type;
unsigned int value_count;
field_type = get_exif_ui16(e, tag_pos+2);
value_count = get_exif_ui32(e, tag_pos+4);
if(value_count!=1) return 0;
if(field_type==3) { // SHORT (uint16)
*pv = get_exif_ui16(e, tag_pos+8);
return 1;
}
else if(field_type==4) { // LONG (uint32)
*pv = get_exif_ui32(e, tag_pos+8);
return 1;
}
return 0;
}
// Read an Exif tag into a double.
// This only supports the case where the tag contains exactly one Rational value.
static int get_exif_tag_dbl_value(struct iw_exif_state *e, unsigned int tag_pos,
double *pv)
{
unsigned int field_type;
unsigned int value_count;
unsigned int value_pos;
unsigned int numer, denom;
field_type = get_exif_ui16(e, tag_pos+2);
value_count = get_exif_ui32(e, tag_pos+4);
if(value_count!=1) return 0;
if(field_type!=5) return 0; // 5=Rational (two uint32's)
// A rational is 8 bytes. Since 8>4, it is stored indirectly. First, read
// the location where it is stored.
value_pos = get_exif_ui32(e, tag_pos+8);
if(value_pos > e->d_len-8) return 0;
// Read the actual value.
numer = get_exif_ui32(e, value_pos);
denom = get_exif_ui32(e, value_pos+4);
if(denom==0) return 0;
*pv = ((double)numer)/denom;
return 1;
}
static void iwjpeg_scan_exif_ifd(struct iwjpegrcontext *rctx,
struct iw_exif_state *e, iw_uint32 ifd)
{
unsigned int tag_count;
unsigned int i;
unsigned int tag_pos;
unsigned int tag_id;
unsigned int v;
double v_dbl;
if(ifd<8 || e->d_len<18 || ifd>e->d_len-18) return;
tag_count = get_exif_ui16(e, ifd);
if(tag_count>1000) return; // Sanity check.
for(i=0;i<tag_count;i++) {
tag_pos = ifd+2+i*12;
if(tag_pos+12 > e->d_len) return; // Avoid overruns.
tag_id = get_exif_ui16(e, tag_pos);
switch(tag_id) {
case 274: // 274 = Orientation
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_orientation = v;
}
break;
case 296: // 296 = ResolutionUnit
if(get_exif_tag_int_value(e,tag_pos,&v)) {
rctx->exif_density_unit = v;
}
break;
case 282: // 282 = XResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_x = v_dbl;
}
break;
case 283: // 283 = YResolution
if(get_exif_tag_dbl_value(e,tag_pos,&v_dbl)) {
rctx->exif_density_y = v_dbl;
}
break;
}
}
}
static void iwjpeg_scan_exif(struct iwjpegrcontext *rctx,
const iw_byte *d, size_t d_len)
{
struct iw_exif_state e;
iw_uint32 ifd;
if(d_len<8) return;
iw_zeromem(&e,sizeof(struct iw_exif_state));
e.d = d;
e.d_len = d_len;
e.endian = d[0]=='I' ? IW_ENDIAN_LITTLE : IW_ENDIAN_BIG;
ifd = get_exif_ui32(&e, 4);
iwjpeg_scan_exif_ifd(rctx,&e,ifd);
}
// Look at the saved JPEG markers.
// The only one we care about is Exif.
static void iwjpeg_read_saved_markers(struct iwjpegrcontext *rctx,
struct jpeg_decompress_struct *cinfo)
{
struct jpeg_marker_struct *mk;
const iw_byte *d;
mk = cinfo->marker_list;
// Walk the list of saved markers.
while(mk) {
d = (const iw_byte*)mk->data;
if(mk->marker==0xe1) {
if(mk->data_length>=6 && d[0]=='E' && d[1]=='x' &&
d[2]=='i' && d[3]=='f' && d[4]==0)
{
// I don't know what the d[5] byte is for, but Exif
// data always starts with d[6].
iwjpeg_scan_exif(rctx, &d[6], mk->data_length-6);
}
}
mk = mk->next;
}
}
static void iwjpeg_read_density(struct iw_context *ctx, struct iw_image *img,
struct jpeg_decompress_struct *cinfo)
{
switch(cinfo->density_unit) {
case 1: // pixels/inch
img->density_x = ((double)cinfo->X_density)/0.0254;
img->density_y = ((double)cinfo->Y_density)/0.0254;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
case 2: // pixels/cm
img->density_x = ((double)cinfo->X_density)*100.0;
img->density_y = ((double)cinfo->Y_density)*100.0;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
default: // unknown units
// If we have square pixels with unknown units, we might be looking at
// libjpeg's default (i.e. no JFIF segment), or the density might have
// been read from the file. In either case, leave the density set to
// "unknown", which allows it to be overridden later by Exif data.
if(cinfo->X_density!=cinfo->Y_density) {
img->density_x = (double)cinfo->X_density;
img->density_y = (double)cinfo->Y_density;
img->density_code = IW_DENSITY_UNITS_UNKNOWN;
}
}
}
// Look at the Exif density setting that we may have recorded, and copy
// it to the image, if appropriate.
static void handle_exif_density(struct iwjpegrcontext *rctx, struct iw_image *img)
{
if(img->density_code!=IW_DENSITY_UNKNOWN) {
// We already have a density, presumably from the JFIF segment.
// TODO: In principle, Exif should not be allowed to overrule JFIF.
// But Exif density can be more precise than JFIF density, so it might
// be better to respect Exif.
// (On the other other hand, files with Exif data are usually from
// digital cameras, which means the density information is unlikely
// to be meaningful anyway.)
return;
}
if(rctx->exif_density_x<=0.0 || rctx->exif_density_y<=0.0) return;
switch(rctx->exif_density_unit) {
case 1: // No units
if(fabs(rctx->exif_density_x-rctx->exif_density_y)<0.00001)
return; // Square, unitless pixels = no meaningful information.
img->density_x = rctx->exif_density_x;
img->density_y = rctx->exif_density_y;
img->density_code = IW_DENSITY_UNITS_UNKNOWN;
break;
case 2: // Inches
img->density_x = rctx->exif_density_x/0.0254;
img->density_y = rctx->exif_density_y/0.0254;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
case 3: // Centimeters
img->density_x = rctx->exif_density_x*100.0;
img->density_y = rctx->exif_density_y*100.0;
img->density_code = IW_DENSITY_UNITS_PER_METER;
break;
}
}
static void my_init_source_fn(j_decompress_ptr cinfo)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = 0;
}
static boolean my_fill_input_buffer_fn(j_decompress_ptr cinfo)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
size_t bytesread = 0;
int ret;
ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr,
rctx->buffer,rctx->buffer_len,&bytesread);
if(!ret) return FALSE;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = bytesread;
if(bytesread<1) return FALSE;
return TRUE;
}
static void my_skip_input_data_fn(j_decompress_ptr cinfo, long num_bytes)
{
struct iwjpegrcontext *rctx = (struct iwjpegrcontext*)cinfo->src;
size_t bytes_still_to_skip;
size_t nbytes;
int ret;
size_t bytesread;
if(num_bytes<=0) return;
bytes_still_to_skip = (size_t)num_bytes;
while(bytes_still_to_skip>0) {
if(rctx->pub.bytes_in_buffer>0) {
// There are some bytes in the buffer. Skip up to
// 'bytes_still_to_skip' of them.
nbytes = rctx->pub.bytes_in_buffer;
if(nbytes>bytes_still_to_skip)
nbytes = bytes_still_to_skip;
rctx->pub.bytes_in_buffer -= nbytes;
rctx->pub.next_input_byte += nbytes;
bytes_still_to_skip -= nbytes;
}
if(bytes_still_to_skip<1) return;
// Need to read from the file (or do a seek, but we currently don't
// support seeking).
ret = (*rctx->iodescr->read_fn)(rctx->ctx,rctx->iodescr,
rctx->buffer,rctx->buffer_len,&bytesread);
if(!ret) bytesread=0;
rctx->pub.next_input_byte = rctx->buffer;
rctx->pub.bytes_in_buffer = bytesread;
}
}
static void my_term_source_fn(j_decompress_ptr cinfo)
{
}
static void convert_cmyk_to_rbg(struct iw_context *ctx, const JSAMPLE *src,
JSAMPLE *dst, int npixels)
{
int i;
double c, m, y, k, r, g, b;
for(i=0;i<npixels;i++) {
c = 1.0 - ((double)src[4*i+0])/255.0;
m = 1.0 - ((double)src[4*i+1])/255.0;
y = 1.0 - ((double)src[4*i+2])/255.0;
k = 1.0 - ((double)src[4*i+3])/255.0;
r = 1.0 - c*(1.0-k) - k;
g = 1.0 - m*(1.0-k) - k;
b = 1.0 - y*(1.0-k) - k;
if(r<0.0) r=0.0; if(r>1.0) r=1.0;
if(g<0.0) g=0.0; if(g>1.0) g=1.0;
if(b<0.0) b=0.0; if(b>1.0) b=1.0;
dst[3*i+0] = (JSAMPLE)(0.5+255.0*r);
dst[3*i+1] = (JSAMPLE)(0.5+255.0*g);
dst[3*i+2] = (JSAMPLE)(0.5+255.0*b);
}
}
IW_IMPL(int) iw_read_jpeg_file(struct iw_context *ctx, struct iw_iodescr *iodescr)
{
int retval=0;
struct jpeg_decompress_struct cinfo;
struct my_error_mgr jerr;
int cinfo_valid=0;
int colorspace;
JDIMENSION rownum;
JSAMPLE *jsamprow;
int numchannels=0;
struct iw_image img;
struct iwjpegrcontext rctx;
JSAMPLE *tmprow = NULL;
int cmyk_flag = 0;
iw_zeromem(&img,sizeof(struct iw_image));
iw_zeromem(&cinfo,sizeof(struct jpeg_decompress_struct));
iw_zeromem(&jerr,sizeof(struct my_error_mgr));
iw_zeromem(&rctx,sizeof(struct iwjpegrcontext));
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
jerr.pub.output_message = my_output_message;
if (setjmp(jerr.setjmp_buffer)) {
char buffer[JMSG_LENGTH_MAX];
(*cinfo.err->format_message) ((j_common_ptr)&cinfo, buffer);
iw_set_errorf(ctx,"libjpeg reports read error: %s",buffer);
goto done;
}
jpeg_create_decompress(&cinfo);
cinfo_valid=1;
// Set up our custom source manager.
rctx.pub.init_source = my_init_source_fn;
rctx.pub.fill_input_buffer = my_fill_input_buffer_fn;
rctx.pub.skip_input_data = my_skip_input_data_fn;
rctx.pub.resync_to_restart = jpeg_resync_to_restart; // libjpeg default
rctx.pub.term_source = my_term_source_fn;
rctx.ctx = ctx;
rctx.iodescr = iodescr;
rctx.buffer_len = 32768;
rctx.buffer = iw_malloc(ctx, rctx.buffer_len);
if(!rctx.buffer) goto done;
rctx.exif_density_x = -1.0;
rctx.exif_density_y = -1.0;
cinfo.src = (struct jpeg_source_mgr*)&rctx;
// The lazy way. It would be more efficient to use
// jpeg_set_marker_processor(), instead of saving everything to memory.
// But libjpeg's marker processing functions have fairly complex
// requirements.
jpeg_save_markers(&cinfo, 0xe1, 65535);
jpeg_read_header(&cinfo, TRUE);
rctx.is_jfif = cinfo.saw_JFIF_marker;
iwjpeg_read_density(ctx,&img,&cinfo);
iwjpeg_read_saved_markers(&rctx,&cinfo);
jpeg_start_decompress(&cinfo);
colorspace=cinfo.out_color_space;
numchannels=cinfo.output_components;
// libjpeg will automatically convert YCbCr images to RGB, and YCCK images
// to CMYK. That leaves GRAYSCALE, RGB, and CMYK for us to handle.
// Note: cinfo.jpeg_color_space is the colorspace before conversion, and
// cinfo.out_color_space is the colorspace after conversion.
if(colorspace==JCS_GRAYSCALE && numchannels==1) {
img.imgtype = IW_IMGTYPE_GRAY;
img.native_grayscale = 1;
}
else if((colorspace==JCS_RGB) && numchannels==3) {
img.imgtype = IW_IMGTYPE_RGB;
}
else if((colorspace==JCS_CMYK) && numchannels==4) {
img.imgtype = IW_IMGTYPE_RGB;
cmyk_flag = 1;
}
else {
iw_set_error(ctx,"Unsupported type of JPEG");
goto done;
}
img.width = cinfo.output_width;
img.height = cinfo.output_height;
if(!iw_check_image_dimensions(ctx,img.width,img.height)) {
goto done;
}
img.bit_depth = 8;
img.bpr = iw_calc_bytesperrow(img.width,img.bit_depth*numchannels);
img.pixels = (iw_byte*)iw_malloc_large(ctx, img.bpr, img.height);
if(!img.pixels) {
goto done;
}
if(cmyk_flag) {
tmprow = iw_malloc(ctx,4*img.width);
if(!tmprow) goto done;
}
while(cinfo.output_scanline < cinfo.output_height) {
rownum=cinfo.output_scanline;
jsamprow = &img.pixels[img.bpr * rownum];
if(cmyk_flag) {
// read into tmprow, then convert and copy to img.pixels
jpeg_read_scanlines(&cinfo, &tmprow, 1);
convert_cmyk_to_rbg(ctx,tmprow,jsamprow,img.width);
}
else {
// read directly into img.pixels
jpeg_read_scanlines(&cinfo, &jsamprow, 1);
}
if(cinfo.output_scanline<=rownum) {
iw_set_error(ctx,"Error reading JPEG file");
goto done;
}
}
jpeg_finish_decompress(&cinfo);
handle_exif_density(&rctx, &img);
iw_set_input_image(ctx, &img);
// The contents of img no longer belong to us.
img.pixels = NULL;
if(rctx.exif_orientation>=2 && rctx.exif_orientation<=8) {
static const unsigned int exif_orient_to_transform[9] =
{ 0,0, 1,3,2,4,5,7,6 };
// An Exif marker indicated an unusual image orientation.
if(rctx.is_jfif) {
// The presence of a JFIF marker implies a particular orientation.
// If there's also an Exif marker that says something different,
// I'm not sure what we're supposed to do.
iw_warning(ctx,"JPEG image has an ambiguous orientation");
}
iw_reorient_image(ctx,exif_orient_to_transform[rctx.exif_orientation]);
}
retval=1;
done:
iw_free(ctx, img.pixels);
if(cinfo_valid) jpeg_destroy_decompress(&cinfo);
if(rctx.buffer) iw_free(ctx,rctx.buffer);
if(tmprow) iw_free(ctx,tmprow);
return retval;
}
////////////////////////////////////
struct iwjpegwcontext {
struct jpeg_destination_mgr pub; // This field must be first.
struct iw_context *ctx;
struct iw_iodescr *iodescr;
JOCTET *buffer;
size_t buffer_len;
};
static void iwjpg_set_density(struct iw_context *ctx,struct jpeg_compress_struct *cinfo,
const struct iw_image *img)
{
int pref_units;
if(img->density_code==IW_DENSITY_UNITS_UNKNOWN) {
cinfo->density_unit=0; // unknown units
cinfo->X_density = (UINT16)(0.5+img->density_x);
cinfo->Y_density = (UINT16)(0.5+img->density_y);
}
else if(img->density_code==IW_DENSITY_UNITS_PER_METER) {
pref_units = iw_get_value(ctx,IW_VAL_PREF_UNITS);
if(pref_units==IW_PREF_UNITS_METRIC) {
// If we think the caller prefers metric, use dots/cm.
cinfo->density_unit=2; // dots/cm
cinfo->X_density = (UINT16)(0.5+ img->density_x*0.01);
cinfo->Y_density = (UINT16)(0.5+ img->density_y*0.01);
}
else {
// Otherwise use dpi.
cinfo->density_unit=1; // dots/inch
cinfo->X_density = (UINT16)(0.5+ img->density_x*0.0254);
cinfo->Y_density = (UINT16)(0.5+ img->density_y*0.0254);
}
}
}
static void my_init_destination_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
// Configure the destination manager to use our buffer.
wctx->pub.next_output_byte = wctx->buffer;
wctx->pub.free_in_buffer = wctx->buffer_len;
}
static boolean my_empty_output_buffer_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
// Write out the entire buffer
(*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,
wctx->buffer,wctx->buffer_len);
// Change the data pointer and free-space indicator to reflect the
// data we wrote.
wctx->pub.next_output_byte = wctx->buffer;
wctx->pub.free_in_buffer = wctx->buffer_len;
return TRUE;
}
static void my_term_destination_fn(j_compress_ptr cinfo)
{
struct iwjpegwcontext *wctx = (struct iwjpegwcontext*)cinfo->dest;
size_t bytesleft;
bytesleft = wctx->buffer_len - wctx->pub.free_in_buffer;
if(bytesleft>0) {
(*wctx->iodescr->write_fn)(wctx->ctx,wctx->iodescr,
wctx->buffer,bytesleft);
}
}
IW_IMPL(int) iw_write_jpeg_file(struct iw_context *ctx, struct iw_iodescr *iodescr)
{
int retval=0;
struct jpeg_compress_struct cinfo;
struct my_error_mgr jerr;
J_COLOR_SPACE in_colortype; // Color type of the data we give to libjpeg
int jpeg_cmpts;
int compress_created = 0;
int compress_started = 0;
JSAMPROW *row_pointers = NULL;
int is_grayscale;
int j;
struct iw_image img;
int jpeg_quality;
int samp_factor_h, samp_factor_v;
int disable_subsampling = 0;
struct iwjpegwcontext wctx;
const char *optv;
int ret;
iw_zeromem(&cinfo,sizeof(struct jpeg_compress_struct));
iw_zeromem(&jerr,sizeof(struct my_error_mgr));
iw_zeromem(&wctx,sizeof(struct iwjpegwcontext));
iw_get_output_image(ctx,&img);
if(IW_IMGTYPE_HAS_ALPHA(img.imgtype)) {
iw_set_error(ctx,"Internal: Transparency not supported with JPEG output");
goto done;
}
if(img.bit_depth!=8) {
iw_set_errorf(ctx,"Internal: Precision %d not supported with JPEG output",img.bit_depth);
goto done;
}
is_grayscale = IW_IMGTYPE_IS_GRAY(img.imgtype);
if(is_grayscale) {
in_colortype=JCS_GRAYSCALE;
jpeg_cmpts=1;
}
else {
in_colortype=JCS_RGB;
jpeg_cmpts=3;
}
cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = my_error_exit;
if (setjmp(jerr.setjmp_buffer)) {
char buffer[JMSG_LENGTH_MAX];
(*cinfo.err->format_message) ((j_common_ptr)&cinfo, buffer);
iw_set_errorf(ctx,"libjpeg reports write error: %s",buffer);
goto done;
}
jpeg_create_compress(&cinfo);
compress_created=1;
// Set up our custom destination manager.
wctx.pub.init_destination = my_init_destination_fn;
wctx.pub.empty_output_buffer = my_empty_output_buffer_fn;
wctx.pub.term_destination = my_term_destination_fn;
wctx.ctx = ctx;
wctx.iodescr = iodescr;
wctx.buffer_len = 32768;
wctx.buffer = iw_malloc(ctx,wctx.buffer_len);
if(!wctx.buffer) goto done;
// Our wctx is organized so it can double as a
// 'struct jpeg_destination_mgr'.
cinfo.dest = (struct jpeg_destination_mgr*)&wctx;
cinfo.image_width = img.width;
cinfo.image_height = img.height;
cinfo.input_components = jpeg_cmpts;
cinfo.in_color_space = in_colortype;
jpeg_set_defaults(&cinfo);
optv = iw_get_option(ctx, "jpeg:block");
if(optv) {
#if (JPEG_LIB_VERSION_MAJOR>=9 || \
(JPEG_LIB_VERSION_MAJOR==8 && JPEG_LIB_VERSION_MINOR>=3))
// Note: This might not work if DCT_SCALING_SUPPORTED was not defined when
// libjpeg was compiled, but that symbol is not normally exposed to
// applications.
cinfo.block_size = iw_parse_int(optv);
#else
iw_warning(ctx, "Setting block size is not supported by this version of libjpeg");
#endif
}
optv = iw_get_option(ctx, "jpeg:arith");
if(optv)
cinfo.arith_code = iw_parse_int(optv) ? TRUE : FALSE;
else
cinfo.arith_code = FALSE;
optv = iw_get_option(ctx, "jpeg:colortype");
if(optv) {
if(!strcmp(optv, "rgb")) {
if(in_colortype==JCS_RGB) {
jpeg_set_colorspace(&cinfo,JCS_RGB);
disable_subsampling = 1;
}
}
else if(!strcmp(optv, "rgb1")) {
if(in_colortype==JCS_RGB) {
#if JPEG_LIB_VERSION_MAJOR >= 9
cinfo.color_transform = JCT_SUBTRACT_GREEN;
#else
iw_warning(ctx, "Color type rgb1 is not supported by this version of libjpeg");
#endif
jpeg_set_colorspace(&cinfo,JCS_RGB);
disable_subsampling = 1;
}
}
}
optv = iw_get_option(ctx, "jpeg:bgycc");
if(optv && iw_parse_int(optv)) {
#if (JPEG_LIB_VERSION_MAJOR>9 || \
(JPEG_LIB_VERSION_MAJOR==9 && JPEG_LIB_VERSION_MINOR>=1))
jpeg_set_colorspace(&cinfo, JCS_BG_YCC);
#else
iw_warning(ctx, "Big gamut YCC is not supported by this version of libjpeg");
#endif
}
iwjpg_set_density(ctx,&cinfo,&img);
optv = iw_get_option(ctx, "jpeg:quality");
if(optv)
jpeg_quality = iw_parse_int(optv);
else
jpeg_quality = 0;
if(jpeg_quality>0) {
jpeg_set_quality(&cinfo,jpeg_quality,0);
}
if(jpeg_cmpts>1 && !disable_subsampling) {
samp_factor_h = 0;
samp_factor_v = 0;
// sampling-x and sampling-y are for backward compatibility, and should
// not be used.
optv = iw_get_option(ctx, "jpeg:sampling-x");
if(optv)
samp_factor_h = iw_parse_int(optv);
optv = iw_get_option(ctx, "jpeg:sampling-y");
if(optv)
samp_factor_v = iw_parse_int(optv);
optv = iw_get_option(ctx, "jpeg:sampling");
if(optv) {
double tmpsamp[2];
tmpsamp[0] = 1.0;
tmpsamp[1] = 1.0;
ret = iw_parse_number_list(optv, 2, tmpsamp);
samp_factor_h = iw_round_to_int(tmpsamp[0]);
if(ret==1) {
// If only one value was given, use it for both factors.
samp_factor_v = samp_factor_h;
}
else {
samp_factor_v = iw_round_to_int(tmpsamp[1]);
}
}
if(samp_factor_h>0) {
if(samp_factor_h>4) samp_factor_h=4;
cinfo.comp_info[0].h_samp_factor = samp_factor_h;
}
if(samp_factor_v>0) {
if(samp_factor_v>4) samp_factor_v=4;
cinfo.comp_info[0].v_samp_factor = samp_factor_v;
}
}
if(iw_get_value(ctx,IW_VAL_OUTPUT_INTERLACED)) {
jpeg_simple_progression(&cinfo);
}
row_pointers = (JSAMPROW*)iw_malloc(ctx, img.height * sizeof(JSAMPROW));
if(!row_pointers) goto done;
for(j=0;j<img.height;j++) {
row_pointers[j] = &img.pixels[j*img.bpr];
}
jpeg_start_compress(&cinfo, TRUE);
compress_started=1;
jpeg_write_scanlines(&cinfo, row_pointers, img.height);
retval=1;
done:
if(compress_started)
jpeg_finish_compress(&cinfo);
if(compress_created)
jpeg_destroy_compress(&cinfo);
if(row_pointers) iw_free(ctx,row_pointers);
if(wctx.buffer) iw_free(ctx,wctx.buffer);
return retval;
}
IW_IMPL(char*) iw_get_libjpeg_version_string(char *s, int s_len)
{
struct jpeg_error_mgr jerr;
const char *jv;
char *space_ptr;
jpeg_std_error(&jerr);
jv = jerr.jpeg_message_table[JMSG_VERSION];
iw_snprintf(s,s_len,"%s",jv);
// The version is probably a string like "8c 16-Jan-2011", containing
// both the version number and the release date. We only need the version
// number, so chop it off at the first space.
space_ptr = strchr(s,' ');
if(space_ptr) *space_ptr = '\0';
return s;
}
#endif // IW_SUPPORT_JPEG
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3369_0 |
crossvul-cpp_data_good_2696_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 Internet Control Message Protocol (ICMPv6) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "extract.h"
#include "ip6.h"
#include "ipproto.h"
#include "udp.h"
#include "ah.h"
/* NetBSD: icmp6.h,v 1.13 2000/08/03 16:30:37 itojun Exp */
/* $KAME: icmp6.h,v 1.22 2000/08/03 15:25:16 jinmei Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
struct icmp6_hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0] /* parameter prob */
#define icmp6_mtu icmp6_data32[0] /* packet too big */
#define icmp6_id icmp6_data16[0] /* echo request/reply */
#define icmp6_seq icmp6_data16[1] /* echo request/reply */
#define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */
#define ICMP6_DST_UNREACH 1 /* dest unreachable, codes: */
#define ICMP6_PACKET_TOO_BIG 2 /* packet too big */
#define ICMP6_TIME_EXCEEDED 3 /* time exceeded, code: */
#define ICMP6_PARAM_PROB 4 /* ip6 header bad */
#define ICMP6_ECHO_REQUEST 128 /* echo service */
#define ICMP6_ECHO_REPLY 129 /* echo reply */
#define ICMP6_MEMBERSHIP_QUERY 130 /* group membership query */
#define MLD6_LISTENER_QUERY 130 /* multicast listener query */
#define ICMP6_MEMBERSHIP_REPORT 131 /* group membership report */
#define MLD6_LISTENER_REPORT 131 /* multicast listener report */
#define ICMP6_MEMBERSHIP_REDUCTION 132 /* group membership termination */
#define MLD6_LISTENER_DONE 132 /* multicast listener done */
#define ND_ROUTER_SOLICIT 133 /* router solicitation */
#define ND_ROUTER_ADVERT 134 /* router advertisement */
#define ND_NEIGHBOR_SOLICIT 135 /* neighbor solicitation */
#define ND_NEIGHBOR_ADVERT 136 /* neighbor advertisement */
#define ND_REDIRECT 137 /* redirect */
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
#define ICMP6_WRUREQUEST 139 /* who are you request */
#define ICMP6_WRUREPLY 140 /* who are you reply */
#define ICMP6_FQDN_QUERY 139 /* FQDN query */
#define ICMP6_FQDN_REPLY 140 /* FQDN reply */
#define ICMP6_NI_QUERY 139 /* node information request */
#define ICMP6_NI_REPLY 140 /* node information reply */
#define IND_SOLICIT 141 /* inverse neighbor solicitation */
#define IND_ADVERT 142 /* inverse neighbor advertisement */
#define ICMP6_V2_MEMBERSHIP_REPORT 143 /* v2 membership report */
#define MLDV2_LISTENER_REPORT 143 /* v2 multicast listener report */
#define ICMP6_HADISCOV_REQUEST 144
#define ICMP6_HADISCOV_REPLY 145
#define ICMP6_MOBILEPREFIX_SOLICIT 146
#define ICMP6_MOBILEPREFIX_ADVERT 147
#define MLD6_MTRACE_RESP 200 /* mtrace response(to sender) */
#define MLD6_MTRACE 201 /* mtrace messages */
#define ICMP6_MAXTYPE 201
#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */
#define ICMP6_DST_UNREACH_ADMIN 1 /* administratively prohibited */
#define ICMP6_DST_UNREACH_NOTNEIGHBOR 2 /* not a neighbor(obsolete) */
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */
#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT 4 /* port unreachable */
#define ICMP6_TIME_EXCEED_TRANSIT 0 /* ttl==0 in transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* ttl==0 in reass */
#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */
#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized next header */
#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized option */
#define ICMP6_INFOMSG_MASK 0x80 /* all informational messages */
#define ICMP6_NI_SUBJ_IPV6 0 /* Query Subject is an IPv6 address */
#define ICMP6_NI_SUBJ_FQDN 1 /* Query Subject is a Domain name */
#define ICMP6_NI_SUBJ_IPV4 2 /* Query Subject is an IPv4 address */
#define ICMP6_NI_SUCCESS 0 /* node information successful reply */
#define ICMP6_NI_REFUSED 1 /* node information request is refused */
#define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */
#define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */
#define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */
/* Used in kernel only */
#define ND_REDIRECT_ONLINK 0 /* redirect to an on-link node */
#define ND_REDIRECT_ROUTER 1 /* redirect to a better router */
/*
* Multicast Listener Discovery
*/
struct mld6_hdr {
struct icmp6_hdr mld6_hdr;
struct in6_addr mld6_addr; /* multicast address */
};
#define mld6_type mld6_hdr.icmp6_type
#define mld6_code mld6_hdr.icmp6_code
#define mld6_cksum mld6_hdr.icmp6_cksum
#define mld6_maxdelay mld6_hdr.icmp6_data16[0]
#define mld6_reserved mld6_hdr.icmp6_data16[1]
#define MLD_MINLEN 24
#define MLDV2_MINLEN 28
/*
* Neighbor Discovery
*/
struct nd_router_solicit { /* router solicitation */
struct icmp6_hdr nd_rs_hdr;
/* could be followed by options */
};
#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]
struct nd_router_advert { /* router advertisement */
struct icmp6_hdr nd_ra_hdr;
uint32_t nd_ra_reachable; /* reachable time */
uint32_t nd_ra_retransmit; /* retransmit timer */
/* could be followed by options */
};
#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define ND_RA_FLAG_HOME_AGENT 0x20
/*
* Router preference values based on draft-draves-ipngwg-router-selection-01.
* These are non-standard definitions.
*/
#define ND_RA_FLAG_RTPREF_MASK 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_HIGH 0x08 /* 00001000 */
#define ND_RA_FLAG_RTPREF_MEDIUM 0x00 /* 00000000 */
#define ND_RA_FLAG_RTPREF_LOW 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_RSV 0x10 /* 00010000 */
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]
struct nd_neighbor_solicit { /* neighbor solicitation */
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target; /*target address */
/* could be followed by options */
};
#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]
struct nd_neighbor_advert { /* neighbor advertisement */
struct icmp6_hdr nd_na_hdr;
struct in6_addr nd_na_target; /* target address */
/* could be followed by options */
};
#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
struct nd_redirect { /* redirect */
struct icmp6_hdr nd_rd_hdr;
struct in6_addr nd_rd_target; /* target address */
struct in6_addr nd_rd_dst; /* destination address */
/* could be followed by options */
};
#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]
struct nd_opt_hdr { /* Neighbor discovery option header */
uint8_t nd_opt_type;
uint8_t nd_opt_len;
/* followed by option specific data*/
};
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
#define ND_OPT_ADVINTERVAL 7
#define ND_OPT_HOMEAGENT_INFO 8
#define ND_OPT_ROUTE_INFO 24 /* RFC4191 */
#define ND_OPT_RDNSS 25
#define ND_OPT_DNSSL 31
struct nd_opt_prefix_info { /* prefix information */
nd_uint8_t nd_opt_pi_type;
nd_uint8_t nd_opt_pi_len;
nd_uint8_t nd_opt_pi_prefix_len;
nd_uint8_t nd_opt_pi_flags_reserved;
nd_uint32_t nd_opt_pi_valid_time;
nd_uint32_t nd_opt_pi_preferred_time;
nd_uint32_t nd_opt_pi_reserved2;
struct in6_addr nd_opt_pi_prefix;
};
#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
#define ND_OPT_PI_FLAG_ROUTER 0x20 /*2292bis*/
struct nd_opt_rd_hdr { /* redirected header */
uint8_t nd_opt_rh_type;
uint8_t nd_opt_rh_len;
uint16_t nd_opt_rh_reserved1;
uint32_t nd_opt_rh_reserved2;
/* followed by IP header and data */
};
struct nd_opt_mtu { /* MTU option */
uint8_t nd_opt_mtu_type;
uint8_t nd_opt_mtu_len;
uint16_t nd_opt_mtu_reserved;
uint32_t nd_opt_mtu_mtu;
};
struct nd_opt_rdnss { /* RDNSS RFC 6106 5.1 */
uint8_t nd_opt_rdnss_type;
uint8_t nd_opt_rdnss_len;
uint16_t nd_opt_rdnss_reserved;
uint32_t nd_opt_rdnss_lifetime;
struct in6_addr nd_opt_rdnss_addr[1]; /* variable-length */
};
struct nd_opt_dnssl { /* DNSSL RFC 6106 5.2 */
uint8_t nd_opt_dnssl_type;
uint8_t nd_opt_dnssl_len;
uint16_t nd_opt_dnssl_reserved;
uint32_t nd_opt_dnssl_lifetime;
/* followed by list of DNS search domains, variable-length */
};
struct nd_opt_advinterval { /* Advertisement interval option */
uint8_t nd_opt_adv_type;
uint8_t nd_opt_adv_len;
uint16_t nd_opt_adv_reserved;
uint32_t nd_opt_adv_interval;
};
struct nd_opt_homeagent_info { /* Home Agent info */
uint8_t nd_opt_hai_type;
uint8_t nd_opt_hai_len;
uint16_t nd_opt_hai_reserved;
int16_t nd_opt_hai_preference;
uint16_t nd_opt_hai_lifetime;
};
struct nd_opt_route_info { /* route info */
uint8_t nd_opt_rti_type;
uint8_t nd_opt_rti_len;
uint8_t nd_opt_rti_prefixlen;
uint8_t nd_opt_rti_flags;
uint32_t nd_opt_rti_lifetime;
/* prefix follows */
};
/*
* icmp6 namelookup
*/
struct icmp6_namelookup {
struct icmp6_hdr icmp6_nl_hdr;
uint8_t icmp6_nl_nonce[8];
int32_t icmp6_nl_ttl;
#if 0
uint8_t icmp6_nl_len;
uint8_t icmp6_nl_name[3];
#endif
/* could be followed by options */
};
/*
* icmp6 node information
*/
struct icmp6_nodeinfo {
struct icmp6_hdr icmp6_ni_hdr;
uint8_t icmp6_ni_nonce[8];
/* could be followed by reply data */
};
#define ni_type icmp6_ni_hdr.icmp6_type
#define ni_code icmp6_ni_hdr.icmp6_code
#define ni_cksum icmp6_ni_hdr.icmp6_cksum
#define ni_qtype icmp6_ni_hdr.icmp6_data16[0]
#define ni_flags icmp6_ni_hdr.icmp6_data16[1]
#define NI_QTYPE_NOOP 0 /* NOOP */
#define NI_QTYPE_SUPTYPES 1 /* Supported Qtypes */
#define NI_QTYPE_FQDN 2 /* FQDN (draft 04) */
#define NI_QTYPE_DNSNAME 2 /* DNS Name */
#define NI_QTYPE_NODEADDR 3 /* Node Addresses */
#define NI_QTYPE_IPV4ADDR 4 /* IPv4 Addresses */
/* network endian */
#define NI_SUPTYPE_FLAG_COMPRESS ((uint16_t)htons(0x1))
#define NI_FQDN_FLAG_VALIDTTL ((uint16_t)htons(0x1))
/* network endian */
#define NI_NODEADDR_FLAG_TRUNCATE ((uint16_t)htons(0x1))
#define NI_NODEADDR_FLAG_ALL ((uint16_t)htons(0x2))
#define NI_NODEADDR_FLAG_COMPAT ((uint16_t)htons(0x4))
#define NI_NODEADDR_FLAG_LINKLOCAL ((uint16_t)htons(0x8))
#define NI_NODEADDR_FLAG_SITELOCAL ((uint16_t)htons(0x10))
#define NI_NODEADDR_FLAG_GLOBAL ((uint16_t)htons(0x20))
#define NI_NODEADDR_FLAG_ANYCAST ((uint16_t)htons(0x40)) /* just experimental. not in spec */
struct ni_reply_fqdn {
uint32_t ni_fqdn_ttl; /* TTL */
uint8_t ni_fqdn_namelen; /* length in octets of the FQDN */
uint8_t ni_fqdn_name[3]; /* XXX: alignment */
};
/*
* Router Renumbering. as router-renum-08.txt
*/
struct icmp6_router_renum { /* router renumbering header */
struct icmp6_hdr rr_hdr;
uint8_t rr_segnum;
uint8_t rr_flags;
uint16_t rr_maxdelay;
uint32_t rr_reserved;
};
#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08
#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]
struct rr_pco_match { /* match prefix part */
uint8_t rpm_code;
uint8_t rpm_len;
uint8_t rpm_ordinal;
uint8_t rpm_matchlen;
uint8_t rpm_minlen;
uint8_t rpm_maxlen;
uint16_t rpm_reserved;
struct in6_addr rpm_prefix;
};
#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3
#define RPM_PCO_MAX 4
struct rr_pco_use { /* use prefix part */
uint8_t rpu_uselen;
uint8_t rpu_keeplen;
uint8_t rpu_ramask;
uint8_t rpu_raflags;
uint32_t rpu_vltime;
uint32_t rpu_pltime;
uint32_t rpu_flags;
struct in6_addr rpu_prefix;
};
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x80
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x40
/* network endian */
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME ((uint32_t)htonl(0x80000000))
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME ((uint32_t)htonl(0x40000000))
struct rr_result { /* router renumbering result message */
uint16_t rrr_flags;
uint8_t rrr_ordinal;
uint8_t rrr_matchedlen;
uint32_t rrr_ifid;
struct in6_addr rrr_prefix;
};
/* network endian */
#define ICMP6_RR_RESULT_FLAGS_OOB ((uint16_t)htons(0x0002))
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN ((uint16_t)htons(0x0001))
static const char *get_rtpref(u_int);
static const char *get_lifetime(uint32_t);
static void print_lladdr(netdissect_options *ndo, const u_char *, size_t);
static void icmp6_opt_print(netdissect_options *ndo, const u_char *, int);
static void mld6_print(netdissect_options *ndo, const u_char *);
static void mldv2_report_print(netdissect_options *ndo, const u_char *, u_int);
static void mldv2_query_print(netdissect_options *ndo, const u_char *, u_int);
static const struct udphdr *get_upperlayer(netdissect_options *ndo, const u_char *, u_int *);
static void dnsname_print(netdissect_options *ndo, const u_char *, const u_char *);
static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int, const u_char *, const u_char *);
static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *, const u_char *);
#ifndef abs
#define abs(a) ((0 < (a)) ? (a) : -(a))
#endif
#include "rpl.h"
static const struct tok icmp6_type_values[] = {
{ ICMP6_DST_UNREACH, "destination unreachable"},
{ ICMP6_PACKET_TOO_BIG, "packet too big"},
{ ICMP6_TIME_EXCEEDED, "time exceeded in-transit"},
{ ICMP6_PARAM_PROB, "parameter problem"},
{ ICMP6_ECHO_REQUEST, "echo request"},
{ ICMP6_ECHO_REPLY, "echo reply"},
{ MLD6_LISTENER_QUERY, "multicast listener query"},
{ MLD6_LISTENER_REPORT, "multicast listener report"},
{ MLD6_LISTENER_DONE, "multicast listener done"},
{ ND_ROUTER_SOLICIT, "router solicitation"},
{ ND_ROUTER_ADVERT, "router advertisement"},
{ ND_NEIGHBOR_SOLICIT, "neighbor solicitation"},
{ ND_NEIGHBOR_ADVERT, "neighbor advertisement"},
{ ND_REDIRECT, "redirect"},
{ ICMP6_ROUTER_RENUMBERING, "router renumbering"},
{ IND_SOLICIT, "inverse neighbor solicitation"},
{ IND_ADVERT, "inverse neighbor advertisement"},
{ MLDV2_LISTENER_REPORT, "multicast listener report v2"},
{ ICMP6_HADISCOV_REQUEST, "ha discovery request"},
{ ICMP6_HADISCOV_REPLY, "ha discovery reply"},
{ ICMP6_MOBILEPREFIX_SOLICIT, "mobile router solicitation"},
{ ICMP6_MOBILEPREFIX_ADVERT, "mobile router advertisement"},
{ ICMP6_WRUREQUEST, "who-are-you request"},
{ ICMP6_WRUREPLY, "who-are-you reply"},
{ ICMP6_NI_QUERY, "node information query"},
{ ICMP6_NI_REPLY, "node information reply"},
{ MLD6_MTRACE, "mtrace message"},
{ MLD6_MTRACE_RESP, "mtrace response"},
{ ND_RPL_MESSAGE, "RPL"},
{ 0, NULL }
};
static const struct tok icmp6_dst_unreach_code_values[] = {
{ ICMP6_DST_UNREACH_NOROUTE, "unreachable route" },
{ ICMP6_DST_UNREACH_ADMIN, " unreachable prohibited"},
{ ICMP6_DST_UNREACH_BEYONDSCOPE, "beyond scope"},
{ ICMP6_DST_UNREACH_ADDR, "unreachable address"},
{ ICMP6_DST_UNREACH_NOPORT, "unreachable port"},
{ 0, NULL }
};
static const struct tok icmp6_opt_pi_flag_values[] = {
{ ND_OPT_PI_FLAG_ONLINK, "onlink" },
{ ND_OPT_PI_FLAG_AUTO, "auto" },
{ ND_OPT_PI_FLAG_ROUTER, "router" },
{ 0, NULL }
};
static const struct tok icmp6_opt_ra_flag_values[] = {
{ ND_RA_FLAG_MANAGED, "managed" },
{ ND_RA_FLAG_OTHER, "other stateful"},
{ ND_RA_FLAG_HOME_AGENT, "home agent"},
{ 0, NULL }
};
static const struct tok icmp6_nd_na_flag_values[] = {
{ ND_NA_FLAG_ROUTER, "router" },
{ ND_NA_FLAG_SOLICITED, "solicited" },
{ ND_NA_FLAG_OVERRIDE, "override" },
{ 0, NULL }
};
static const struct tok icmp6_opt_values[] = {
{ ND_OPT_SOURCE_LINKADDR, "source link-address"},
{ ND_OPT_TARGET_LINKADDR, "destination link-address"},
{ ND_OPT_PREFIX_INFORMATION, "prefix info"},
{ ND_OPT_REDIRECTED_HEADER, "redirected header"},
{ ND_OPT_MTU, "mtu"},
{ ND_OPT_RDNSS, "rdnss"},
{ ND_OPT_DNSSL, "dnssl"},
{ ND_OPT_ADVINTERVAL, "advertisement interval"},
{ ND_OPT_HOMEAGENT_INFO, "homeagent information"},
{ ND_OPT_ROUTE_INFO, "route info"},
{ 0, NULL }
};
/* mldv2 report types */
static const struct tok mldv2report2str[] = {
{ 1, "is_in" },
{ 2, "is_ex" },
{ 3, "to_in" },
{ 4, "to_ex" },
{ 5, "allow" },
{ 6, "block" },
{ 0, NULL }
};
static const char *
get_rtpref(u_int v)
{
static const char *rtpref_str[] = {
"medium", /* 00 */
"high", /* 01 */
"rsv", /* 10 */
"low" /* 11 */
};
return rtpref_str[((v & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff];
}
static const char *
get_lifetime(uint32_t v)
{
static char buf[20];
if (v == (uint32_t)~0UL)
return "infinity";
else {
snprintf(buf, sizeof(buf), "%us", v);
return buf;
}
}
static void
print_lladdr(netdissect_options *ndo, const uint8_t *p, size_t l)
{
const uint8_t *ep, *q;
q = p;
ep = p + l;
while (l > 0 && q < ep) {
if (q > p)
ND_PRINT((ndo,":"));
ND_PRINT((ndo,"%02x", *q++));
l--;
}
}
static int icmp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6,
const struct icmp6_hdr *icp, u_int len)
{
return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)icp, len, len,
IPPROTO_ICMPV6);
}
static const struct tok rpl_mop_values[] = {
{ RPL_DIO_NONSTORING, "nonstoring"},
{ RPL_DIO_STORING, "storing"},
{ RPL_DIO_NONSTORING_MULTICAST, "nonstoring-multicast"},
{ RPL_DIO_STORING_MULTICAST, "storing-multicast"},
{ 0, NULL},
};
static const struct tok rpl_subopt_values[] = {
{ RPL_OPT_PAD0, "pad0"},
{ RPL_OPT_PADN, "padN"},
{ RPL_DIO_METRICS, "metrics"},
{ RPL_DIO_ROUTINGINFO, "routinginfo"},
{ RPL_DIO_CONFIG, "config"},
{ RPL_DAO_RPLTARGET, "rpltarget"},
{ RPL_DAO_TRANSITINFO, "transitinfo"},
{ RPL_DIO_DESTPREFIX, "destprefix"},
{ RPL_DAO_RPLTARGET_DESC, "rpltargetdesc"},
{ 0, NULL},
};
static void
rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dio_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp;
const char *dagid_str;
ND_TCHECK(*dio);
dagid_str = ip6addr_string (ndo, dio->rpl_dagid);
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]",
dagid_str,
dio->rpl_dtsn,
dio->rpl_instanceid,
EXTRACT_16BITS(&dio->rpl_dagrank),
RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"",
tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)),
RPL_DIO_PRF(dio->rpl_mopprf)));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1];
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
static void
rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
static void
rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
void
icmp6_print(netdissect_options *ndo,
const u_char *bp, u_int length, const u_char *bp2, int fragmented)
{
const struct icmp6_hdr *dp;
const struct ip6_hdr *ip;
const struct ip6_hdr *oip;
const struct udphdr *ouh;
int dport;
const u_char *ep;
u_int prot;
dp = (const struct icmp6_hdr *)bp;
ip = (const struct ip6_hdr *)bp2;
oip = (const struct ip6_hdr *)(dp + 1);
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->icmp6_cksum);
if (ndo->ndo_vflag && !fragmented) {
uint16_t sum, udp_sum;
if (ND_TTEST2(bp[0], length)) {
udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum);
sum = icmp6_cksum(ndo, ip, dp, length);
if (sum != 0)
ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ",
udp_sum,
in_cksum_shouldbe(udp_sum, sum)));
else
ND_PRINT((ndo,"[icmp6 sum ok] "));
}
}
ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type)));
/* display cosmetics: print the packet length for printer that use the vflag now */
if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT ||
dp->icmp6_type == ND_ROUTER_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
dp->icmp6_type == ND_REDIRECT ||
dp->icmp6_type == ICMP6_HADISCOV_REPLY ||
dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT ))
ND_PRINT((ndo,", length %u", length));
switch (dp->icmp6_type) {
case ICMP6_DST_UNREACH:
ND_TCHECK(oip->ip6_dst);
ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code)));
switch (dp->icmp6_code) {
case ICMP6_DST_UNREACH_NOROUTE: /* fall through */
case ICMP6_DST_UNREACH_ADMIN:
case ICMP6_DST_UNREACH_ADDR:
ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_DST_UNREACH_BEYONDSCOPE:
ND_PRINT((ndo," %s, source address %s",
ip6addr_string(ndo, &oip->ip6_dst),
ip6addr_string(ndo, &oip->ip6_src)));
break;
case ICMP6_DST_UNREACH_NOPORT:
if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot))
== NULL)
goto trunc;
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (prot) {
case IPPROTO_TCP:
ND_PRINT((ndo,", %s tcp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
tcpport_string(ndo, dport)));
break;
case IPPROTO_UDP:
ND_PRINT((ndo,", %s udp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
udpport_string(ndo, dport)));
break;
default:
ND_PRINT((ndo,", %s protocol %d port %d unreachable",
ip6addr_string(ndo, &oip->ip6_dst),
oip->ip6_nxt, dport));
break;
}
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, bp,"\n\t",length);
return;
}
break;
}
break;
case ICMP6_PACKET_TOO_BIG:
ND_TCHECK(dp->icmp6_mtu);
ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu)));
break;
case ICMP6_TIME_EXCEEDED:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_TIME_EXCEED_TRANSIT:
ND_PRINT((ndo," for %s",
ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_TIME_EXCEED_REASSEMBLY:
ND_PRINT((ndo," (reassembly)"));
break;
default:
ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code));
break;
}
break;
case ICMP6_PARAM_PROB:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_PARAMPROB_HEADER:
ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_NEXTHEADER:
ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_OPTION:
ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
default:
ND_PRINT((ndo,", code-#%d",
dp->icmp6_code));
break;
}
break;
case ICMP6_ECHO_REQUEST:
case ICMP6_ECHO_REPLY:
ND_TCHECK(dp->icmp6_seq);
ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq)));
break;
case ICMP6_MEMBERSHIP_QUERY:
if (length == MLD_MINLEN) {
mld6_print(ndo, (const u_char *)dp);
} else if (length >= MLDV2_MINLEN) {
ND_PRINT((ndo," v2"));
mldv2_query_print(ndo, (const u_char *)dp, length);
} else {
ND_PRINT((ndo," unknown-version (len %u) ", length));
}
break;
case ICMP6_MEMBERSHIP_REPORT:
mld6_print(ndo, (const u_char *)dp);
break;
case ICMP6_MEMBERSHIP_REDUCTION:
mld6_print(ndo, (const u_char *)dp);
break;
case ND_ROUTER_SOLICIT:
#define RTSOLLEN 8
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN,
length - RTSOLLEN);
}
break;
case ND_ROUTER_ADVERT:
#define RTADVLEN 16
if (ndo->ndo_vflag) {
const struct nd_router_advert *p;
p = (const struct nd_router_advert *)dp;
ND_TCHECK(p->nd_ra_retransmit);
ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \
", pref %s, router lifetime %us, reachable time %us, retrans time %us",
(u_int)p->nd_ra_curhoplimit,
bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)),
get_rtpref(p->nd_ra_flags_reserved),
EXTRACT_16BITS(&p->nd_ra_router_lifetime),
EXTRACT_32BITS(&p->nd_ra_reachable),
EXTRACT_32BITS(&p->nd_ra_retransmit)));
icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN,
length - RTADVLEN);
}
break;
case ND_NEIGHBOR_SOLICIT:
{
const struct nd_neighbor_solicit *p;
p = (const struct nd_neighbor_solicit *)dp;
ND_TCHECK(p->nd_ns_target);
ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target)));
if (ndo->ndo_vflag) {
#define NDSOLLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN,
length - NDSOLLEN);
}
}
break;
case ND_NEIGHBOR_ADVERT:
{
const struct nd_neighbor_advert *p;
p = (const struct nd_neighbor_advert *)dp;
ND_TCHECK(p->nd_na_target);
ND_PRINT((ndo,", tgt is %s",
ip6addr_string(ndo, &p->nd_na_target)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo,", Flags [%s]",
bittok2str(icmp6_nd_na_flag_values,
"none",
EXTRACT_32BITS(&p->nd_na_flags_reserved))));
#define NDADVLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN,
length - NDADVLEN);
#undef NDADVLEN
}
}
break;
case ND_REDIRECT:
#define RDR(i) ((const struct nd_redirect *)(i))
ND_TCHECK(RDR(dp)->nd_rd_dst);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst)));
ND_TCHECK(RDR(dp)->nd_rd_target);
ND_PRINT((ndo," to %s",
ip6addr_string(ndo, &RDR(dp)->nd_rd_target)));
#define REDIRECTLEN 40
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN,
length - REDIRECTLEN);
}
break;
#undef REDIRECTLEN
#undef RDR
case ICMP6_ROUTER_RENUMBERING:
icmp6_rrenum_print(ndo, bp, ep);
break;
case ICMP6_NI_QUERY:
case ICMP6_NI_REPLY:
icmp6_nodeinfo_print(ndo, length, bp, ep);
break;
case IND_SOLICIT:
case IND_ADVERT:
break;
case ICMP6_V2_MEMBERSHIP_REPORT:
mldv2_report_print(ndo, (const u_char *) dp, length);
break;
case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */
case ICMP6_HADISCOV_REQUEST:
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
break;
case ICMP6_HADISCOV_REPLY:
if (ndo->ndo_vflag) {
const struct in6_addr *in6;
const u_char *cp;
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
cp = (const u_char *)dp + length;
in6 = (const struct in6_addr *)(dp + 1);
for (; (const u_char *)in6 < cp; in6++) {
ND_TCHECK(*in6);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6)));
}
}
break;
case ICMP6_MOBILEPREFIX_ADVERT:
if (ndo->ndo_vflag) {
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
ND_TCHECK(dp->icmp6_data16[1]);
if (dp->icmp6_data16[1] & 0xc0)
ND_PRINT((ndo," "));
if (dp->icmp6_data16[1] & 0x80)
ND_PRINT((ndo,"M"));
if (dp->icmp6_data16[1] & 0x40)
ND_PRINT((ndo,"O"));
#define MPADVLEN 8
icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN,
length - MPADVLEN);
}
break;
case ND_RPL_MESSAGE:
/* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */
rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4);
break;
default:
ND_PRINT((ndo,", length %u", length));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp,"\n\t", length);
return;
}
if (!ndo->ndo_vflag)
ND_PRINT((ndo,", length %u", length));
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static const struct udphdr *
get_upperlayer(netdissect_options *ndo, const u_char *bp, u_int *prot)
{
const u_char *ep;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
const struct udphdr *uh;
const struct ip6_hbh *hbh;
const struct ip6_frag *fragh;
const struct ah *ah;
u_int nh;
int hlen;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(ip6->ip6_nxt))
return NULL;
nh = ip6->ip6_nxt;
hlen = sizeof(struct ip6_hdr);
while (bp < ep) {
bp += hlen;
switch(nh) {
case IPPROTO_UDP:
case IPPROTO_TCP:
uh = (const struct udphdr *)bp;
if (ND_TTEST(uh->uh_dport)) {
*prot = nh;
return(uh);
}
else
return(NULL);
/* NOTREACHED */
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
hbh = (const struct ip6_hbh *)bp;
if (!ND_TTEST(hbh->ip6h_len))
return(NULL);
nh = hbh->ip6h_nxt;
hlen = (hbh->ip6h_len + 1) << 3;
break;
case IPPROTO_FRAGMENT: /* this should be odd, but try anyway */
fragh = (const struct ip6_frag *)bp;
if (!ND_TTEST(fragh->ip6f_offlg))
return(NULL);
/* fragments with non-zero offset are meaningless */
if ((EXTRACT_16BITS(&fragh->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return(NULL);
nh = fragh->ip6f_nxt;
hlen = sizeof(struct ip6_frag);
break;
case IPPROTO_AH:
ah = (const struct ah *)bp;
if (!ND_TTEST(ah->ah_len))
return(NULL);
nh = ah->ah_nxt;
hlen = (ah->ah_len + 2) << 2;
break;
default: /* unknown or undecodable header */
*prot = nh; /* meaningless, but set here anyway */
return(NULL);
}
}
return(NULL); /* should be notreached, though */
}
static void
icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid)
{
const struct nd_opt_hdr *op;
const struct nd_opt_prefix_info *opp;
const struct nd_opt_mtu *opm;
const struct nd_opt_rdnss *oprd;
const struct nd_opt_dnssl *opds;
const struct nd_opt_advinterval *opa;
const struct nd_opt_homeagent_info *oph;
const struct nd_opt_route_info *opri;
const u_char *cp, *ep, *domp;
struct in6_addr in6;
const struct in6_addr *in6p;
size_t l;
u_int i;
#define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return
cp = bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
while (cp < ep) {
op = (const struct nd_opt_hdr *)cp;
ECHECK(op->nd_opt_len);
if (resid <= 0)
return;
if (op->nd_opt_len == 0)
goto trunc;
if (cp + (op->nd_opt_len << 3) > ep)
goto trunc;
ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ",
tok2str(icmp6_opt_values, "unknown", op->nd_opt_type),
op->nd_opt_type,
op->nd_opt_len << 3,
op->nd_opt_len));
switch (op->nd_opt_type) {
case ND_OPT_SOURCE_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_TARGET_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_PREFIX_INFORMATION:
opp = (const struct nd_opt_prefix_info *)op;
ND_TCHECK(opp->nd_opt_pi_prefix);
ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s",
ip6addr_string(ndo, &opp->nd_opt_pi_prefix),
opp->nd_opt_pi_prefix_len,
(op->nd_opt_len != 4) ? "badlen" : "",
bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved),
get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time))));
ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time))));
break;
case ND_OPT_REDIRECTED_HEADER:
print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3);
/* xxx */
break;
case ND_OPT_MTU:
opm = (const struct nd_opt_mtu *)op;
ND_TCHECK(opm->nd_opt_mtu_mtu);
ND_PRINT((ndo," %u%s",
EXTRACT_32BITS(&opm->nd_opt_mtu_mtu),
(op->nd_opt_len != 1) ? "bad option length" : "" ));
break;
case ND_OPT_RDNSS:
oprd = (const struct nd_opt_rdnss *)op;
l = (op->nd_opt_len - 1) / 2;
ND_PRINT((ndo," lifetime %us,",
EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime)));
for (i = 0; i < l; i++) {
ND_TCHECK(oprd->nd_opt_rdnss_addr[i]);
ND_PRINT((ndo," addr: %s",
ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i])));
}
break;
case ND_OPT_DNSSL:
opds = (const struct nd_opt_dnssl *)op;
ND_PRINT((ndo," lifetime %us, domain(s):",
EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime)));
domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */
while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0')
{
ND_PRINT((ndo, " "));
if ((domp = ns_nprint (ndo, domp, bp)) == NULL)
goto trunc;
}
break;
case ND_OPT_ADVINTERVAL:
opa = (const struct nd_opt_advinterval *)op;
ND_TCHECK(opa->nd_opt_adv_interval);
ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval)));
break;
case ND_OPT_HOMEAGENT_INFO:
oph = (const struct nd_opt_homeagent_info *)op;
ND_TCHECK(oph->nd_opt_hai_lifetime);
ND_PRINT((ndo," preference %u, lifetime %u",
EXTRACT_16BITS(&oph->nd_opt_hai_preference),
EXTRACT_16BITS(&oph->nd_opt_hai_lifetime)));
break;
case ND_OPT_ROUTE_INFO:
opri = (const struct nd_opt_route_info *)op;
ND_TCHECK(opri->nd_opt_rti_lifetime);
memset(&in6, 0, sizeof(in6));
in6p = (const struct in6_addr *)(opri + 1);
switch (op->nd_opt_len) {
case 1:
break;
case 2:
ND_TCHECK2(*in6p, 8);
memcpy(&in6, opri + 1, 8);
break;
case 3:
ND_TCHECK(*in6p);
memcpy(&in6, opri + 1, sizeof(in6));
break;
default:
goto trunc;
}
ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6),
opri->nd_opt_rti_prefixlen));
ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags)));
ND_PRINT((ndo,", lifetime=%s",
get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime))));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
return;
}
break;
}
/* do we want to see an additional hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
cp += op->nd_opt_len << 3;
resid -= op->nd_opt_len << 3;
}
return;
trunc:
ND_PRINT((ndo, "[ndp opt]"));
return;
#undef ECHECK
}
static void
mld6_print(netdissect_options *ndo, const u_char *bp)
{
const struct mld6_hdr *mp = (const struct mld6_hdr *)bp;
const u_char *ep;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if ((const u_char *)mp + sizeof(*mp) > ep)
return;
ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay)));
ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr)));
}
static void
mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
dnsname_print(netdissect_options *ndo, const u_char *cp, const u_char *ep)
{
int i;
/* DNS name decoding - no decompression */
ND_PRINT((ndo,", \""));
while (cp < ep) {
i = *cp++;
if (i) {
if (i > ep - cp) {
ND_PRINT((ndo,"???"));
break;
}
while (i-- && cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
if (cp + 1 < ep && *cp)
ND_PRINT((ndo,"."));
} else {
if (cp == ep) {
/* FQDN */
ND_PRINT((ndo,"."));
} else if (cp + 1 == ep && *cp == '\0') {
/* truncated */
} else {
/* invalid */
ND_PRINT((ndo,"???"));
}
break;
}
}
ND_PRINT((ndo,"\""));
}
static void
icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static void
icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2696_0 |
crossvul-cpp_data_bad_5094_0 |
/* $Id: fpm_status.c 312262 2011-06-18 17:41:56Z felipe $ */
/* (c) 2009 Jerome Loyet */
#include "php.h"
#include "SAPI.h"
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#ifdef HAVE_TIMES
#include <sys/times.h>
#endif
#include "fpm_config.h"
#include "fpm_log.h"
#include "fpm_clock.h"
#include "fpm_process_ctl.h"
#include "fpm_signals.h"
#include "fpm_scoreboard.h"
#include "fastcgi.h"
#include "zlog.h"
#ifdef MAX_LINE_LENGTH
# define FPM_LOG_BUFFER MAX_LINE_LENGTH
#else
# define FPM_LOG_BUFFER 1024
#endif
static char *fpm_log_format = NULL;
static int fpm_log_fd = -1;
int fpm_log_open(int reopen) /* {{{ */
{
struct fpm_worker_pool_s *wp;
int ret = 1;
int fd;
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
if (!wp->config->access_log) {
continue;
}
ret = 0;
fd = open(wp->config->access_log, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
if (0 > fd) {
zlog(ZLOG_SYSERROR, "failed to open access log (%s)", wp->config->access_log);
return -1;
} else {
zlog(ZLOG_DEBUG, "open access log (%s)", wp->config->access_log);
}
if (reopen) {
dup2(fd, wp->log_fd);
close(fd);
fd = wp->log_fd;
fpm_pctl_kill_all(SIGQUIT);
} else {
wp->log_fd = fd;
}
if (0 > fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC)) {
zlog(ZLOG_WARNING, "failed to change attribute of access_log");
}
}
return ret;
}
/* }}} */
/* }}} */
int fpm_log_init_child(struct fpm_worker_pool_s *wp) /* {{{ */
{
if (!wp || !wp->config) {
return -1;
}
if (wp->config->access_log && *wp->config->access_log) {
if (wp->config->access_format) {
fpm_log_format = strdup(wp->config->access_format);
}
}
if (fpm_log_fd == -1) {
fpm_log_fd = wp->log_fd;
}
for (wp = fpm_worker_all_pools; wp; wp = wp->next) {
if (wp->log_fd > -1 && wp->log_fd != fpm_log_fd) {
close(wp->log_fd);
wp->log_fd = -1;
}
}
return 0;
}
/* }}} */
int fpm_log_write(char *log_format) /* {{{ */
{
char *s, *b;
char buffer[FPM_LOG_BUFFER+1];
int token, test;
size_t len, len2;
struct fpm_scoreboard_proc_s proc, *proc_p;
struct fpm_scoreboard_s *scoreboard;
char tmp[129];
char format[129];
time_t now_epoch;
#ifdef HAVE_TIMES
clock_t tms_total;
#endif
if (!log_format && (!fpm_log_format || fpm_log_fd == -1)) {
return -1;
}
if (!log_format) {
log_format = fpm_log_format;
test = 0;
} else {
test = 1;
}
now_epoch = time(NULL);
if (!test) {
scoreboard = fpm_scoreboard_get();
if (!scoreboard) {
zlog(ZLOG_WARNING, "unable to get scoreboard while preparing the access log");
return -1;
}
proc_p = fpm_scoreboard_proc_acquire(NULL, -1, 0);
if (!proc_p) {
zlog(ZLOG_WARNING, "[pool %s] Unable to acquire shm slot while preparing the access log", scoreboard->pool);
return -1;
}
proc = *proc_p;
fpm_scoreboard_proc_release(proc_p);
}
token = 0;
memset(buffer, '\0', sizeof(buffer));
b = buffer;
len = 0;
s = log_format;
while (*s != '\0') {
/* Test is we have place for 1 more char. */
if (len >= FPM_LOG_BUFFER) {
zlog(ZLOG_NOTICE, "the log buffer is full (%d). The access log request has been truncated.", FPM_LOG_BUFFER);
len = FPM_LOG_BUFFER;
break;
}
if (!token && *s == '%') {
token = 1;
memset(format, '\0', sizeof(format)); /* reset format */
s++;
continue;
}
if (token) {
token = 0;
len2 = 0;
switch (*s) {
case '%': /* '%' */
*b = '%';
len2 = 1;
break;
#ifdef HAVE_TIMES
case 'C': /* %CPU */
if (format[0] == '\0' || !strcasecmp(format, "total")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cutime + proc.last_request_cpu.tms_cstime;
}
} else if (!strcasecmp(format, "user")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_utime + proc.last_request_cpu.tms_cutime;
}
} else if (!strcasecmp(format, "system")) {
if (!test) {
tms_total = proc.last_request_cpu.tms_stime + proc.last_request_cpu.tms_cstime;
}
} else {
zlog(ZLOG_WARNING, "only 'total', 'user' or 'system' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.2f", tms_total / fpm_scoreboard_get_tick() / (proc.cpu_duration.tv_sec + proc.cpu_duration.tv_usec / 1000000.) * 100.);
}
break;
#endif
case 'd': /* duration µs */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "seconds")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec + proc.duration.tv_usec / 1000000.);
}
/* miliseconds */
} else if (!strcasecmp(format, "miliseconds") || !strcasecmp(format, "mili")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%.3f", proc.duration.tv_sec * 1000. + proc.duration.tv_usec / 1000.);
}
/* microseconds */
} else if (!strcasecmp(format, "microseconds") || !strcasecmp(format, "micro")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.duration.tv_sec * 1000000UL + proc.duration.tv_usec);
}
} else {
zlog(ZLOG_WARNING, "only 'seconds', 'mili', 'miliseconds', 'micro' or 'microseconds' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'e': /* fastcgi env */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the environment variable must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
char *env = fcgi_getenv((fcgi_request*) SG(server_context), format, strlen(format));
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", env ? env : "-");
}
format[0] = '\0';
break;
case 'f': /* script */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.script_filename ? proc.script_filename : "-");
}
break;
case 'l': /* content length */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.content_length);
}
break;
case 'm': /* method */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.request_method ? proc.request_method : "-");
}
break;
case 'M': /* memory */
/* seconds */
if (format[0] == '\0' || !strcasecmp(format, "bytes")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%zu", proc.memory);
}
/* kilobytes */
} else if (!strcasecmp(format, "kilobytes") || !strcasecmp(format, "kilo")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024);
}
/* megabytes */
} else if (!strcasecmp(format, "megabytes") || !strcasecmp(format, "mega")) {
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%lu", proc.memory / 1024 / 1024);
}
} else {
zlog(ZLOG_WARNING, "only 'bytes', 'kilo', 'kilobytes', 'mega' or 'megabytes' are allowed as a modifier for %%%c ('%s')", *s, format);
return -1;
}
format[0] = '\0';
break;
case 'n': /* pool name */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", scoreboard->pool[0] ? scoreboard->pool : "-");
}
break;
case 'o': /* header output */
if (format[0] == '\0') {
zlog(ZLOG_WARNING, "the name of the header must be set between embraces for %%%c", *s);
return -1;
}
if (!test) {
sapi_header_struct *h;
zend_llist_position pos;
sapi_headers_struct *sapi_headers = &SG(sapi_headers);
size_t format_len = strlen(format);
h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
while (h) {
char *header;
if (!h->header_len) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (!strstr(h->header, format)) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
/* test if enought char after the header name + ': ' */
if (h->header_len <= format_len + 2) {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
if (h->header[format_len] != ':' || h->header[format_len + 1] != ' ') {
h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
continue;
}
header = h->header + format_len + 2;
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", header && *header ? header : "-");
/* found, done */
break;
}
if (!len2) {
len2 = 1;
*b = '-';
}
}
format[0] = '\0';
break;
case 'p': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getpid());
}
break;
case 'P': /* PID */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%ld", (long)getppid());
}
break;
case 'q': /* query_string */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.query_string);
}
break;
case 'Q': /* '?' */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", *proc.query_string ? "?" : "");
}
break;
case 'r': /* request URI */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.request_uri);
}
break;
case 'R': /* remote IP address */
if (!test) {
const char *tmp = fcgi_get_last_client_ip();
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp ? tmp : "-");
}
break;
case 's': /* status */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%d", SG(sapi_headers).http_response_code);
}
break;
case 'T':
case 't': /* time */
if (!test) {
time_t *t;
if (*s == 't') {
t = &proc.accepted_epoch;
} else {
t = &now_epoch;
}
if (format[0] == '\0') {
strftime(tmp, sizeof(tmp) - 1, "%d/%b/%Y:%H:%M:%S %z", localtime(t));
} else {
strftime(tmp, sizeof(tmp) - 1, format, localtime(t));
}
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", tmp);
}
format[0] = '\0';
break;
case 'u': /* remote user */
if (!test) {
len2 = snprintf(b, FPM_LOG_BUFFER - len, "%s", proc.auth_user);
}
break;
case '{': /* complex var */
token = 1;
{
char *start;
size_t l;
start = ++s;
while (*s != '\0') {
if (*s == '}') {
l = s - start;
if (l >= sizeof(format) - 1) {
l = sizeof(format) - 1;
}
memcpy(format, start, l);
format[l] = '\0';
break;
}
s++;
}
if (s[1] == '\0') {
zlog(ZLOG_WARNING, "missing closing embrace in the access.format");
return -1;
}
}
break;
default:
zlog(ZLOG_WARNING, "Invalid token in the access.format (%%%c)", *s);
return -1;
}
if (*s != '}' && format[0] != '\0') {
zlog(ZLOG_WARNING, "embrace is not allowed for modifier %%%c", *s);
return -1;
}
s++;
if (!test) {
b += len2;
len += len2;
}
continue;
}
if (!test) {
// push the normal char to the output buffer
*b = *s;
b++;
len++;
}
s++;
}
if (!test && strlen(buffer) > 0) {
buffer[len] = '\n';
write(fpm_log_fd, buffer, len + 1);
}
return 0;
}
/* }}} */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5094_0 |
crossvul-cpp_data_bad_2644_8 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996, 1997
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Code by Matt Thomas, Digital Equipment Corporation
* with an awful lot of hacking by Jeffrey Mogul, DECWRL
*/
/* \summary: IEEE 802.2 LLC printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "llc.h"
#include "ethertype.h"
#include "oui.h"
static const struct tok llc_values[] = {
{ LLCSAP_NULL, "Null" },
{ LLCSAP_GLOBAL, "Global" },
{ LLCSAP_8021B_I, "802.1B I" },
{ LLCSAP_8021B_G, "802.1B G" },
{ LLCSAP_IP, "IP" },
{ LLCSAP_SNA, "SNA" },
{ LLCSAP_PROWAYNM, "ProWay NM" },
{ LLCSAP_8021D, "STP" },
{ LLCSAP_RS511, "RS511" },
{ LLCSAP_ISO8208, "ISO8208" },
{ LLCSAP_PROWAY, "ProWay" },
{ LLCSAP_SNAP, "SNAP" },
{ LLCSAP_IPX, "IPX" },
{ LLCSAP_NETBEUI, "NetBeui" },
{ LLCSAP_ISONS, "OSI" },
{ 0, NULL },
};
static const struct tok llc_cmd_values[] = {
{ LLC_UI, "ui" },
{ LLC_TEST, "test" },
{ LLC_XID, "xid" },
{ LLC_UA, "ua" },
{ LLC_DISC, "disc" },
{ LLC_DM, "dm" },
{ LLC_SABME, "sabme" },
{ LLC_FRMR, "frmr" },
{ 0, NULL }
};
static const struct tok llc_flag_values[] = {
{ 0, "Command" },
{ LLC_GSAP, "Response" },
{ LLC_U_POLL, "Poll" },
{ LLC_GSAP|LLC_U_POLL, "Final" },
{ LLC_IS_POLL, "Poll" },
{ LLC_GSAP|LLC_IS_POLL, "Final" },
{ 0, NULL }
};
static const struct tok llc_ig_flag_values[] = {
{ 0, "Individual" },
{ LLC_IG, "Group" },
{ 0, NULL }
};
static const struct tok llc_supervisory_values[] = {
{ 0, "Receiver Ready" },
{ 1, "Receiver not Ready" },
{ 2, "Reject" },
{ 0, NULL }
};
static const struct tok cisco_values[] = {
{ PID_CISCO_CDP, "CDP" },
{ PID_CISCO_VTP, "VTP" },
{ PID_CISCO_DTP, "DTP" },
{ PID_CISCO_UDLD, "UDLD" },
{ PID_CISCO_PVST, "PVST" },
{ PID_CISCO_VLANBRIDGE, "VLAN Bridge" },
{ 0, NULL }
};
static const struct tok bridged_values[] = {
{ PID_RFC2684_ETH_FCS, "Ethernet + FCS" },
{ PID_RFC2684_ETH_NOFCS, "Ethernet w/o FCS" },
{ PID_RFC2684_802_4_FCS, "802.4 + FCS" },
{ PID_RFC2684_802_4_NOFCS, "802.4 w/o FCS" },
{ PID_RFC2684_802_5_FCS, "Token Ring + FCS" },
{ PID_RFC2684_802_5_NOFCS, "Token Ring w/o FCS" },
{ PID_RFC2684_FDDI_FCS, "FDDI + FCS" },
{ PID_RFC2684_FDDI_NOFCS, "FDDI w/o FCS" },
{ PID_RFC2684_802_6_FCS, "802.6 + FCS" },
{ PID_RFC2684_802_6_NOFCS, "802.6 w/o FCS" },
{ PID_RFC2684_BPDU, "BPDU" },
{ 0, NULL },
};
static const struct tok null_values[] = {
{ 0, NULL }
};
struct oui_tok {
uint32_t oui;
const struct tok *tok;
};
static const struct oui_tok oui_to_tok[] = {
{ OUI_ENCAP_ETHER, ethertype_values },
{ OUI_CISCO_90, ethertype_values }, /* uses some Ethertype values */
{ OUI_APPLETALK, ethertype_values }, /* uses some Ethertype values */
{ OUI_CISCO, cisco_values },
{ OUI_RFC2684, bridged_values }, /* bridged, RFC 2427 FR or RFC 2864 ATM */
{ 0, NULL }
};
/*
* If we printed information about the payload, returns the length of the LLC
* header, plus the length of any SNAP header following it.
*
* Otherwise (for example, if the packet has unknown SAPs or has a SNAP
* header with an unknown OUI/PID combination), returns the *negative*
* of that value.
*/
int
llc_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen,
const struct lladdr_info *src, const struct lladdr_info *dst)
{
uint8_t dsap_field, dsap, ssap_field, ssap;
uint16_t control;
int hdrlen;
int is_u;
if (caplen < 3) {
ND_PRINT((ndo, "[|llc]"));
ND_DEFAULTPRINT((const u_char *)p, caplen);
return (caplen);
}
if (length < 3) {
ND_PRINT((ndo, "[|llc]"));
ND_DEFAULTPRINT((const u_char *)p, caplen);
return (length);
}
dsap_field = *p;
ssap_field = *(p + 1);
/*
* OK, what type of LLC frame is this? The length
* of the control field depends on that - I frames
* have a two-byte control field, and U frames have
* a one-byte control field.
*/
control = *(p + 2);
if ((control & LLC_U_FMT) == LLC_U_FMT) {
/*
* U frame.
*/
is_u = 1;
hdrlen = 3; /* DSAP, SSAP, 1-byte control field */
} else {
/*
* The control field in I and S frames is
* 2 bytes...
*/
if (caplen < 4) {
ND_PRINT((ndo, "[|llc]"));
ND_DEFAULTPRINT((const u_char *)p, caplen);
return (caplen);
}
if (length < 4) {
ND_PRINT((ndo, "[|llc]"));
ND_DEFAULTPRINT((const u_char *)p, caplen);
return (length);
}
/*
* ...and is little-endian.
*/
control = EXTRACT_LE_16BITS(p + 2);
is_u = 0;
hdrlen = 4; /* DSAP, SSAP, 2-byte control field */
}
if (ssap_field == LLCSAP_GLOBAL && dsap_field == LLCSAP_GLOBAL) {
/*
* This is an Ethernet_802.3 IPX frame; it has an
* 802.3 header (i.e., an Ethernet header where the
* type/length field is <= ETHERMTU, i.e. it's a length
* field, not a type field), but has no 802.2 header -
* the IPX packet starts right after the Ethernet header,
* with a signature of two bytes of 0xFF (which is
* LLCSAP_GLOBAL).
*
* (It might also have been an Ethernet_802.3 IPX at
* one time, but got bridged onto another network,
* such as an 802.11 network; this has appeared in at
* least one capture file.)
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "IPX 802.3: "));
ipx_print(ndo, p, length);
return (0); /* no LLC header */
}
dsap = dsap_field & ~LLC_IG;
ssap = ssap_field & ~LLC_GSAP;
if (ndo->ndo_eflag) {
ND_PRINT((ndo, "LLC, dsap %s (0x%02x) %s, ssap %s (0x%02x) %s",
tok2str(llc_values, "Unknown", dsap),
dsap,
tok2str(llc_ig_flag_values, "Unknown", dsap_field & LLC_IG),
tok2str(llc_values, "Unknown", ssap),
ssap,
tok2str(llc_flag_values, "Unknown", ssap_field & LLC_GSAP)));
if (is_u) {
ND_PRINT((ndo, ", ctrl 0x%02x: ", control));
} else {
ND_PRINT((ndo, ", ctrl 0x%04x: ", control));
}
}
/*
* Skip LLC header.
*/
p += hdrlen;
length -= hdrlen;
caplen -= hdrlen;
if (ssap == LLCSAP_SNAP && dsap == LLCSAP_SNAP
&& control == LLC_UI) {
/*
* XXX - what *is* the right bridge pad value here?
* Does anybody ever bridge one form of LAN traffic
* over a networking type that uses 802.2 LLC?
*/
if (!snap_print(ndo, p, length, caplen, src, dst, 2)) {
/*
* Unknown packet type; tell our caller, by
* returning a negative value, so they
* can print the raw packet.
*/
return (-(hdrlen + 5)); /* include LLC and SNAP header */
} else
return (hdrlen + 5); /* include LLC and SNAP header */
}
if (ssap == LLCSAP_8021D && dsap == LLCSAP_8021D &&
control == LLC_UI) {
stp_print(ndo, p, length);
return (hdrlen);
}
if (ssap == LLCSAP_IP && dsap == LLCSAP_IP &&
control == LLC_UI) {
/*
* This is an RFC 948-style IP packet, with
* an 802.3 header and an 802.2 LLC header
* with the source and destination SAPs being
* the IP SAP.
*/
ip_print(ndo, p, length);
return (hdrlen);
}
if (ssap == LLCSAP_IPX && dsap == LLCSAP_IPX &&
control == LLC_UI) {
/*
* This is an Ethernet_802.2 IPX frame, with an 802.3
* header and an 802.2 LLC header with the source and
* destination SAPs being the IPX SAP.
*/
if (ndo->ndo_eflag)
ND_PRINT((ndo, "IPX 802.2: "));
ipx_print(ndo, p, length);
return (hdrlen);
}
#ifdef ENABLE_SMB
if (ssap == LLCSAP_NETBEUI && dsap == LLCSAP_NETBEUI
&& (!(control & LLC_S_FMT) || control == LLC_U_FMT)) {
/*
* we don't actually have a full netbeui parser yet, but the
* smb parser can handle many smb-in-netbeui packets, which
* is very useful, so we call that
*
* We don't call it for S frames, however, just I frames
* (which are frames that don't have the low-order bit,
* LLC_S_FMT, set in the first byte of the control field)
* and UI frames (whose control field is just 3, LLC_U_FMT).
*/
netbeui_print(ndo, control, p, length);
return (hdrlen);
}
#endif
if (ssap == LLCSAP_ISONS && dsap == LLCSAP_ISONS
&& control == LLC_UI) {
isoclns_print(ndo, p, length, caplen);
return (hdrlen);
}
if (!ndo->ndo_eflag) {
if (ssap == dsap) {
if (src == NULL || dst == NULL)
ND_PRINT((ndo, "%s ", tok2str(llc_values, "Unknown DSAP 0x%02x", dsap)));
else
ND_PRINT((ndo, "%s > %s %s ",
(src->addr_string)(ndo, src->addr),
(dst->addr_string)(ndo, dst->addr),
tok2str(llc_values, "Unknown DSAP 0x%02x", dsap)));
} else {
if (src == NULL || dst == NULL)
ND_PRINT((ndo, "%s > %s ",
tok2str(llc_values, "Unknown SSAP 0x%02x", ssap),
tok2str(llc_values, "Unknown DSAP 0x%02x", dsap)));
else
ND_PRINT((ndo, "%s %s > %s %s ",
(src->addr_string)(ndo, src->addr),
tok2str(llc_values, "Unknown SSAP 0x%02x", ssap),
(dst->addr_string)(ndo, dst->addr),
tok2str(llc_values, "Unknown DSAP 0x%02x", dsap)));
}
}
if (is_u) {
ND_PRINT((ndo, "Unnumbered, %s, Flags [%s], length %u",
tok2str(llc_cmd_values, "%02x", LLC_U_CMD(control)),
tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_U_POLL)),
length + hdrlen));
if ((control & ~LLC_U_POLL) == LLC_XID) {
if (length == 0) {
/*
* XID with no payload.
* This could, for example, be an SNA
* "short form" XID.
*/
return (hdrlen);
}
if (caplen < 1) {
ND_PRINT((ndo, "[|llc]"));
if (caplen > 0)
ND_DEFAULTPRINT((const u_char *)p, caplen);
return (hdrlen);
}
if (*p == LLC_XID_FI) {
if (caplen < 3 || length < 3) {
ND_PRINT((ndo, "[|llc]"));
if (caplen > 0)
ND_DEFAULTPRINT((const u_char *)p, caplen);
} else
ND_PRINT((ndo, ": %02x %02x", p[1], p[2]));
return (hdrlen);
}
}
} else {
if ((control & LLC_S_FMT) == LLC_S_FMT) {
ND_PRINT((ndo, "Supervisory, %s, rcv seq %u, Flags [%s], length %u",
tok2str(llc_supervisory_values,"?",LLC_S_CMD(control)),
LLC_IS_NR(control),
tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)),
length + hdrlen));
return (hdrlen); /* no payload to print */
} else {
ND_PRINT((ndo, "Information, send seq %u, rcv seq %u, Flags [%s], length %u",
LLC_I_NS(control),
LLC_IS_NR(control),
tok2str(llc_flag_values,"?",(ssap_field & LLC_GSAP) | (control & LLC_IS_POLL)),
length + hdrlen));
}
}
return (-hdrlen);
}
static const struct tok *
oui_to_struct_tok(uint32_t orgcode)
{
const struct tok *tok = null_values;
const struct oui_tok *otp;
for (otp = &oui_to_tok[0]; otp->tok != NULL; otp++) {
if (otp->oui == orgcode) {
tok = otp->tok;
break;
}
}
return (tok);
}
int
snap_print(netdissect_options *ndo, const u_char *p, u_int length, u_int caplen,
const struct lladdr_info *src, const struct lladdr_info *dst,
u_int bridge_pad)
{
uint32_t orgcode;
register u_short et;
register int ret;
ND_TCHECK2(*p, 5);
if (caplen < 5 || length < 5)
goto trunc;
orgcode = EXTRACT_24BITS(p);
et = EXTRACT_16BITS(p + 3);
if (ndo->ndo_eflag) {
/*
* Somebody's already printed the MAC addresses, if there
* are any, so just print the SNAP header, not the MAC
* addresses.
*/
ND_PRINT((ndo, "oui %s (0x%06x), %s %s (0x%04x), length %u: ",
tok2str(oui_values, "Unknown", orgcode),
orgcode,
(orgcode == 0x000000 ? "ethertype" : "pid"),
tok2str(oui_to_struct_tok(orgcode), "Unknown", et),
et, length - 5));
}
p += 5;
length -= 5;
caplen -= 5;
switch (orgcode) {
case OUI_ENCAP_ETHER:
case OUI_CISCO_90:
/*
* This is an encapsulated Ethernet packet,
* or a packet bridged by some piece of
* Cisco hardware; the protocol ID is
* an Ethernet protocol type.
*/
ret = ethertype_print(ndo, et, p, length, caplen, src, dst);
if (ret)
return (ret);
break;
case OUI_APPLETALK:
if (et == ETHERTYPE_ATALK) {
/*
* No, I have no idea why Apple used one
* of their own OUIs, rather than
* 0x000000, and an Ethernet packet
* type, for Appletalk data packets,
* but used 0x000000 and an Ethernet
* packet type for AARP packets.
*/
ret = ethertype_print(ndo, et, p, length, caplen, src, dst);
if (ret)
return (ret);
}
break;
case OUI_CISCO:
switch (et) {
case PID_CISCO_CDP:
cdp_print(ndo, p, length, caplen);
return (1);
case PID_CISCO_DTP:
dtp_print(ndo, p, length);
return (1);
case PID_CISCO_UDLD:
udld_print(ndo, p, length);
return (1);
case PID_CISCO_VTP:
vtp_print(ndo, p, length);
return (1);
case PID_CISCO_PVST:
case PID_CISCO_VLANBRIDGE:
stp_print(ndo, p, length);
return (1);
default:
break;
}
break;
case OUI_RFC2684:
switch (et) {
case PID_RFC2684_ETH_FCS:
case PID_RFC2684_ETH_NOFCS:
/*
* XXX - remove the last two bytes for
* PID_RFC2684_ETH_FCS?
*/
/*
* Skip the padding.
*/
ND_TCHECK2(*p, bridge_pad);
caplen -= bridge_pad;
length -= bridge_pad;
p += bridge_pad;
/*
* What remains is an Ethernet packet.
*/
ether_print(ndo, p, length, caplen, NULL, NULL);
return (1);
case PID_RFC2684_802_5_FCS:
case PID_RFC2684_802_5_NOFCS:
/*
* XXX - remove the last two bytes for
* PID_RFC2684_ETH_FCS?
*/
/*
* Skip the padding, but not the Access
* Control field.
*/
ND_TCHECK2(*p, bridge_pad);
caplen -= bridge_pad;
length -= bridge_pad;
p += bridge_pad;
/*
* What remains is an 802.5 Token Ring
* packet.
*/
token_print(ndo, p, length, caplen);
return (1);
case PID_RFC2684_FDDI_FCS:
case PID_RFC2684_FDDI_NOFCS:
/*
* XXX - remove the last two bytes for
* PID_RFC2684_ETH_FCS?
*/
/*
* Skip the padding.
*/
ND_TCHECK2(*p, bridge_pad + 1);
caplen -= bridge_pad + 1;
length -= bridge_pad + 1;
p += bridge_pad + 1;
/*
* What remains is an FDDI packet.
*/
fddi_print(ndo, p, length, caplen);
return (1);
case PID_RFC2684_BPDU:
stp_print(ndo, p, length);
return (1);
}
}
if (!ndo->ndo_eflag) {
/*
* Nobody printed the link-layer addresses, so print them, if
* we have any.
*/
if (src != NULL && dst != NULL) {
ND_PRINT((ndo, "%s > %s ",
(src->addr_string)(ndo, src->addr),
(dst->addr_string)(ndo, dst->addr)));
}
/*
* Print the SNAP header, but if the OUI is 000000, don't
* bother printing it, and report the PID as being an
* ethertype.
*/
if (orgcode == 0x000000) {
ND_PRINT((ndo, "SNAP, ethertype %s (0x%04x), length %u: ",
tok2str(ethertype_values, "Unknown", et),
et, length));
} else {
ND_PRINT((ndo, "SNAP, oui %s (0x%06x), pid %s (0x%04x), length %u: ",
tok2str(oui_values, "Unknown", orgcode),
orgcode,
tok2str(oui_to_struct_tok(orgcode), "Unknown", et),
et, length));
}
}
return (0);
trunc:
ND_PRINT((ndo, "[|snap]"));
return (1);
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2644_8 |
crossvul-cpp_data_good_2711_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (snpal == 6)
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal)));
if (netal != 0)
ND_PRINT((ndo, "\n\t NET (length: %u) %s",
netal,
isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*pptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
return;
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN)
goto trunc;
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN;
len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
if (stlv_len < 8)
goto trunc;
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
int sysid_len;
sysid_len = SYSTEM_ID_LEN;
if (sysid_len > id_len)
sysid_len = id_len;
for (i = 1; i <= sysid_len; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2711_0 |
crossvul-cpp_data_good_925_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD %
% T H H R R E SS H H O O L D D %
% T HHHHH RRRR EEE SSS HHHHH O O L D D %
% T H H R R E SS H H O O L D D %
% T H H R R EEEEE SSSSS H H OOO LLLLL DDDD %
% %
% %
% MagickCore Image Threshold Methods %
% %
% Software Design %
% Cristy %
% October 1996 %
% %
% %
% Copyright 1999-2019 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 %
% %
% https://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 "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/configure.h"
#include "MagickCore/constitute.h"
#include "MagickCore/decorate.h"
#include "MagickCore/draw.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/effect.h"
#include "MagickCore/fx.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/montage.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantize.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/random_.h"
#include "MagickCore/random-private.h"
#include "MagickCore/resize.h"
#include "MagickCore/resource_.h"
#include "MagickCore/segment.h"
#include "MagickCore/shear.h"
#include "MagickCore/signature-private.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/threshold.h"
#include "MagickCore/token.h"
#include "MagickCore/transform.h"
#include "MagickCore/xml-tree.h"
#include "MagickCore/xml-tree-private.h"
/*
Define declarations.
*/
#define ThresholdsFilename "thresholds.xml"
/*
Typedef declarations.
*/
struct _ThresholdMap
{
char
*map_id,
*description;
size_t
width,
height;
ssize_t
divisor,
*levels;
};
/*
Static declarations.
*/
static const char
*MinimalThresholdMap =
"<?xml version=\"1.0\"?>"
"<thresholds>"
" <threshold map=\"threshold\" alias=\"1x1\">"
" <description>Threshold 1x1 (non-dither)</description>"
" <levels width=\"1\" height=\"1\" divisor=\"2\">"
" 1"
" </levels>"
" </threshold>"
" <threshold map=\"checks\" alias=\"2x1\">"
" <description>Checkerboard 2x1 (dither)</description>"
" <levels width=\"2\" height=\"2\" divisor=\"3\">"
" 1 2"
" 2 1"
" </levels>"
" </threshold>"
"</thresholds>";
/*
Forward declarations.
*/
static ThresholdMap
*GetThresholdMapFile(const char *,const char *,const char *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveThresholdImage() selects an individual threshold for each pixel
% based on the range of intensity values in its local neighborhood. This
% allows for thresholding of an image whose global intensity histogram
% doesn't contain distinctive peaks.
%
% The format of the AdaptiveThresholdImage method is:
%
% Image *AdaptiveThresholdImage(const Image *image,const size_t width,
% const size_t height,const double bias,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o width: the width of the local neighborhood.
%
% o height: the height of the local neighborhood.
%
% o bias: the mean bias.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveThresholdImage(const Image *image,
const size_t width,const size_t height,const double bias,
ExceptionInfo *exception)
{
#define AdaptiveThresholdImageTag "AdaptiveThreshold/Image"
CacheView
*image_view,
*threshold_view;
Image
*threshold_image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickSizeType
number_pixels;
ssize_t
y;
/*
Initialize threshold image attributes.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
threshold_image=CloneImage(image,0,0,MagickTrue,exception);
if (threshold_image == (Image *) NULL)
return((Image *) NULL);
if ((width == 0) || (height == 0))
return(threshold_image);
status=SetImageStorageClass(threshold_image,DirectClass,exception);
if (status == MagickFalse)
{
threshold_image=DestroyImage(threshold_image);
return((Image *) NULL);
}
/*
Threshold image.
*/
status=MagickTrue;
progress=0;
number_pixels=(MagickSizeType) width*height;
image_view=AcquireVirtualCacheView(image,exception);
threshold_view=AcquireAuthenticCacheView(threshold_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,threshold_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
double
channel_bias[MaxPixelChannels],
channel_sum[MaxPixelChannels];
register const Quantum
*magick_restrict p,
*magick_restrict pixels;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
center,
u,
v;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(height/2L),image->columns+width,height,exception);
q=QueueCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
center=(ssize_t) GetPixelChannels(image)*(image->columns+width)*(height/2L)+
GetPixelChannels(image)*(width/2);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
pixels=p;
channel_bias[channel]=0.0;
channel_sum[channel]=0.0;
for (v=0; v < (ssize_t) height; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
if (u == (ssize_t) (width-1))
channel_bias[channel]+=pixels[i];
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image);
}
pixels+=GetPixelChannels(image)*image->columns;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
mean;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
PixelTrait threshold_traits=GetPixelChannelTraits(threshold_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(threshold_traits == UndefinedPixelTrait))
continue;
if ((threshold_traits & CopyPixelTrait) != 0)
{
SetPixelChannel(threshold_image,channel,p[center+i],q);
continue;
}
channel_sum[channel]-=channel_bias[channel];
channel_bias[channel]=0.0;
pixels=p;
for (v=0; v < (ssize_t) height; v++)
{
channel_bias[channel]+=pixels[i];
pixels+=(width-1)*GetPixelChannels(image);
channel_sum[channel]+=pixels[i];
pixels+=GetPixelChannels(image)*(image->columns+1);
}
mean=(double) (channel_sum[channel]/number_pixels+bias);
SetPixelChannel(threshold_image,channel,(Quantum) ((double)
p[center+i] <= mean ? 0 : QuantumRange),q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(threshold_image);
}
if (SyncCacheViewAuthenticPixels(threshold_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,AdaptiveThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
threshold_image->type=image->type;
threshold_view=DestroyCacheView(threshold_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
threshold_image=DestroyImage(threshold_image);
return(threshold_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoThresholdImage() automatically performs image thresholding
% dependent on which method you specify.
%
% The format of the AutoThresholdImage method is:
%
% MagickBooleanType AutoThresholdImage(Image *image,
% const AutoThresholdMethod method,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image to auto-threshold.
%
% o method: choose from Kapur, OTSU, or Triangle.
%
% o exception: return any errors or warnings in this structure.
%
*/
static double KapurThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
#define MaxIntensity 255
double
*black_entropy,
*cumulative_histogram,
entropy,
epsilon,
maximum_entropy,
*white_entropy;
register ssize_t
i,
j;
size_t
threshold;
/*
Compute optimal threshold from the entopy of the histogram.
*/
cumulative_histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*cumulative_histogram));
black_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*black_entropy));
white_entropy=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*white_entropy));
if ((cumulative_histogram == (double *) NULL) ||
(black_entropy == (double *) NULL) || (white_entropy == (double *) NULL))
{
if (white_entropy != (double *) NULL)
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
if (black_entropy != (double *) NULL)
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
if (cumulative_histogram != (double *) NULL)
cumulative_histogram=(double *)
RelinquishMagickMemory(cumulative_histogram);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Entropy for black and white parts of the histogram.
*/
cumulative_histogram[0]=histogram[0];
for (i=1; i <= MaxIntensity; i++)
cumulative_histogram[i]=cumulative_histogram[i-1]+histogram[i];
epsilon=MagickMinimumValue;
for (j=0; j <= MaxIntensity; j++)
{
/*
Black entropy.
*/
black_entropy[j]=0.0;
if (cumulative_histogram[j] > epsilon)
{
entropy=0.0;
for (i=0; i <= j; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/cumulative_histogram[j]*
log(histogram[i]/cumulative_histogram[j]);
black_entropy[j]=entropy;
}
/*
White entropy.
*/
white_entropy[j]=0.0;
if ((1.0-cumulative_histogram[j]) > epsilon)
{
entropy=0.0;
for (i=j+1; i <= MaxIntensity; i++)
if (histogram[i] > epsilon)
entropy-=histogram[i]/(1.0-cumulative_histogram[j])*
log(histogram[i]/(1.0-cumulative_histogram[j]));
white_entropy[j]=entropy;
}
}
/*
Find histogram bin with maximum entropy.
*/
maximum_entropy=black_entropy[0]+white_entropy[0];
threshold=0;
for (j=1; j <= MaxIntensity; j++)
if ((black_entropy[j]+white_entropy[j]) > maximum_entropy)
{
maximum_entropy=black_entropy[j]+white_entropy[j];
threshold=(size_t) j;
}
/*
Free resources.
*/
white_entropy=(double *) RelinquishMagickMemory(white_entropy);
black_entropy=(double *) RelinquishMagickMemory(black_entropy);
cumulative_histogram=(double *) RelinquishMagickMemory(cumulative_histogram);
return(100.0*threshold/MaxIntensity);
}
static double OTSUThreshold(const Image *image,const double *histogram,
ExceptionInfo *exception)
{
double
max_sigma,
*myu,
*omega,
*probability,
*sigma,
threshold;
register ssize_t
i;
/*
Compute optimal threshold from maximization of inter-class variance.
*/
myu=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*myu));
omega=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*omega));
probability=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*probability));
sigma=(double *) AcquireQuantumMemory(MaxIntensity+1UL,sizeof(*sigma));
if ((myu == (double *) NULL) || (omega == (double *) NULL) ||
(probability == (double *) NULL) || (sigma == (double *) NULL))
{
if (sigma != (double *) NULL)
sigma=(double *) RelinquishMagickMemory(sigma);
if (probability != (double *) NULL)
probability=(double *) RelinquishMagickMemory(probability);
if (omega != (double *) NULL)
omega=(double *) RelinquishMagickMemory(omega);
if (myu != (double *) NULL)
myu=(double *) RelinquishMagickMemory(myu);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(-1.0);
}
/*
Calculate probability density.
*/
for (i=0; i <= (ssize_t) MaxIntensity; i++)
probability[i]=histogram[i];
/*
Generate probability of graylevels and mean value for separation.
*/
omega[0]=probability[0];
myu[0]=0.0;
for (i=1; i <= (ssize_t) MaxIntensity; i++)
{
omega[i]=omega[i-1]+probability[i];
myu[i]=myu[i-1]+i*probability[i];
}
/*
Sigma maximization: inter-class variance and compute optimal threshold.
*/
threshold=0;
max_sigma=0.0;
for (i=0; i < (ssize_t) MaxIntensity; i++)
{
sigma[i]=0.0;
if ((omega[i] != 0.0) && (omega[i] != 1.0))
sigma[i]=pow(myu[MaxIntensity]*omega[i]-myu[i],2.0)/(omega[i]*(1.0-
omega[i]));
if (sigma[i] > max_sigma)
{
max_sigma=sigma[i];
threshold=(double) i;
}
}
/*
Free resources.
*/
myu=(double *) RelinquishMagickMemory(myu);
omega=(double *) RelinquishMagickMemory(omega);
probability=(double *) RelinquishMagickMemory(probability);
sigma=(double *) RelinquishMagickMemory(sigma);
return(100.0*threshold/MaxIntensity);
}
static double TriangleThreshold(const double *histogram)
{
double
a,
b,
c,
count,
distance,
inverse_ratio,
max_distance,
segment,
x1,
x2,
y1,
y2;
register ssize_t
i;
ssize_t
end,
max,
start,
threshold;
/*
Compute optimal threshold with triangle algorithm.
*/
start=0; /* find start bin, first bin not zero count */
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > 0.0)
{
start=i;
break;
}
end=0; /* find end bin, last bin not zero count */
for (i=(ssize_t) MaxIntensity; i >= 0; i--)
if (histogram[i] > 0.0)
{
end=i;
break;
}
max=0; /* find max bin, bin with largest count */
count=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
if (histogram[i] > count)
{
max=i;
count=histogram[i];
}
/*
Compute threshold at split point.
*/
x1=(double) max;
y1=histogram[max];
x2=(double) end;
if ((max-start) >= (end-max))
x2=(double) start;
y2=0.0;
a=y1-y2;
b=x2-x1;
c=(-1.0)*(a*x1+b*y1);
inverse_ratio=1.0/sqrt(a*a+b*b+c*c);
threshold=0;
max_distance=0.0;
if (x2 == (double) start)
for (i=start; i < max; i++)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment > 0.0))
{
threshold=i;
max_distance=distance;
}
}
else
for (i=end; i > max; i--)
{
segment=inverse_ratio*(a*i+b*histogram[i]+c);
distance=sqrt(segment*segment);
if ((distance > max_distance) && (segment < 0.0))
{
threshold=i;
max_distance=distance;
}
}
return(100.0*threshold/MaxIntensity);
}
MagickExport MagickBooleanType AutoThresholdImage(Image *image,
const AutoThresholdMethod method,ExceptionInfo *exception)
{
CacheView
*image_view;
char
property[MagickPathExtent];
double
gamma,
*histogram,
sum,
threshold;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
y;
/*
Form histogram.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
histogram=(double *) AcquireQuantumMemory(MaxIntensity+1UL,
sizeof(*histogram));
if (histogram == (double *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=MagickTrue;
(void) memset(histogram,0,(MaxIntensity+1UL)*sizeof(*histogram));
image_view=AcquireVirtualCacheView(image,exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register ssize_t
x;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
double intensity = GetPixelIntensity(image,p);
histogram[ScaleQuantumToChar(ClampToQuantum(intensity))]++;
p+=GetPixelChannels(image);
}
}
image_view=DestroyCacheView(image_view);
/*
Normalize histogram.
*/
sum=0.0;
for (i=0; i <= (ssize_t) MaxIntensity; i++)
sum+=histogram[i];
gamma=PerceptibleReciprocal(sum);
for (i=0; i <= (ssize_t) MaxIntensity; i++)
histogram[i]=gamma*histogram[i];
/*
Discover threshold from histogram.
*/
switch (method)
{
case KapurThresholdMethod:
{
threshold=KapurThreshold(image,histogram,exception);
break;
}
case OTSUThresholdMethod:
default:
{
threshold=OTSUThreshold(image,histogram,exception);
break;
}
case TriangleThresholdMethod:
{
threshold=TriangleThreshold(histogram);
break;
}
}
histogram=(double *) RelinquishMagickMemory(histogram);
if (threshold < 0.0)
status=MagickFalse;
if (status == MagickFalse)
return(MagickFalse);
/*
Threshold image.
*/
(void) FormatLocaleString(property,MagickPathExtent,"%g%%",threshold);
(void) SetImageProperty(image,"auto-threshold:threshold",property,exception);
return(BilevelImage(image,QuantumRange*threshold/100.0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B i l e v e l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BilevelImage() changes the value of individual pixels based on the
% intensity of each pixel channel. The result is a high-contrast image.
%
% More precisely each channel value of the image is 'thresholded' so that if
% it is equal to or less than the given value it is set to zero, while any
% value greater than that give is set to it maximum or QuantumRange.
%
% This function is what is used to implement the "-threshold" operator for
% the command line API.
%
% If the default channel setting is given the image is thresholded using just
% the gray 'intensity' of the image, rather than the individual channels.
%
% The format of the BilevelImage method is:
%
% MagickBooleanType BilevelImage(Image *image,const double threshold,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold values.
%
% o exception: return any errors or warnings in this structure.
%
% Aside: You can get the same results as operator using LevelImages()
% with the 'threshold' value for both the black_point and the white_point.
%
*/
MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold,
ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
/*
Bilevel threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
q[i]=(Quantum) (pixel <= threshold ? 0 : QuantumRange);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% B l a c k T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BlackThresholdImage() is like ThresholdImage() but forces all pixels below
% the threshold into black while leaving all pixels at or above the threshold
% unchanged.
%
% The format of the BlackThresholdImage method is:
%
% MagickBooleanType BlackThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType BlackThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel < GetPixelInfoChannel(&threshold,channel))
q[i]=(Quantum) 0;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l a m p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClampImage() set each pixel whose value is below zero to zero and any the
% pixel whose value is above the quantum range to the quantum range (e.g.
% 65535) otherwise the pixel value remains unchanged.
%
% The format of the ClampImage method is:
%
% MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ClampImage(Image *image,ExceptionInfo *exception)
{
#define ClampImageTag "Clamp/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) ClampPixel(q->red);
q->green=(double) ClampPixel(q->green);
q->blue=(double) ClampPixel(q->blue);
q->alpha=(double) ClampPixel(q->alpha);
q++;
}
return(SyncImage(image,exception));
}
/*
Clamp image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
q[i]=ClampPixel((MagickRealType) q[i]);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ClampImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyThresholdMap() de-allocate the given ThresholdMap
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *DestroyThresholdMap(Threshold *map)
%
% A description of each parameter follows.
%
% o map: Pointer to the Threshold map to destroy
%
*/
MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map)
{
assert(map != (ThresholdMap *) NULL);
if (map->map_id != (char *) NULL)
map->map_id=DestroyString(map->map_id);
if (map->description != (char *) NULL)
map->description=DestroyString(map->description);
if (map->levels != (ssize_t *) NULL)
map->levels=(ssize_t *) RelinquishMagickMemory(map->levels);
map=(ThresholdMap *) RelinquishMagickMemory(map);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t T h r e s h o l d M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMap() loads and searches one or more threshold map files for the
% map matching the given name or alias.
%
% The format of the GetThresholdMap method is:
%
% ThresholdMap *GetThresholdMap(const char *map_id,
% ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o map_id: ID of the map to look for.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport ThresholdMap *GetThresholdMap(const char *map_id,
ExceptionInfo *exception)
{
ThresholdMap
*map;
map=GetThresholdMapFile(MinimalThresholdMap,"built-in",map_id,exception);
if (map != (ThresholdMap *) NULL)
return(map);
#if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT)
{
const StringInfo
*option;
LinkedListInfo
*options;
options=GetConfigureOptions(ThresholdsFilename,exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
map=GetThresholdMapFile((const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),map_id,exception);
if (map != (ThresholdMap *) NULL)
break;
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
}
#endif
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetThresholdMapFile() look for a given threshold map name or alias in the
% given XML file data, and return the allocated the map when found.
%
% The format of the ListThresholdMaps method is:
%
% ThresholdMap *GetThresholdMap(const char *xml,const char *filename,
% const char *map_id,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o map_id: ID of the map to look for in XML list.
%
% o exception: return any errors or warnings in this structure.
%
*/
static ThresholdMap *GetThresholdMapFile(const char *xml,const char *filename,
const char *map_id,ExceptionInfo *exception)
{
char
*p;
const char
*attribute,
*content;
double
value;
register ssize_t
i;
ThresholdMap
*map;
XMLTreeInfo
*description,
*levels,
*threshold,
*thresholds;
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
map=(ThresholdMap *) NULL;
thresholds=NewXMLTree(xml,exception);
if (thresholds == (XMLTreeInfo *) NULL)
return(map);
for (threshold=GetXMLTreeChild(thresholds,"threshold");
threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
attribute=GetXMLTreeAttribute(threshold,"map");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
attribute=GetXMLTreeAttribute(threshold,"alias");
if ((attribute != (char *) NULL) && (LocaleCompare(map_id,attribute) == 0))
break;
}
if (threshold == (XMLTreeInfo *) NULL)
{
thresholds=DestroyXMLTree(thresholds);
return(map);
}
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
levels=GetXMLTreeChild(threshold,"levels");
if (levels == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<levels>, map \"%s\"", map_id);
thresholds=DestroyXMLTree(thresholds);
return(map);
}
map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map));
map->map_id=(char *) NULL;
map->description=(char *) NULL;
map->levels=(ssize_t *) NULL;
attribute=GetXMLTreeAttribute(threshold,"map");
if (attribute != (char *) NULL)
map->map_id=ConstantString(attribute);
content=GetXMLTreeContent(description);
if (content != (char *) NULL)
map->description=ConstantString(content);
attribute=GetXMLTreeAttribute(levels,"width");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->width=StringToUnsignedLong(attribute);
if (map->width == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels width>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"height");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->height=StringToUnsignedLong(attribute);
if (map->height == 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels height>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
attribute=GetXMLTreeAttribute(levels,"divisor");
if (attribute == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->divisor=(ssize_t) StringToLong(attribute);
if (map->divisor < 2)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidAttribute", "<levels divisor>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=GetXMLTreeContent(levels);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<levels>, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height*
sizeof(*map->levels));
if (map->levels == (ssize_t *) NULL)
ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap");
for (i=0; i < (ssize_t) (map->width*map->height); i++)
{
map->levels[i]=(ssize_t) strtol(content,&p,10);
if (p == content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too few values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
if ((map->levels[i] < 0) || (map->levels[i] > map->divisor))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> %.20g out of range, map \"%s\"",
(double) map->levels[i],map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
content=p;
}
value=(double) strtol(content,&p,10);
(void) value;
if (p != content)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlInvalidContent", "<level> too many values, map \"%s\"",map_id);
thresholds=DestroyXMLTree(thresholds);
map=DestroyThresholdMap(map);
return(map);
}
thresholds=DestroyXMLTree(thresholds);
return(map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ L i s t T h r e s h o l d M a p F i l e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMapFile() lists the threshold maps and their descriptions
% in the given XML file data.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,const char*xml,
% const char *filename,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o xml: The threshold map list in XML format.
%
% o filename: The threshold map XML filename.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml,
const char *filename,ExceptionInfo *exception)
{
const char
*alias,
*content,
*map;
XMLTreeInfo
*description,
*threshold,
*thresholds;
assert( xml != (char *) NULL );
assert( file != (FILE *) NULL );
(void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
"Loading threshold map file \"%s\" ...",filename);
thresholds=NewXMLTree(xml,exception);
if ( thresholds == (XMLTreeInfo *) NULL )
return(MagickFalse);
(void) FormatLocaleFile(file,"%-16s %-12s %s\n","Map","Alias","Description");
(void) FormatLocaleFile(file,
"----------------------------------------------------\n");
threshold=GetXMLTreeChild(thresholds,"threshold");
for ( ; threshold != (XMLTreeInfo *) NULL;
threshold=GetNextXMLTreeTag(threshold))
{
map=GetXMLTreeAttribute(threshold,"map");
if (map == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingAttribute", "<map>");
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
alias=GetXMLTreeAttribute(threshold,"alias");
description=GetXMLTreeChild(threshold,"description");
if (description == (XMLTreeInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingElement", "<description>, map \"%s\"",map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
content=GetXMLTreeContent(description);
if (content == (char *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"XmlMissingContent", "<description>, map \"%s\"", map);
thresholds=DestroyXMLTree(thresholds);
return(MagickFalse);
}
(void) FormatLocaleFile(file,"%-16s %-12s %s\n",map,alias ? alias : "",
content);
}
thresholds=DestroyXMLTree(thresholds);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i s t T h r e s h o l d M a p s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ListThresholdMaps() lists the threshold maps and their descriptions
% as defined by "threshold.xml" to a file.
%
% The format of the ListThresholdMaps method is:
%
% MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o file: An pointer to the output FILE.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListThresholdMaps(FILE *file,
ExceptionInfo *exception)
{
const StringInfo
*option;
LinkedListInfo
*options;
MagickStatusType
status;
status=MagickTrue;
if (file == (FILE *) NULL)
file=stdout;
options=GetConfigureOptions(ThresholdsFilename,exception);
(void) FormatLocaleFile(file,
"\n Threshold Maps for Ordered Dither Operations\n");
option=(const StringInfo *) GetNextValueInLinkedList(options);
while (option != (const StringInfo *) NULL)
{
(void) FormatLocaleFile(file,"\nPath: %s\n\n",GetStringInfoPath(option));
status&=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option),
GetStringInfoPath(option),exception);
option=(const StringInfo *) GetNextValueInLinkedList(options);
}
options=DestroyConfigureOptions(options);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O r d e r e d D i t h e r I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OrderedDitherImage() will perform a ordered dither based on a number
% of pre-defined dithering threshold maps, but over multiple intensity
% levels, which can be different for different channels, according to the
% input argument.
%
% The format of the OrderedDitherImage method is:
%
% MagickBooleanType OrderedDitherImage(Image *image,
% const char *threshold_map,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold_map: A string containing the name of the threshold dither
% map to use, followed by zero or more numbers representing the number
% of color levels tho dither between.
%
% Any level number less than 2 will be equivalent to 2, and means only
% binary dithering will be applied to each color channel.
%
% No numbers also means a 2 level (bitmap) dither will be applied to all
% channels, while a single number is the number of levels applied to each
% channel in sequence. More numbers will be applied in turn to each of
% the color channels.
%
% For example: "o3x3,6" will generate a 6 level posterization of the
% image with a ordered 3x3 diffused pixel dither being applied between
% each level. While checker,8,8,4 will produce a 332 colormaped image
% with only a single checkerboard hash pattern (50% grey) between each
% color level, to basically double the number of color levels with
% a bare minimim of dithering.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OrderedDitherImage(Image *image,
const char *threshold_map,ExceptionInfo *exception)
{
#define DitherImageTag "Dither/Image"
CacheView
*image_view;
char
token[MagickPathExtent];
const char
*p;
double
levels[CompositePixelChannel];
MagickBooleanType
status;
MagickOffsetType
progress;
register ssize_t
i;
ssize_t
y;
ThresholdMap
*map;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (threshold_map == (const char *) NULL)
return(MagickTrue);
p=(char *) threshold_map;
while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) &&
(*p != '\0'))
p++;
threshold_map=p;
while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) &&
(*p != '\0'))
{
if ((p-threshold_map) >= (MagickPathExtent-1))
break;
token[p-threshold_map]=(*p);
p++;
}
token[p-threshold_map]='\0';
map=GetThresholdMap(token,exception);
if (map == (ThresholdMap *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"InvalidArgument","%s : '%s'","ordered-dither",threshold_map);
return(MagickFalse);
}
for (i=0; i < MaxPixelChannels; i++)
levels[i]=2.0;
p=strchr((char *) threshold_map,',');
if ((p != (char *) NULL) && (isdigit((int) ((unsigned char) *(++p))) != 0))
{
GetNextToken(p,&p,MagickPathExtent,token);
for (i=0; (i < MaxPixelChannels); i++)
levels[i]=StringToDouble(token,(char **) NULL);
for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++)
{
GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
GetNextToken(p,&p,MagickPathExtent,token);
levels[i]=StringToDouble(token,(char **) NULL);
}
}
for (i=0; i < MaxPixelChannels; i++)
if (fabs(levels[i]) >= 1)
levels[i]-=1.0;
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
ssize_t
n;
n=0;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
ssize_t
level,
threshold;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (fabs(levels[n]) < MagickEpsilon)
{
n++;
continue;
}
threshold=(ssize_t) (QuantumScale*q[i]*(levels[n]*(map->divisor-1)+1));
level=threshold/(map->divisor-1);
threshold-=level*(map->divisor-1);
q[i]=ClampToQuantum((double) (level+(threshold >=
map->levels[(x % map->width)+map->width*(y % map->height)]))*
QuantumRange/levels[n]);
n++;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,DitherImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
map=DestroyThresholdMap(map);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% P e r c e p t i b l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% PerceptibleImage() set each pixel whose value is less than |epsilon| to
% epsilon or -epsilon (whichever is closer) otherwise the pixel value remains
% unchanged.
%
% The format of the PerceptibleImage method is:
%
% MagickBooleanType PerceptibleImage(Image *image,const double epsilon,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o epsilon: the epsilon threshold (e.g. 1.0e-9).
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline Quantum PerceptibleThreshold(const Quantum quantum,
const double epsilon)
{
double
sign;
sign=(double) quantum < 0.0 ? -1.0 : 1.0;
if ((sign*quantum) >= epsilon)
return(quantum);
return((Quantum) (sign*epsilon));
}
MagickExport MagickBooleanType PerceptibleImage(Image *image,
const double epsilon,ExceptionInfo *exception)
{
#define PerceptibleImageTag "Perceptible/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (image->storage_class == PseudoClass)
{
register ssize_t
i;
register PixelInfo
*magick_restrict q;
q=image->colormap;
for (i=0; i < (ssize_t) image->colors; i++)
{
q->red=(double) PerceptibleThreshold(ClampToQuantum(q->red),
epsilon);
q->green=(double) PerceptibleThreshold(ClampToQuantum(q->green),
epsilon);
q->blue=(double) PerceptibleThreshold(ClampToQuantum(q->blue),
epsilon);
q->alpha=(double) PerceptibleThreshold(ClampToQuantum(q->alpha),
epsilon);
q++;
}
return(SyncImage(image,exception));
}
/*
Perceptible image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if (traits == UndefinedPixelTrait)
continue;
q[i]=PerceptibleThreshold(q[i],epsilon);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,PerceptibleImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n d o m T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RandomThresholdImage() changes the value of individual pixels based on the
% intensity of each pixel compared to a random threshold. The result is a
% low-contrast, two color image.
%
% The format of the RandomThresholdImage method is:
%
% MagickBooleanType RandomThresholdImage(Image *image,
% const char *thresholds,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low,high: Specify the high and low thresholds. These values range from
% 0 to QuantumRange.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RandomThresholdImage(Image *image,
const double min_threshold, const double max_threshold,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
RandomInfo
**magick_restrict random_info;
ssize_t
y;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
unsigned long
key;
#endif
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
GetPixelInfo(image,&threshold);
/*
Random threshold image.
*/
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
double
threshold;
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if ((double) q[i] < min_threshold)
threshold=min_threshold;
else
if ((double) q[i] > max_threshold)
threshold=max_threshold;
else
threshold=(double) (QuantumRange*
GetPseudoRandomValue(random_info[id]));
q[i]=(double) q[i] <= threshold ? 0 : QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
random_info=DestroyRandomInfoThreadSet(random_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R a n g e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RangeThresholdImage() applies soft and hard thresholding.
%
% The format of the RangeThresholdImage method is:
%
% MagickBooleanType RangeThresholdImage(Image *image,
% const double low_black,const double low_white,const double high_white,
% const double high_black,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low_black: Define the minimum black threshold value.
%
% o low_white: Define the minimum white threshold value.
%
% o high_white: Define the maximum white threshold value.
%
% o high_black: Define the maximum black threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType RangeThresholdImage(Image *image,
const double low_black,const double low_white,const double high_white,
const double high_black,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Range threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel < low_black)
q[i]=0;
else
if ((pixel >= low_black) && (pixel < low_white))
q[i]=ClampToQuantum(QuantumRange*
PerceptibleReciprocal(low_white-low_black)*(pixel-low_black));
else
if ((pixel >= low_white) && (pixel <= high_white))
q[i]=QuantumRange;
else
if ((pixel > high_white) && (pixel <= high_black))
q[i]=ClampToQuantum(QuantumRange*PerceptibleReciprocal(
high_black-high_white)*(high_black-pixel));
else
if (pixel > high_black)
q[i]=0;
else
q[i]=0;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W h i t e T h r e s h o l d I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WhiteThresholdImage() is like ThresholdImage() but forces all pixels above
% the threshold into white while leaving all pixels at or below the threshold
% unchanged.
%
% The format of the WhiteThresholdImage method is:
%
% MagickBooleanType WhiteThresholdImage(Image *image,
% const char *threshold,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o threshold: Define the threshold value.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType WhiteThresholdImage(Image *image,
const char *thresholds,ExceptionInfo *exception)
{
#define ThresholdImageTag "Threshold/Image"
CacheView
*image_view;
GeometryInfo
geometry_info;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
threshold;
MagickStatusType
flags;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (thresholds == (const char *) NULL)
return(MagickTrue);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
GetPixelInfo(image,&threshold);
flags=ParseGeometry(thresholds,&geometry_info);
threshold.red=geometry_info.rho;
threshold.green=geometry_info.rho;
threshold.blue=geometry_info.rho;
threshold.black=geometry_info.rho;
threshold.alpha=100.0;
if ((flags & SigmaValue) != 0)
threshold.green=geometry_info.sigma;
if ((flags & XiValue) != 0)
threshold.blue=geometry_info.xi;
if ((flags & PsiValue) != 0)
threshold.alpha=geometry_info.psi;
if (threshold.colorspace == CMYKColorspace)
{
if ((flags & PsiValue) != 0)
threshold.black=geometry_info.psi;
if ((flags & ChiValue) != 0)
threshold.alpha=geometry_info.chi;
}
if ((flags & PercentValue) != 0)
{
threshold.red*=(MagickRealType) (QuantumRange/100.0);
threshold.green*=(MagickRealType) (QuantumRange/100.0);
threshold.blue*=(MagickRealType) (QuantumRange/100.0);
threshold.black*=(MagickRealType) (QuantumRange/100.0);
threshold.alpha*=(MagickRealType) (QuantumRange/100.0);
}
/*
White threshold image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
double
pixel;
register ssize_t
i;
pixel=GetPixelIntensity(image,q);
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
PixelTrait traits = GetPixelChannelTraits(image,channel);
if ((traits & UpdatePixelTrait) == 0)
continue;
if (image->channel_mask != DefaultChannels)
pixel=(double) q[i];
if (pixel > GetPixelInfoChannel(&threshold,channel))
q[i]=QuantumRange;
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,ThresholdImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_925_0 |
crossvul-cpp_data_bad_1014_0 | /*
* QLogic iSCSI Offload Driver
* Copyright (c) 2016 Cavium Inc.
*
* This software is available 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.
*/
#include "qedi_dbg.h"
#include <linux/vmalloc.h>
void
qedi_dbg_err(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (likely(qedi) && likely(qedi->pdev))
pr_err("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_err("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
va_end(va);
}
void
qedi_dbg_warn(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & QEDI_LOG_WARN))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_warn("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_warn("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
}
void
qedi_dbg_notice(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & QEDI_LOG_NOTICE))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_notice("[%s]:[%s:%d]:%d: %pV",
dev_name(&qedi->pdev->dev), nfunc, line,
qedi->host_no, &vaf);
else
pr_notice("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
}
void
qedi_dbg_info(struct qedi_dbg_ctx *qedi, const char *func, u32 line,
u32 level, const char *fmt, ...)
{
va_list va;
struct va_format vaf;
char nfunc[32];
memset(nfunc, 0, sizeof(nfunc));
memcpy(nfunc, func, sizeof(nfunc) - 1);
va_start(va, fmt);
vaf.fmt = fmt;
vaf.va = &va;
if (!(qedi_dbg_log & level))
goto ret;
if (likely(qedi) && likely(qedi->pdev))
pr_info("[%s]:[%s:%d]:%d: %pV", dev_name(&qedi->pdev->dev),
nfunc, line, qedi->host_no, &vaf);
else
pr_info("[0000:00:00.0]:[%s:%d]: %pV", nfunc, line, &vaf);
ret:
va_end(va);
}
int
qedi_create_sysfs_attr(struct Scsi_Host *shost, struct sysfs_bin_attrs *iter)
{
int ret = 0;
for (; iter->name; iter++) {
ret = sysfs_create_bin_file(&shost->shost_gendev.kobj,
iter->attr);
if (ret)
pr_err("Unable to create sysfs %s attr, err(%d).\n",
iter->name, ret);
}
return ret;
}
void
qedi_remove_sysfs_attr(struct Scsi_Host *shost, struct sysfs_bin_attrs *iter)
{
for (; iter->name; iter++)
sysfs_remove_bin_file(&shost->shost_gendev.kobj, iter->attr);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1014_0 |
crossvul-cpp_data_good_1019_2 | /*! @file GPMF_demo.c
*
* @brief Demo to extract GPMF from an MP4
*
* @version 1.0.1
*
* (C) Copyright 2017 GoPro Inc (http://gopro.com/).
*
* Licensed under either:
* - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
* - MIT license, http://opensource.org/licenses/MIT
* at your option.
*
* 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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "../GPMF_parser.h"
#include "GPMF_mp4reader.h"
extern void PrintGPMF(GPMF_stream *ms);
int main(int argc, char *argv[])
{
int32_t ret = GPMF_OK;
GPMF_stream metadata_stream, *ms = &metadata_stream;
double metadatalength;
uint32_t *payload = NULL; //buffer to store GPMF samples from the MP4.
// get file return data
if (argc != 2)
{
printf("usage: %s <file_with_GPMF>\n", argv[0]);
return -1;
}
size_t mp4 = OpenMP4Source(argv[1], MOV_GPMF_TRAK_TYPE, MOV_GPMF_TRAK_SUBTYPE);
if (mp4 == 0)
{
printf("error: %s is an invalid MP4/MOV\n", argv[1]);
return -1;
}
// size_t mp4 = OpenMP4SourceUDTA(argv[1]); //Search for GPMF payload with MP4's udta
metadatalength = GetDuration(mp4);
if (metadatalength > 0.0)
{
uint32_t index, payloads = GetNumberPayloads(mp4);
// printf("found %.2fs of metadata, from %d payloads, within %s\n", metadatalength, payloads, argv[1]);
#if 1
if (payloads == 1) // Printf the contents of the single payload
{
uint32_t payloadsize = GetPayloadSize(mp4,0);
payload = GetPayload(mp4, payload, 0);
if(payload == NULL)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
// Output (printf) all the contained GPMF data within this payload
ret = GPMF_Validate(ms, GPMF_RECURSE_LEVELS); // optional
if (GPMF_OK != ret)
{
printf("Invalid Structure\n");
goto cleanup;
}
GPMF_ResetState(ms);
do
{
PrintGPMF(ms); // printf current GPMF KLV
} while (GPMF_OK == GPMF_Next(ms, GPMF_RECURSE_LEVELS));
GPMF_ResetState(ms);
printf("\n");
}
#endif
for (index = 0; index < payloads; index++)
{
uint32_t payloadsize = GetPayloadSize(mp4, index);
double in = 0.0, out = 0.0; //times
payload = GetPayload(mp4, payload, index);
if (payload == NULL)
goto cleanup;
ret = GetPayloadTime(mp4, index, &in, &out);
if (ret != GPMF_OK)
goto cleanup;
ret = GPMF_Init(ms, payload, payloadsize);
if (ret != GPMF_OK)
goto cleanup;
#if 1 // Find all the available Streams and the data carrying FourCC
if (index == 0) // show first payload
{
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
while (GPMF_OK == ret)
{
ret = GPMF_SeekToSamples(ms);
if (GPMF_OK == ret) //find the last FOURCC within the stream
{
uint32_t key = GPMF_Key(ms);
GPMF_SampleType type = GPMF_Type(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
//uint32_t samples = GPMF_Repeat(ms);
uint32_t samples = GPMF_PayloadSampleCount(ms);
if (samples)
{
printf(" STRM of %c%c%c%c ", PRINTF_4CC(key));
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))
{
char tmp[64];
char *data = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
if (size < sizeof(tmp))
{
memcpy(tmp, data, size);
tmp[size] = 0;
printf("of type %s ", tmp);
}
}
}
else
{
printf("of type %c ", type);
}
printf("with %d sample%s ", samples, samples > 1 ? "s" : "");
if (elements > 1)
printf("-- %d elements per sample", elements);
printf("\n");
}
ret = GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS);
}
else
{
if (ret == GPMF_ERROR_BAD_STRUCTURE) // some payload element was corrupt, skip to the next valid GPMF KLV at the previous level.
{
ret = GPMF_Next(ms, GPMF_CURRENT_LEVEL); // this will be the next stream if any more are present.
}
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
#if 1 // Find GPS values and return scaled doubles.
if (index == 0) // show first payload
{
if (GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPS5"), GPMF_RECURSE_LEVELS) || //GoPro Hero5/6/7 GPS
GPMF_OK == GPMF_FindNext(ms, STR2FOURCC("GPRI"), GPMF_RECURSE_LEVELS)) //GoPro Karma GPS
{
uint32_t key = GPMF_Key(ms);
uint32_t samples = GPMF_Repeat(ms);
uint32_t elements = GPMF_ElementsInStruct(ms);
uint32_t buffersize = samples * elements * sizeof(double);
GPMF_stream find_stream;
double *ptr, *tmpbuffer = malloc(buffersize);
char units[10][6] = { "" };
uint32_t unit_samples = 1;
printf("MP4 Payload time %.3f to %.3f seconds\n", in, out);
if (tmpbuffer && samples)
{
uint32_t i, j;
//Search for any units to display
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_SI_UNITS, GPMF_CURRENT_LEVEL) ||
GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_UNITS, GPMF_CURRENT_LEVEL))
{
char *data = (char *)GPMF_RawData(&find_stream);
int ssize = GPMF_StructSize(&find_stream);
unit_samples = GPMF_Repeat(&find_stream);
for (i = 0; i < unit_samples; i++)
{
memcpy(units[i], data, ssize);
units[i][ssize] = 0;
data += ssize;
}
}
//GPMF_FormattedData(ms, tmpbuffer, buffersize, 0, samples); // Output data in LittleEnd, but no scale
GPMF_ScaledData(ms, tmpbuffer, buffersize, 0, samples, GPMF_TYPE_DOUBLE); //Output scaled data as floats
ptr = tmpbuffer;
for (i = 0; i < samples; i++)
{
printf("%c%c%c%c ", PRINTF_4CC(key));
for (j = 0; j < elements; j++)
printf("%.3f%s, ", *ptr++, units[j%unit_samples]);
printf("\n");
}
free(tmpbuffer);
}
}
GPMF_ResetState(ms);
printf("\n");
}
#endif
}
#if 1
// Find all the available Streams and compute they sample rates
while (GPMF_OK == GPMF_FindNext(ms, GPMF_KEY_STREAM, GPMF_RECURSE_LEVELS))
{
if (GPMF_OK == GPMF_SeekToSamples(ms)) //find the last FOURCC within the stream
{
double in = 0.0, out = 0.0;
uint32_t fourcc = GPMF_Key(ms);
double rate = GetGPMFSampleRate(mp4, fourcc, GPMF_SAMPLE_RATE_PRECISE, &in, &out);// GPMF_SAMPLE_RATE_FAST);
printf("%c%c%c%c sampling rate = %f Hz (from %f to %f)\n", PRINTF_4CC(fourcc), rate, in, out);
}
}
#endif
cleanup:
if (payload) FreePayload(payload); payload = NULL;
CloseSource(mp4);
}
return ret;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1019_2 |
crossvul-cpp_data_good_451_0 | /*
** The Sleuth Kit
**
** This software is subject to the IBM Public License ver. 1.0,
** which was displayed prior to download and is included in the readme.txt
** file accompanying the Sleuth Kit files. It may also be requested from:
** Crucial Security Inc.
** 14900 Conference Center Drive
** Chantilly, VA 20151
**
** Copyright (c) 2009 Brian Carrier. All rights reserved.
**
** Judson Powers [jpowers@atc-nycorp.com]
** Matt Stillerman [matt@atc-nycorp.com]
** Rob Joyce [rob@atc-nycorp.com]
** Copyright (c) 2008, 2012 ATC-NY. All rights reserved.
** This file contains data developed with support from the National
** Institute of Justice, Office of Justice Programs, U.S. Department of Justice.
**
** Wyatt Banks [wbanks@crucialsecurity.com]
** Copyright (c) 2005 Crucial Security Inc. All rights reserved.
**
** Brian Carrier [carrier@sleuthkit.org]
** Copyright (c) 2003-2005 Brian Carrier. All rights reserved
**
** Copyright (c) 1997,1998,1999, International Business Machines
** Corporation and others. All Rights Reserved.
*/
/* 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
--*/
/*
** You may distribute the Sleuth Kit, or other software that incorporates
** part of all of the Sleuth Kit, in object code form under a license agreement,
** provided that:
** a) you comply with the terms and conditions of the IBM Public License
** ver 1.0; and
** b) the license agreement
** i) effectively disclaims on behalf of all Contributors all warranties
** and conditions, express and implied, including warranties or
** conditions of title and non-infringement, and implied warranties
** or conditions of merchantability and fitness for a particular
** purpose.
** ii) effectively excludes on behalf of all Contributors liability for
** damages, including direct, indirect, special, incidental and
** consequential damages such as lost profits.
** iii) states that any provisions which differ from IBM Public License
** ver. 1.0 are offered by that Contributor alone and not by any
** other party; and
** iv) states that the source code for the program is available from you,
** and informs licensees how to obtain it in a reasonable manner on or
** through a medium customarily used for software exchange.
**
** When the Sleuth Kit or other software that incorporates part or all of
** the Sleuth Kit is made available in source code form:
** a) it must be made available under IBM Public License ver. 1.0; and
** b) a copy of the IBM Public License ver. 1.0 must be included with
** each copy of the program.
*/
/** \file hfs.c
* Contains the general internal TSK HFS metadata and data unit code
*/
#include "tsk_fs_i.h"
#include "tsk_hfs.h"
#include <stdarg.h>
#ifdef TSK_WIN32
#include <string.h>
#else
#include <strings.h>
#endif
#define XSWAP(a,b) { a ^= b; b ^= a; a ^= b; }
// Compression Stuff
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "lzvn.h"
// Forward declarations:
static uint8_t hfs_load_attrs(TSK_FS_FILE * fs_file);
static uint8_t hfs_load_extended_attrs(TSK_FS_FILE * file,
unsigned char *isCompressed, unsigned char *cmpType,
uint64_t * uncSize);
void error_detected(uint32_t errnum, char *errstr, ...);
void error_returned(char *errstr, ...);
#ifdef HAVE_LIBZ
/***************** ZLIB stuff *******************************/
// Adapted from zpipe.c (part of zlib) at http://zlib.net/zpipe.c
#define CHUNK 16384
/*
* Invokes the zlib library to inflate (uncompress) data.
*
* Returns and error code. Places the uncompressed data in a buffer supplied by the caller. Also
* returns the uncompressed length, and the number of compressed bytes consumed.
*
* Will stop short of the end of compressed data, if a natural end of a compression unit is reached. Using
* bytesConsumed, the caller can then advance the source pointer, and re-invoke the function. This will then
* inflate the next following compression unit in the data stream.
*
* @param source - buffer of compressed data
* @param sourceLen - length of the compressed data.
* @param dest -- buffer to hold the uncompressed results
* @param destLen -- length of the dest buffer
* @param uncompressedLength -- return of the length of the uncompressed data found.
* @param bytesConsumed -- return of the number of input bytes of compressed data used.
* @return 0 on success, a negative number on error
*/
static int
zlib_inflate(char *source, uint64_t sourceLen, char *dest, uint64_t destLen, uint64_t * uncompressedLength, unsigned long *bytesConsumed) // this is unsigned long because that's what zlib uses.
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
// Some vars to help with copying bytes into "in"
char *srcPtr = source;
char *destPtr = dest;
uint64_t srcAvail = sourceLen; //uint64_t
uint64_t amtToCopy;
uint64_t copiedSoFar = 0;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK) {
error_detected(TSK_ERR_FS_READ,
"zlib_inflate: failed to initialize inflation engine (%d)",
ret);
return ret;
}
/* decompress until deflate stream ends or end of file */
do {
// Copy up to CHUNK bytes into "in" from source, advancing the pointer, and
// setting strm.avail_in equal to the number of bytes copied.
if (srcAvail >= CHUNK) {
amtToCopy = CHUNK;
srcAvail -= CHUNK;
}
else {
amtToCopy = srcAvail;
srcAvail = 0;
}
// wipe out any previous value, copy in the bytes, advance the pointer, record number of bytes.
memset(in, 0, CHUNK);
if (amtToCopy > SIZE_MAX || amtToCopy > UINT_MAX) {
error_detected(TSK_ERR_FS_READ,
"zlib_inflate: amtToCopy in one chunk is too large");
return -100;
}
memcpy(in, srcPtr, (size_t) amtToCopy); // cast OK because of above test
srcPtr += amtToCopy;
strm.avail_in = (uInt) amtToCopy; // cast OK because of above test
if (strm.avail_in == 0)
break;
strm.next_in = in;
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
if (ret == Z_NEED_DICT)
ret = Z_DATA_ERROR; // we don't have a custom dict
if (ret < 0 && ret != Z_BUF_ERROR) { // Z_BUF_ERROR is not fatal
error_detected(TSK_ERR_FS_READ,
" zlib_inflate: zlib returned error %d (%s)", ret,
strm.msg);
(void) inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
// Is there enough space in dest to copy the current chunk?
if (copiedSoFar + have > destLen) {
// There is not enough space, so better return an error
error_detected(TSK_ERR_FS_READ,
" zlib_inflate: not enough space in inflation destination\n");
(void) inflateEnd(&strm);
return -200;
}
// Copy "have" bytes from out to destPtr, advance destPtr
memcpy(destPtr, out, have);
destPtr += have;
copiedSoFar += have;
} while ((strm.avail_out == 0) && (ret != Z_STREAM_END));
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
if (ret == Z_STREAM_END)
*uncompressedLength = copiedSoFar;
*bytesConsumed = strm.total_in;
/* clean up and return */
(void) inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
#endif
/* may set error up to string 1
* returns 0 on success, 1 on failure */
uint8_t
hfs_checked_read_random(TSK_FS_INFO * fs, char *buf, size_t len,
TSK_OFF_T offs)
{
ssize_t r;
r = tsk_fs_read(fs, offs, buf, len);
if (r != (ssize_t) len) {
if (r >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
return 1;
}
return 0;
}
/**********************************************************************
*
* MISC FUNCS
*
**********************************************************************/
/* convert the HFS Time (seconds from 1/1/1904)
* to UNIX (UTC seconds from 1/1/1970)
* The number is borrowed from linux HFS driver source
*/
uint32_t
hfs_convert_2_unix_time(uint32_t hfsdate)
{
if (hfsdate < NSEC_BTWN_1904_1970)
return 0;
return (uint32_t) (hfsdate - NSEC_BTWN_1904_1970);
}
/**
* Convert a cnid (metadata address) to big endian array.
* This is used to create the key for tree lookups.
* @param cnid Metadata address to convert
* @param array [out] Array to write data into.
*/
static void
cnid_to_array(uint32_t cnid, uint8_t array[4])
{
array[3] = (cnid >> 0) & 0xff;
array[2] = (cnid >> 8) & 0xff;
array[1] = (cnid >> 16) & 0xff;
array[0] = (cnid >> 24) & 0xff;
}
/**********************************************************************
*
* Lookup Functions
*
**********************************************************************/
/* Compares the given HFS+ Extents B-tree key to key constructed
* for finding the beginning of the data fork extents for the given
* CNID. (That is, the search key uses the given CNID and has
* fork = 0 and start_block = 0.)
*/
static int
hfs_ext_compare_keys(HFS_INFO * hfs, uint32_t cnid,
const hfs_btree_key_ext * key)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint32_t key_cnid;
key_cnid = tsk_getu32(fs->endian, key->file_id);
if (key_cnid < cnid)
return -1;
if (key_cnid > cnid)
return 1;
/* referring to the same cnids */
/* we are always looking for the data fork */
if (key->fork_type != HFS_EXT_KEY_TYPE_DATA)
return 1;
/* we are always looking for a start_block of zero
(interested in the beginning of the extents, regardless
of what the start_block is); all files except the bad
blocks file should have a start_block greater than
zero */
if (tsk_getu32(fs->endian, key->start_block) == 0)
return 0;
return 1;
}
/** \internal
* Returns the length of an HFS+ B-tree INDEX key based on the tree header
* structure and the length claimed in the record. With some trees,
* the length given in the record is not used.
* Note that this neither detects nor correctly handles 8-bit keys
* (which should not be present in HFS+).
*
* This does not give the right answer for the Attributes File B-tree, for some
* HFS+ file systems produced by the Apple OS, while it works for others. For
* the Attributes file, INDEX keys should always be as stated in the record itself,
* never the "maxKeyLen" of the B-tree header.
*
* In this software, this function is only invoked when dealing with the Extents file. In
* that usage, it is not sufficiently well tested to know if it always gives the right
* answer or not. We can only test that with a highly fragmented disk.
* @param hfs File System
* @param keylen Length of key as given in record
* @param header Tree header
* @returns Length of key
*/
uint16_t
hfs_get_idxkeylen(HFS_INFO * hfs, uint16_t keylen,
const hfs_btree_header_record * header)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
// if the flag is set, use the length given in the record
if (tsk_getu32(fs->endian, header->attr) & HFS_BT_HEAD_ATTR_VARIDXKEYS)
return keylen;
else
return tsk_getu16(fs->endian, header->maxKeyLen);
}
/**
* Convert the extents runs to TSK_FS_ATTR_RUN runs.
*
* @param a_fs File system to analyze
* @param a_extents Raw extents to process (in an array of 8)
* @param a_start_off Starting block offset of these runs
* @returns NULL on error or if no runs are in extents (test tsk_errno)
*/
static TSK_FS_ATTR_RUN *
hfs_extents_to_attr(TSK_FS_INFO * a_fs, const hfs_ext_desc * a_extents,
TSK_OFF_T a_start_off)
{
TSK_FS_ATTR_RUN *head_run = NULL;
TSK_FS_ATTR_RUN *prev_run = NULL;
int i;
TSK_OFF_T cur_off = a_start_off;
// since tsk_errno is checked as a return value, make sure it is clean.
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_extents_to_attr: Converting extents from offset %" PRIuOFF
" to runlist\n", a_start_off);
for (i = 0; i < 8; ++i) {
TSK_FS_ATTR_RUN *cur_run;
uint32_t addr = tsk_getu32(a_fs->endian, a_extents[i].start_blk);
uint32_t len = tsk_getu32(a_fs->endian, a_extents[i].blk_cnt);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_extents_to_attr: run %i at addr %" PRIu32
" with len %" PRIu32 "\n", i, addr, len);
if ((addr == 0) && (len == 0)) {
break;
}
// make a non-resident run
if ((cur_run = tsk_fs_attr_run_alloc()) == NULL) {
error_returned(" - hfs_extents_to_attr");
return NULL;
}
cur_run->addr = addr;
cur_run->len = len;
cur_run->offset = cur_off;
if (head_run == NULL)
head_run = cur_run;
if (prev_run != NULL)
prev_run->next = cur_run;
cur_off += cur_run->len;
prev_run = cur_run;
}
return head_run;
}
/**
* Look in the extents catalog for entries for a given file. Add the runs
* to the passed attribute structure.
*
* @param hfs File system being analyzed
* @param cnid file id of file to search for
* @param a_attr Attribute to add extents runs to
* @param dataForkQ if true, then find extents for the data fork. If false, then find extents for the Resource fork.
* @returns 1 on error and 0 on success
*/
static uint8_t
hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid,
TSK_FS_ATTR * a_attr, unsigned char dataForkQ)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint16_t nodesize; /* size of nodes (all, regardless of the name) */
uint32_t cur_node; /* node id of the current node */
char *node = NULL;
uint8_t is_done;
uint8_t desiredType;
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record_attr: Looking for extents for file %"
PRIu32 " %s\n", cnid,
dataForkQ ? "data fork" : "resource fork");
if (!hfs->has_extents_file) {
// No extents file (which is optional), and so, no further extents are possible.
return 0;
}
// Are we looking for extents of the data fork or the resource fork?
desiredType =
dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC;
// Load the extents attribute, if it has not been done so yet.
if (hfs->extents_file == NULL) {
ssize_t cnt;
if ((hfs->extents_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_EXTENTS_FILE_ID)) == NULL) {
return 1;
}
/* cache the data attribute */
hfs->extents_attr =
tsk_fs_attrlist_get(hfs->extents_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->extents_attr) {
tsk_error_errstr2_concat
(" - Default Attribute not found in Extents File");
return 1;
}
// cache the extents file header
cnt = tsk_fs_attr_read(hfs->extents_attr, 14,
(char *) &(hfs->extents_header),
sizeof(hfs_btree_header_record), 0);
if (cnt != sizeof(hfs_btree_header_record)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_ext_find_extent_record_attr: Error reading header");
return 1;
}
}
// allocate a node buffer
nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize);
if ((node = (char *) tsk_malloc(nodesize)) == NULL) {
return 1;
}
/* start at root node */
cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode);
/* if the root node is zero, then the extents btree is empty */
/* if no files have overflow extents, the Extents B-tree still
exists on disk, but is an empty B-tree containing only
the header node */
if (cur_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_ext_find_extent_record: "
"empty extents btree\n");
free(node);
return 0;
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_ext_find_extent_record: starting at "
"root node %" PRIu32 "; nodesize = %"
PRIu16 "\n", cur_node, nodesize);
/* Recurse down to the needed leaf nodes and then go forward */
is_done = 0;
while (is_done == 0) {
TSK_OFF_T cur_off; /* start address of cur_node */
uint16_t num_rec; /* number of records in this node */
ssize_t cnt;
hfs_btree_node *node_desc;
// sanity check
if (cur_node > tsk_getu32(fs->endian,
hfs->extents_header.totalNodes)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: Node %d too large for file",
cur_node);
free(node);
return 1;
}
// read the current node
cur_off = (TSK_OFF_T)cur_node * nodesize;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: reading node %" PRIu32
" at offset %" PRIuOFF "\n", cur_node, cur_off);
cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off,
node, nodesize, 0);
if (cnt != nodesize) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_ext_find_extent_record_attr: Error reading node %d at offset %"
PRIuOFF, cur_node, cur_off);
free(node);
return 1;
}
// process the header / descriptor
if (nodesize < sizeof(hfs_btree_node)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: Node size %d is too small to be valid", nodesize);
free(node);
return 1;
}
node_desc = (hfs_btree_node *) node;
num_rec = tsk_getu16(fs->endian, node_desc->num_rec);
if (num_rec == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record: zero records in node %"
PRIu32, cur_node);
free(node);
return 1;
}
/* With an index node, find the record with the largest key that is smaller
* to or equal to cnid */
if (node_desc->type == HFS_BT_NODE_TYPE_IDX) {
uint32_t next_node = 0;
int rec;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: Index node %" PRIu32
" @ %" PRIu64 " has %" PRIu16 " records\n", cur_node,
cur_off, num_rec);
for (rec = 0; rec < num_rec; ++rec) {
int cmp;
size_t rec_off;
hfs_btree_key_ext *key;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_ext *) & node[rec_off];
cmp = hfs_ext_compare_keys(hfs, cnid, key);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: record %" PRIu16
" ; keylen %" PRIu16 " (FileId: %" PRIu32
", ForkType: %" PRIu8 ", StartBlk: %" PRIu32
"); compare: %d\n", rec, tsk_getu16(fs->endian,
key->key_len), tsk_getu32(fs->endian,
key->file_id), key->fork_type,
tsk_getu32(fs->endian, key->start_block), cmp);
/* save the info from this record unless it is bigger than cnid */
if ((cmp <= 0) || (next_node == 0)) {
hfs_btree_index_record *idx_rec;
int keylen =
2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian,
key->key_len), &(hfs->extents_header));
if (rec_off + keylen > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node,
(int) rec_off + keylen, nodesize);
free(node);
return 1;
}
idx_rec =
(hfs_btree_index_record *) & node[rec_off +
keylen];
next_node = tsk_getu32(fs->endian, idx_rec->childNode);
}
// we are bigger than cnid, so move on to the next node
if (cmp > 0) {
break;
}
}
// check if we found a relevant node, if not stop.
if (next_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d",
cnid, cur_node);
is_done = 1;
break;
}
cur_node = next_node;
}
/* with a leaf, we process until we are past cnid. We move right too if we can */
else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) {
int rec;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: Leaf node %" PRIu32 " @ %"
PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off,
num_rec);
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_ext *key;
uint32_t rec_cnid;
hfs_extents *extents;
TSK_OFF_T ext_off = 0;
int keylen;
TSK_FS_ATTR_RUN *attr_run;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_ext *) & node[rec_off];
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: record %" PRIu16
"; keylen %" PRIu16 " (%" PRIu32
", %" PRIu8 ", %" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->file_id),
key->fork_type, tsk_getu32(fs->endian,
key->start_block));
rec_cnid = tsk_getu32(fs->endian, key->file_id);
// see if this record is for our file
// OLD logic, just handles the DATA fork
// if (rec_cnid < cnid) {
// continue;
// }
// else if ((rec_cnid > cnid)
// || (key->fork_type != HFS_EXT_KEY_TYPE_DATA)) {
// is_done = 1;
// break;
// }
// NEW logic, handles both DATA and RSRC forks.
if (rec_cnid < cnid) {
continue;
}
if (rec_cnid > cnid) {
is_done = 1;
break;
}
if (key->fork_type != desiredType) {
if (dataForkQ) {
is_done = 1;
break;
}
else
continue;
}
// OK, this is one of the extents records that we are seeking, so save it.
// Make sure there is room for the hfs_extents struct
keylen = 2 + tsk_getu16(fs->endian, key->key_len);
if (rec_off + keylen + sizeof(hfs_extents) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off + keylen,
nodesize);
free(node);
return 1;
}
// get the starting offset of this extent
ext_off = tsk_getu32(fs->endian, key->start_block);
// convert the extents to the TSK format
extents = (hfs_extents *) & node[rec_off + keylen];
attr_run =
hfs_extents_to_attr(fs, extents->extents, ext_off);
if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) {
tsk_error_errstr2_concat
(" - hfs_ext_find_extent_record_attr");
free(node);
return 1;
}
if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) {
tsk_error_errstr2_concat
(" - hfs_ext_find_extent_record_attr");
free(node);
return 1;
}
}
cur_node = tsk_getu32(fs->endian, node_desc->flink);
if (cur_node == 0) {
is_done = 1;
break;
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_ext_find_extent_record: btree node %"
PRIu32 " (%" PRIuOFF ") is neither index nor leaf (%" PRIu8
")", cur_node, cur_off, node_desc->type);
free(node);
return 1;
}
}
free(node);
return 0;
}
/** \internal
* Compares two Catalog B-tree keys.
* @param hfs File System being analyzed
* @param key1 Key 1 to compare
* @param key2 Key 2 to compare
* @returns -1 if key1 is smaller, 0 if equal, and 1 if key1 is larger
*/
int
hfs_cat_compare_keys(HFS_INFO * hfs, const hfs_btree_key_cat * key1,
const hfs_btree_key_cat * key2)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint32_t cnid1, cnid2;
cnid1 = tsk_getu32(fs->endian, key1->parent_cnid);
cnid2 = tsk_getu32(fs->endian, key2->parent_cnid);
if (cnid1 < cnid2)
return -1;
if (cnid1 > cnid2)
return 1;
return hfs_unicode_compare(hfs, &key1->name, &key2->name);
}
/** \internal
*
* Traverse the HFS catalog file. Call the callback for each
* record.
*
* @param hfs File system
* @param a_cb callback
* @param ptr Pointer to pass to callback
* @returns 1 on error
*/
uint8_t
hfs_cat_traverse(HFS_INFO * hfs,
TSK_HFS_BTREE_CB a_cb, void *ptr)
{
TSK_FS_INFO *fs = &(hfs->fs_info);
uint32_t cur_node; /* node id of the current node */
char *node;
uint16_t nodesize;
uint8_t is_done = 0;
tsk_error_reset();
nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize);
if ((node = (char *) tsk_malloc(nodesize)) == NULL)
return 1;
/* start at root node */
cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode);
/* if the root node is zero, then the extents btree is empty */
/* if no files have overflow extents, the Extents B-tree still
exists on disk, but is an empty B-tree containing only
the header node */
if (cur_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: "
"empty extents btree\n");
free(node);
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: starting at "
"root node %" PRIu32 "; nodesize = %"
PRIu16 "\n", cur_node, nodesize);
/* Recurse down to the needed leaf nodes and then go forward */
is_done = 0;
while (is_done == 0) {
TSK_OFF_T cur_off; /* start address of cur_node */
uint16_t num_rec; /* number of records in this node */
ssize_t cnt;
hfs_btree_node *node_desc;
// sanity check
if (cur_node > tsk_getu32(fs->endian,
hfs->catalog_header.totalNodes)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node %d too large for file", cur_node);
free(node);
return 1;
}
// read the current node
cur_off = cur_node * nodesize;
cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off,
node, nodesize, 0);
if (cnt != nodesize) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_traverse: Error reading node %d at offset %"
PRIuOFF, cur_node, cur_off);
free(node);
return 1;
}
// process the header / descriptor
if (nodesize < sizeof(hfs_btree_node)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node size %d is too small to be valid", nodesize);
free(node);
return 1;
}
node_desc = (hfs_btree_node *) node;
num_rec = tsk_getu16(fs->endian, node_desc->num_rec);
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32
" @ %" PRIu64 " has %" PRIu16 " records\n",
cur_node, cur_off, num_rec);
if (num_rec == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: zero records in node %"
PRIu32, cur_node);
free(node);
return 1;
}
/* With an index node, find the record with the largest key that is smaller
* to or equal to cnid */
if (node_desc->type == HFS_BT_NODE_TYPE_IDX) {
uint32_t next_node = 0;
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if (keylen >= nodesize - rec_off) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, (nodesize - rec_off));
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
" ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
/* save the info from this record unless it is too big */
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
// record the closest entry
else if ((retval == HFS_BTREE_CB_IDX_LT)
|| (next_node == 0)) {
hfs_btree_index_record *idx_rec;
int keylen =
2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian,
key->key_len), &(hfs->catalog_header));
if (rec_off + keylen > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node,
(int) rec_off + keylen, nodesize);
free(node);
return 1;
}
idx_rec =
(hfs_btree_index_record *) & node[rec_off +
keylen];
next_node = tsk_getu32(fs->endian, idx_rec->childNode);
}
if (retval == HFS_BTREE_CB_IDX_EQGT) {
// move down to the next node
break;
}
}
// check if we found a relevant node
if (next_node == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: did not find any keys in index node %d",
cur_node);
is_done = 1;
break;
}
// TODO: Handle multinode loops
if (next_node == cur_node) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: node %d references itself as next node",
cur_node);
is_done = 1;
break;
}
cur_node = next_node;
}
/* With a leaf, we look for the specific record. */
else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) {
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if ((keylen) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, nodesize);
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
"; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
// rec_cnid = tsk_getu32(fs->endian, key->file_id);
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_LEAF_STOP) {
is_done = 1;
break;
}
else if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
}
// move right to the next node if we got this far
if (is_done == 0) {
cur_node = tsk_getu32(fs->endian, node_desc->flink);
if (cur_node == 0) {
is_done = 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: moving forward to next leaf");
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32
" (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")",
cur_node, cur_off, node_desc->type);
free(node);
return 1;
}
}
free(node);
return 0;
}
typedef struct {
const hfs_btree_key_cat *targ_key;
TSK_OFF_T off;
} HFS_CAT_GET_RECORD_OFFSET_DATA;
static uint8_t
hfs_cat_get_record_offset_cb(HFS_INFO * hfs, int8_t level_type,
const hfs_btree_key_cat * cur_key,
TSK_OFF_T key_off, void *ptr)
{
HFS_CAT_GET_RECORD_OFFSET_DATA *offset_data = (HFS_CAT_GET_RECORD_OFFSET_DATA *)ptr;
const hfs_btree_key_cat *targ_key = offset_data->targ_key;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_get_record_offset_cb: %s node want: %" PRIu32
" vs have: %" PRIu32 "\n",
(level_type == HFS_BT_NODE_TYPE_IDX) ? "Index" : "Leaf",
tsk_getu32(hfs->fs_info.endian, targ_key->parent_cnid),
tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid));
if (level_type == HFS_BT_NODE_TYPE_IDX) {
int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key);
if (diff < 0)
return HFS_BTREE_CB_IDX_LT;
else
return HFS_BTREE_CB_IDX_EQGT;
}
else {
int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key);
// see if this record is for our file or if we passed the interesting entries
if (diff < 0) {
return HFS_BTREE_CB_LEAF_GO;
}
else if (diff == 0) {
offset_data->off =
key_off + 2 + tsk_getu16(hfs->fs_info.endian,
cur_key->key_len);
}
return HFS_BTREE_CB_LEAF_STOP;
}
}
/** \internal
* Find the byte offset (from the start of the catalog file) to a record
* in the catalog file.
* @param hfs File System being analyzed
* @param needle Key to search for
* @returns Byte offset or 0 on error. 0 is also returned if catalog
* record was not found. Check tsk_errno to determine if error occurred.
*/
static TSK_OFF_T
hfs_cat_get_record_offset(HFS_INFO * hfs, const hfs_btree_key_cat * needle)
{
HFS_CAT_GET_RECORD_OFFSET_DATA offset_data;
offset_data.off = 0;
offset_data.targ_key = needle;
if (hfs_cat_traverse(hfs, hfs_cat_get_record_offset_cb, &offset_data)) {
return 0;
}
return offset_data.off;
}
/** \internal
* Given a byte offset to a leaf record in teh catalog file, read the data as
* a thread record. This will zero the buffer and read in the size of the thread
* data.
* @param hfs File System
* @param off Byte offset of record in catalog file (not including key)
* @param thread [out] Buffer to write thread data into.
* @returns 0 on success, 1 on failure; sets up to error string 1 */
uint8_t
hfs_cat_read_thread_record(HFS_INFO * hfs, TSK_OFF_T off,
hfs_thread * thread)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint16_t uni_len;
ssize_t cnt;
memset(thread, 0, sizeof(hfs_thread));
cnt = tsk_fs_attr_read(hfs->catalog_attr, off, (char *) thread, 10, 0);
if (cnt != 10) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_thread_record: Error reading catalog offset %"
PRIuOFF " (header)", off);
return 1;
}
if ((tsk_getu16(fs->endian, thread->rec_type) != HFS_FOLDER_THREAD)
&& (tsk_getu16(fs->endian, thread->rec_type) != HFS_FILE_THREAD)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_read_thread_record: unexpected record type %" PRIu16,
tsk_getu16(fs->endian, thread->rec_type));
return 1;
}
uni_len = tsk_getu16(fs->endian, thread->name.length);
if (uni_len > 255) {
tsk_error_set_errno(TSK_ERR_FS_INODE_COR);
tsk_error_set_errstr
("hfs_cat_read_thread_record: invalid string length (%" PRIu16
")", uni_len);
return 1;
}
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off + 10,
(char *) thread->name.unicode, uni_len * 2, 0);
if (cnt != uni_len * 2) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_thread_record: Error reading catalog offset %"
PRIuOFF " (name)", off + 10);
return 1;
}
return 0;
}
/** \internal
* Read a catalog record into a local data structure. This reads the
* correct amount, depending on if it is a file or folder.
* @param hfs File system being analyzed
* @param off Byte offset (in catalog file) of record (not including key)
* @param record [out] Structure to read data into
* @returns 1 on error
*/
uint8_t
hfs_cat_read_file_folder_record(HFS_INFO * hfs, TSK_OFF_T off,
hfs_file_folder * record)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
ssize_t cnt;
char rec_type[2];
memset(record, 0, sizeof(hfs_file_folder));
cnt = tsk_fs_attr_read(hfs->catalog_attr, off, rec_type, 2, 0);
if (cnt != 2) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading record type from catalog offset %"
PRIuOFF " (header)", off);
return 1;
}
if (tsk_getu16(fs->endian, rec_type) == HFS_FOLDER_RECORD) {
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record,
sizeof(hfs_folder), 0);
if (cnt != sizeof(hfs_folder)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading catalog offset %"
PRIuOFF " (folder)", off);
return 1;
}
}
else if (tsk_getu16(fs->endian, rec_type) == HFS_FILE_RECORD) {
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record,
sizeof(hfs_file), 0);
if (cnt != sizeof(hfs_file)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading catalog offset %"
PRIuOFF " (file)", off);
return 1;
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_read_file_folder_record: unexpected record type %"
PRIu16, tsk_getu16(fs->endian, rec_type));
return 1;
}
return 0;
}
// hfs_lookup_hard_link appears to be unnecessary - it looks up the cnid
// by seeing if there's a file/dir with the standard hard link name plus
// linknum and returns the meta_addr. But this should always be the same as linknum,
// and is very slow when there are many hard links, so it shouldn't be used.
//static TSK_INUM_T
//hfs_lookup_hard_link(HFS_INFO * hfs, TSK_INUM_T linknum,
// unsigned char is_directory)
//{
// char fBuff[30];
// TSK_FS_DIR *mdir;
// size_t indx;
// TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
//
// memset(fBuff, 0, 30);
//
// if (is_directory) {
//
// tsk_take_lock(&(hfs->metadata_dir_cache_lock));
// if (hfs->dir_meta_dir == NULL) {
// hfs->dir_meta_dir =
// tsk_fs_dir_open_meta(fs, hfs->meta_dir_inum);
// }
// tsk_release_lock(&(hfs->metadata_dir_cache_lock));
//
// if (hfs->dir_meta_dir == NULL) {
// error_returned
// ("hfs_lookup_hard_link: could not open the dir metadata directory");
// return 0;
// }
// else {
// mdir = hfs->dir_meta_dir;
// }
// snprintf(fBuff, 30, "dir_%" PRIuINUM, linknum);
//
// }
// else {
//
// tsk_take_lock(&(hfs->metadata_dir_cache_lock));
// if (hfs->meta_dir == NULL) {
// hfs->meta_dir = tsk_fs_dir_open_meta(fs, hfs->meta_inum);
// }
// tsk_release_lock(&(hfs->metadata_dir_cache_lock));
//
// if (hfs->meta_dir == NULL) {
// error_returned
// ("hfs_lookup_hard_link: could not open file metadata directory");
// return 0;
// }
// else {
// mdir = hfs->meta_dir;
// }
// snprintf(fBuff, 30, "iNode%" PRIuINUM, linknum);
// }
//
// for (indx = 0; indx < tsk_fs_dir_getsize(mdir); ++indx) {
// if ((mdir->names != NULL) && mdir->names[indx].name &&
// (fs->name_cmp(fs, mdir->names[indx].name, fBuff) == 0)) {
// // OK this is the one
// return mdir->names[indx].meta_addr;
// }
// }
//
// // OK, we did not find that linknum
// return 0;
//}
/*
* Given a catalog entry, will test that entry to see if it is a hard link.
* If it is a hard link, the function returns the inum (or cnid) of the target file.
* If it is NOT a hard link, then then function returns the inum of the given entry.
* In both cases, the parameter is_error is set to zero.
*
* If an ERROR occurs, if it is a mild error, then is_error is set to 1, and the
* inum of the given entry is returned. This signals that hard link detection cannot
* be carried out.
*
* If the error is serious, then is_error is set to 2 or 3, depending on the kind of error, and
* the TSK error code is set, and the function returns zero. is_error==2 means that an error
* occurred in looking up the target file in the Catalog. is_error==3 means that the given
* entry appears to be a hard link, but the target file does not exist in the Catalog.
*
* @param hfs The file system
* @param entry The catalog entry to check
* @param is_error A Boolean that is returned indicating an error, or no error.\
* @return The inum (or cnid) of the hard link target, or of the given catalog entry, or zero.
*/
TSK_INUM_T
hfs_follow_hard_link(HFS_INFO * hfs, hfs_file * cat,
unsigned char *is_error)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_INUM_T cnid;
time_t crtime;
uint32_t file_type;
uint32_t file_creator;
*is_error = 0; // default, not an error
if (cat == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_follow_hard_link: Pointer to Catalog entry (2nd arg) is null");
return 0;
}
cnid = tsk_getu32(fs->endian, cat->std.cnid);
if (cnid < HFS_FIRST_USER_CNID) {
// Can't be a hard link. And, cannot look up in Catalog file either!
return cnid;
}
crtime =
(time_t) hfs_convert_2_unix_time(tsk_getu32(fs->endian,
cat->std.crtime));
file_type = tsk_getu32(fs->endian, cat->std.u_info.file_type);
file_creator = tsk_getu32(fs->endian, cat->std.u_info.file_cr);
// Only proceed with the rest of this if the flags etc are right
if (file_type == HFS_HARDLINK_FILE_TYPE
&& file_creator == HFS_HARDLINK_FILE_CREATOR) {
// see if we have the HFS+ Private Data dir for file links;
// if not, it can't be a hard link. (We could warn the user, but
// we also rely on this when finding the HFS+ Private Data dir in
// the first place and we don't want a warning on every hfs_open.)
if (hfs->meta_inum == 0)
return cnid;
// For this to work, we need the FS creation times. Is at least one of these set?
if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime)
&& (!hfs->has_meta_crtime)) {
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
*is_error = 1;
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: File system creation times are not set. "
"Cannot test inode for hard link. File type and creator indicate that this"
" is a hard link (file), with LINK ID = %" PRIu32 "\n",
linkNum);
return cnid;
}
if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime)) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: Either the root folder or the"
" file metadata folder is not accessible. Testing this potential hard link"
" may be impaired.\n");
}
// Now we need to check the creation time against the three FS creation times
if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) ||
(hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime))
|| (hfs->has_root_crtime && (crtime == hfs->root_crtime))) {
// OK, this is a hard link to a file.
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
// We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found
// that it was very ineffecient and always resulted in the same linkNum value.
// We now just use linkNum
return linkNum;
}
}
else if (file_type == HFS_LINKDIR_FILE_TYPE
&& file_creator == HFS_LINKDIR_FILE_CREATOR) {
// see if we have the HFS+ Private Directory Data dir for links;
// if not, it can't be a hard link. (We could warn the user, but
// we also rely on this when finding the HFS+ Private Directory Data dir in
// the first place and we don't want a warning on every hfs_open.)
if (hfs->meta_dir_inum == 0)
return cnid;
// For this to work, we need the FS creation times. Is at least one of these set?
if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime)
&& (!hfs->has_meta_crtime)) {
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
*is_error = 1;
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: File system creation times are not set. "
"Cannot test inode for hard link. File type and creator indicate that this"
" is a hard link (directory), with LINK ID = %" PRIu32
"\n", linkNum);
return cnid;
}
if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime)
|| (!hfs->has_meta_dir_crtime)) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: Either the root folder or the"
" file metadata folder or the directory metatdata folder is"
" not accessible. Testing this potential hard linked folder "
"may be impaired.\n");
}
// Now we need to check the creation time against the three FS creation times
if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) ||
(hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime))
|| (hfs->has_root_crtime && (crtime == hfs->root_crtime))) {
// OK, this is a hard link to a directory.
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
// We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found
// that it was very ineffecient and always resulted in the same linkNum value.
// We now just use linkNum
return linkNum;
}
}
// It cannot be a hard link (file or directory)
return cnid;
}
/** \internal
* Lookup an entry in the catalog file and save it into the entry. Do not
* call this for the special files that do not have an entry in the catalog.
* data structure.
* @param hfs File system being analyzed
* @param inum Address (cnid) of file to open
* @param entry [out] Structure to read data into
* @returns 1 on error or not found, 0 on success. Check tsk_errno
* to differentiate between error and not found. If it is not found, then the
* errno will be TSK_ERR_FS_INODE_NUM. Else, it will be some other value.
*/
uint8_t
hfs_cat_file_lookup(HFS_INFO * hfs, TSK_INUM_T inum, HFS_ENTRY * entry,
unsigned char follow_hard_link)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
hfs_btree_key_cat key; /* current catalog key */
hfs_thread thread; /* thread record */
hfs_file_folder record; /* file/folder record */
TSK_OFF_T off;
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: called for inum %" PRIuINUM "\n", inum);
// Test if this is a special file that is not located in the catalog
if ((inum == HFS_EXTENTS_FILE_ID) ||
(inum == HFS_CATALOG_FILE_ID) ||
(inum == HFS_ALLOCATION_FILE_ID) ||
(inum == HFS_STARTUP_FILE_ID) ||
(inum == HFS_ATTRIBUTES_FILE_ID)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_file_lookup: Called on special file: %" PRIuINUM,
inum);
return 1;
}
/* first look up the thread record for the item we're searching for */
/* set up the thread record key */
memset((char *) &key, 0, sizeof(hfs_btree_key_cat));
cnid_to_array((uint32_t) inum, key.parent_cnid);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: Looking up thread record (%" PRIuINUM
")\n", inum);
/* look up the thread record */
off = hfs_cat_get_record_offset(hfs, &key);
if (off == 0) {
// no parsing error, just not found
if (tsk_error_get_errno() == 0) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr
("hfs_cat_file_lookup: Error finding thread node for file (%"
PRIuINUM ")", inum);
}
else {
tsk_error_set_errstr2
(" hfs_cat_file_lookup: thread for file (%" PRIuINUM ")",
inum);
}
return 1;
}
/* read the thread record */
if (hfs_cat_read_thread_record(hfs, off, &thread)) {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")",
inum);
return 1;
}
/* now look up the actual file/folder record */
/* build key */
memset((char *) &key, 0, sizeof(hfs_btree_key_cat));
memcpy((char *) key.parent_cnid, (char *) thread.parent_cnid,
sizeof(key.parent_cnid));
memcpy((char *) &key.name, (char *) &thread.name, sizeof(key.name));
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: Looking up file record (parent: %"
PRIuINUM ")\n", (uint64_t) tsk_getu32(fs->endian,
key.parent_cnid));
/* look up the record */
off = hfs_cat_get_record_offset(hfs, &key);
if (off == 0) {
// no parsing error, just not found
if (tsk_error_get_errno() == 0) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr
("hfs_cat_file_lookup: Error finding record node %"
PRIuINUM, inum);
}
else {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM
")", inum);
}
return 1;
}
/* read the record */
if (hfs_cat_read_file_folder_record(hfs, off, &record)) {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")",
inum);
return 1;
}
/* these memcpy can be gotten rid of, really */
if (tsk_getu16(fs->endian,
record.file.std.rec_type) == HFS_FOLDER_RECORD) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: found folder record valence %" PRIu32
", cnid %" PRIu32 "\n", tsk_getu32(fs->endian,
record.folder.std.valence), tsk_getu32(fs->endian,
record.folder.std.cnid));
memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_folder));
}
else if (tsk_getu16(fs->endian,
record.file.std.rec_type) == HFS_FILE_RECORD) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: found file record cnid %" PRIu32
"\n", tsk_getu32(fs->endian, record.file.std.cnid));
memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_file));
}
/* other cases already caught by hfs_cat_read_file_folder_record */
memcpy((char *) &entry->thread, (char *) &thread, sizeof(hfs_thread));
entry->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED;
entry->inum = inum;
if (follow_hard_link) {
// TEST to see if this is a hard link
unsigned char is_err;
TSK_INUM_T target_cnid =
hfs_follow_hard_link(hfs, &(entry->cat), &is_err);
if (is_err > 1) {
error_returned
("hfs_cat_file_lookup: error occurred while following a possible hard link for "
"inum (cnid) = %" PRIuINUM, inum);
return 1;
}
if (target_cnid != inum) {
// This is a hard link, and we have got the cnid of the target file, so look it up.
uint8_t res =
hfs_cat_file_lookup(hfs, target_cnid, entry, FALSE);
if (res != 0) {
error_returned
("hfs_cat_file_lookup: error occurred while looking up the Catalog entry for "
"the target of inum (cnid) = %" PRIuINUM " target",
inum);
}
return 1;
}
// Target is NOT a hard link, so fall through to the non-hard link exit.
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_file_lookup exiting\n");
return 0;
}
static uint8_t
hfs_find_highest_inum_cb(HFS_INFO * hfs, int8_t level_type,
const hfs_btree_key_cat * cur_key,
TSK_OFF_T key_off, void *ptr)
{
// NOTE: This assumes that the biggest inum is the last one that we
// see. the traverse method does not currently promise that as part of
// its callback "contract".
*((TSK_INUM_T*) ptr) = tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid);
return HFS_BTREE_CB_IDX_LT;
}
/** \internal
* Returns the largest inode number in file system
* @param hfs File system being analyzed
* @returns largest metadata address
*/
static TSK_INUM_T
hfs_find_highest_inum(HFS_INFO * hfs)
{
// @@@ get actual number from Catalog file (go to far right) (we can't always trust the vol header)
TSK_INUM_T inum;
if (hfs_cat_traverse(hfs, hfs_find_highest_inum_cb, &inum)) {
/* Catalog traversal failed, fallback on legacy method :
if HFS_VH_ATTR_CNIDS_REUSED is set, then
the maximum CNID is 2^32-1; if it's not set, then nextCatalogId is
supposed to be larger than all CNIDs on disk.
*/
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_CNIDS_REUSED)
return (TSK_INUM_T) 0xffffffff;
else
return (TSK_INUM_T) tsk_getu32(fs->endian,
hfs->fs->next_cat_id) - 1;
}
return inum;
}
static TSK_FS_META_MODE_ENUM
hfs_mode_to_tsk_mode(uint16_t a_mode)
{
TSK_FS_META_MODE_ENUM mode = 0;
if (a_mode & HFS_IN_ISUID)
mode |= TSK_FS_META_MODE_ISUID;
if (a_mode & HFS_IN_ISGID)
mode |= TSK_FS_META_MODE_ISGID;
if (a_mode & HFS_IN_ISVTX)
mode |= TSK_FS_META_MODE_ISVTX;
if (a_mode & HFS_IN_IRUSR)
mode |= TSK_FS_META_MODE_IRUSR;
if (a_mode & HFS_IN_IWUSR)
mode |= TSK_FS_META_MODE_IWUSR;
if (a_mode & HFS_IN_IXUSR)
mode |= TSK_FS_META_MODE_IXUSR;
if (a_mode & HFS_IN_IRGRP)
mode |= TSK_FS_META_MODE_IRGRP;
if (a_mode & HFS_IN_IWGRP)
mode |= TSK_FS_META_MODE_IWGRP;
if (a_mode & HFS_IN_IXGRP)
mode |= TSK_FS_META_MODE_IXGRP;
if (a_mode & HFS_IN_IROTH)
mode |= TSK_FS_META_MODE_IROTH;
if (a_mode & HFS_IN_IWOTH)
mode |= TSK_FS_META_MODE_IWOTH;
if (a_mode & HFS_IN_IXOTH)
mode |= TSK_FS_META_MODE_IXOTH;
return mode;
}
static TSK_FS_META_TYPE_ENUM
hfs_mode_to_tsk_meta_type(uint16_t a_mode)
{
switch (a_mode & HFS_IN_IFMT) {
case HFS_IN_IFIFO:
return TSK_FS_META_TYPE_FIFO;
case HFS_IN_IFCHR:
return TSK_FS_META_TYPE_CHR;
case HFS_IN_IFDIR:
return TSK_FS_META_TYPE_DIR;
case HFS_IN_IFBLK:
return TSK_FS_META_TYPE_BLK;
case HFS_IN_IFREG:
return TSK_FS_META_TYPE_REG;
case HFS_IN_IFLNK:
return TSK_FS_META_TYPE_LNK;
case HFS_IN_IFSOCK:
return TSK_FS_META_TYPE_SOCK;
case HFS_IFWHT:
return TSK_FS_META_TYPE_WHT;
case HFS_IFXATTR:
return TSK_FS_META_TYPE_UNDEF;
default:
/* error */
return TSK_FS_META_TYPE_UNDEF;
}
}
static uint8_t
hfs_make_specialbase(TSK_FS_FILE * fs_file)
{
fs_file->meta->type = TSK_FS_META_TYPE_REG;
fs_file->meta->mode = 0;
fs_file->meta->nlink = 1;
fs_file->meta->flags =
(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC);
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) {
error_returned
(" - hfs_make_specialbase, couldn't malloc space for a name list");
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();
}
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the catalog file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_catalog(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_catalog: Making virtual catalog file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_catalog");
return 1;
}
fs_file->meta->addr = HFS_CATALOG_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_CATALOGNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz);
// convert the runs in the volume header to attribute runs
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->cat_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_catalog");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_catalog");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_catalog");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_CATALOG_FILE_ID, fs_attr,
TRUE)) {
error_returned(" - hfs_make_catalog");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Catalog file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_FILE for the extents file
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_extents(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_extents: Making virtual extents file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_extents");
return 1;
}
fs_file->meta->addr = HFS_EXTENTS_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_EXTENTSNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->ext_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_extents");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_extents");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_extents");
tsk_fs_attr_run_free(attr_run);
return 1;
}
//hfs_load_extended_attrs(fs_file);
// Extents doesn't have an entry in itself
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the blockmap / allocation file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_blockmap(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_blockmap: Making virtual blockmap file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_blockmap");
return 1;
}
fs_file->meta->addr = HFS_ALLOCATION_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_ALLOCATIONNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->alloc_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_blockmap");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_blockmap");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_blockmap");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_ALLOCATION_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_blockmap");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Allocation file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the startup / boot file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_startfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_startfile: Making virtual startup file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_startfile");
return 1;
}
fs_file->meta->addr = HFS_STARTUP_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_STARTUPNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->start_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_startfile");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_startfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_startfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_STARTUP_FILE_ID, fs_attr,
TRUE)) {
error_returned(" - hfs_make_startfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Start file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the attributes file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_attrfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_attrfile: Making virtual attributes file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_attrfile");
return 1;
}
fs_file->meta->addr = HFS_ATTRIBUTES_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_ATTRIBUTESNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->attr_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_attrfile");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_attrfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_attrfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_ATTRIBUTES_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_attrfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
//hfs_load_extended_attrs(fs_file);
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_FILE structure for the BadBlocks file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_badblockfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_ATTR *fs_attr;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_badblockfile: Making virtual badblock file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
fs_file->meta->addr = HFS_BAD_BLOCK_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_BAD_BLOCK_FILE_NAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size = 0;
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
// add the run to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
fs_file->meta->size, fs_file->meta->size, fs_file->meta->size,
0, 0)) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
// see if file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_BAD_BLOCK_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_badblockfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
/* @@@ We have a chicken and egg problem here... The current design of
* fs_attr_set() requires the size to be set, but we dont' know the size
* until we look into the extents file (which adds to an attribute...).
* This does not seem to be the best design... neeed a way to test this. */
fs_file->meta->size = fs_attr->nrd.initsize;
fs_attr->size = fs_file->meta->size;
fs_attr->nrd.allocsize = fs_file->meta->size;
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the BadBlocks file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/** \internal
* Copy the catalog file or folder record entry into a TSK data structure.
* @param a_hfs File system being analyzed
* @param a_hfs_entry Catalog record entry (HFS_ENTRY *)
* @param a_fs_file Structure to copy data into (TSK_FS_FILE *)
* Returns 1 on error.
*/
static uint8_t
hfs_dinode_copy(HFS_INFO * a_hfs, const HFS_ENTRY * a_hfs_entry,
TSK_FS_FILE * a_fs_file)
{
// Note, a_hfs_entry->cat is really of type hfs_file. But, hfs_file_folder is a union
// of that type with hfs_folder. Both of hfs_file and hfs_folder have the same first member.
// So, this cast is appropriate.
const hfs_file_folder *a_entry =
(hfs_file_folder *) & (a_hfs_entry->cat);
const hfs_file_fold_std *std;
TSK_FS_META *a_fs_meta = a_fs_file->meta;
TSK_FS_INFO *fs;
uint16_t hfsmode;
TSK_INUM_T iStd; // the inum (or CNID) that occurs in the standard file metadata
if (a_entry == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_dinode_copy: a_entry = a_hfs_entry->cat is NULL");
return 1;
}
fs = (TSK_FS_INFO *) & a_hfs->fs_info;
// Just a sanity check. The inum (or cnid) occurs in two places in the
// entry data structure.
iStd = tsk_getu32(fs->endian, a_entry->file.std.cnid);
if (iStd != a_hfs_entry->inum) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_dinode_copy: HFS_ENTRY with conflicting values for inum (or cnid).\n");
}
if (a_fs_meta == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("hfs_dinode_copy: a_fs_meta is NULL");
return 1;
}
// both files and folders start off the same
std = &(a_entry->file.std);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy: called for file/folder %" PRIu32 "\n",
tsk_getu32(fs->endian, std->cnid));
if (a_fs_meta->content_len < HFS_FILE_CONTENT_LEN) {
if ((a_fs_meta =
tsk_fs_meta_realloc(a_fs_meta,
HFS_FILE_CONTENT_LEN)) == NULL) {
return 1;
}
}
a_fs_meta->attr_state = TSK_FS_META_ATTR_EMPTY;
if (a_fs_meta->attr) {
tsk_fs_attrlist_markunused(a_fs_meta->attr);
}
/*
* Copy the file type specific stuff first
*/
hfsmode = tsk_getu16(fs->endian, std->perm.mode);
if (tsk_getu16(fs->endian, std->rec_type) == HFS_FOLDER_RECORD) {
// set the type of mode is not set
if ((hfsmode & HFS_IN_IFMT) == 0)
a_fs_meta->type = TSK_FS_META_TYPE_DIR;
a_fs_meta->size = 0;
memset(a_fs_meta->content_ptr, 0, HFS_FILE_CONTENT_LEN);
}
else if (tsk_getu16(fs->endian, std->rec_type) == HFS_FILE_RECORD) {
hfs_fork *fork;
// set the type of mode is not set
if ((hfsmode & HFS_IN_IFMT) == 0)
a_fs_meta->type = TSK_FS_META_TYPE_REG;
a_fs_meta->size =
tsk_getu64(fs->endian, a_entry->file.data.logic_sz);
// copy the data and resource forks
fork = (hfs_fork *) a_fs_meta->content_ptr;
memcpy(fork, &(a_entry->file.data), sizeof(hfs_fork));
memcpy(&fork[1], &(a_entry->file.resource), sizeof(hfs_fork));
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy error: catalog entry is neither file nor folder\n");
return 1;
}
/*
* Copy the standard stuff.
* Use default values (as defined in spec) if mode is not defined.
*/
if ((hfsmode & HFS_IN_IFMT) == 0) {
a_fs_meta->mode = 0;
a_fs_meta->uid = 99;
a_fs_meta->gid = 99;
}
else {
a_fs_meta->mode = hfs_mode_to_tsk_mode(hfsmode);
a_fs_meta->type = hfs_mode_to_tsk_meta_type(hfsmode);
a_fs_meta->uid = tsk_getu32(fs->endian, std->perm.owner);
a_fs_meta->gid = tsk_getu32(fs->endian, std->perm.group);
}
// this field is set only for "indirect" entries
if (tsk_getu32(fs->endian, std->perm.special.nlink))
a_fs_meta->nlink = tsk_getu32(fs->endian, std->perm.special.nlink);
else
a_fs_meta->nlink = 1;
a_fs_meta->mtime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->cmtime));
a_fs_meta->atime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->atime));
a_fs_meta->crtime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->crtime));
a_fs_meta->ctime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->amtime));
a_fs_meta->time2.hfs.bkup_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->bkup_date));
a_fs_meta->mtime_nano = a_fs_meta->atime_nano = a_fs_meta->ctime_nano =
a_fs_meta->crtime_nano = 0;
a_fs_meta->time2.hfs.bkup_time_nano = 0;
a_fs_meta->addr = tsk_getu32(fs->endian, std->cnid);
// All entries here are used.
a_fs_meta->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED;
if (std->perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
a_fs_meta->flags |= TSK_FS_META_FLAG_COMP;
// We copy this inum (or cnid) here, because this file *might* have been a hard link. In
// that case, we want to make sure that a_fs_file points consistently to the target of the
// link.
if (a_fs_file->name != NULL) {
a_fs_file->name->meta_addr = a_fs_meta->addr;
}
/* TODO @@@ could fill in name2 with this entry's name and parent inode
from Catalog entry */
/* set the link string (if the file is a link)
* The size check is a sanity check so that we don't try to allocate
* a huge amount of memory for a bad inode value
*/
if ((a_fs_meta->type == TSK_FS_META_TYPE_LNK) &&
(a_fs_meta->size >= 0) && (a_fs_meta->size < HFS_MAXPATHLEN)) {
ssize_t bytes_read;
a_fs_meta->link = tsk_malloc((size_t) a_fs_meta->size + 1);
if (a_fs_meta->link == NULL)
return 1;
bytes_read = tsk_fs_file_read(a_fs_file, (TSK_OFF_T) 0,
a_fs_meta->link, (size_t) a_fs_meta->size,
TSK_FS_FILE_READ_FLAG_NONE);
a_fs_meta->link[a_fs_meta->size] = '\0';
if (bytes_read != a_fs_meta->size) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy: failed to read contents of symbolic link; "
"expected %u bytes but tsk_fs_file_read() returned %u\n",
a_fs_meta->size, bytes_read);
free(a_fs_meta->link);
a_fs_meta->link = NULL;
return 1;
}
}
return 0;
}
/** \internal
* Load a catalog file entry and save it in the TSK_FS_FILE structure.
*
* @param fs File system to read from.
* @param a_fs_file Structure to read into.
* @param inum File address to load
* @returns 1 on error
*/
static uint8_t
hfs_inode_lookup(TSK_FS_INFO * fs, TSK_FS_FILE * a_fs_file,
TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
HFS_ENTRY entry;
if (a_fs_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("hfs_inode_lookup: fs_file is NULL");
return 1;
}
if (a_fs_file->meta == NULL) {
a_fs_file->meta = tsk_fs_meta_alloc(HFS_FILE_CONTENT_LEN);
}
if (a_fs_file->meta == NULL) {
return 1;
}
else {
tsk_fs_meta_reset(a_fs_file->meta);
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_inode_lookup: looking up %" PRIuINUM "\n",
inum);
// @@@ Will need to add orphan stuff here too
/* First see if this is a special entry
* the special ones have their metadata stored in the volume header */
if (inum == HFS_EXTENTS_FILE_ID) {
if (!hfs->has_extents_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Extents File not present");
return 1;
}
return hfs_make_extents(hfs, a_fs_file);
}
else if (inum == HFS_CATALOG_FILE_ID) {
return hfs_make_catalog(hfs, a_fs_file);
}
else if (inum == HFS_BAD_BLOCK_FILE_ID) {
// Note: the Extents file and the BadBlocks file are really the same.
if (!hfs->has_extents_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"BadBlocks File not present");
return 1;
}
return hfs_make_badblockfile(hfs, a_fs_file);
}
else if (inum == HFS_ALLOCATION_FILE_ID) {
return hfs_make_blockmap(hfs, a_fs_file);
}
else if (inum == HFS_STARTUP_FILE_ID) {
if (!hfs->has_startup_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Startup File not present");
return 1;
}
return hfs_make_startfile(hfs, a_fs_file);
}
else if (inum == HFS_ATTRIBUTES_FILE_ID) {
if (!hfs->has_attributes_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Attributes File not present");
return 1;
}
return hfs_make_attrfile(hfs, a_fs_file);
}
/* Lookup inode and store it in the HFS structure */
if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE)) {
return 1;
}
/* Copy the structure in hfs to generic fs_inode */
if (hfs_dinode_copy(hfs, &entry, a_fs_file)) {
return 1;
}
/* If this is potentially a compressed file, its
* actual size is unknown until we examine the
* extended attributes */
if ((a_fs_file->meta->size == 0) &&
(a_fs_file->meta->type == TSK_FS_META_TYPE_REG) &&
(a_fs_file->meta->attr_state != TSK_FS_META_ATTR_ERROR) &&
((a_fs_file->meta->attr_state != TSK_FS_META_ATTR_STUDIED) ||
(a_fs_file->meta->attr == NULL))) {
hfs_load_attrs(a_fs_file);
}
return 0;
}
typedef struct {
uint32_t offset;
uint32_t length;
} CMP_OFFSET_ENTRY;
/**
* \internal
* Reads the ZLIB compression block table from the attribute.
*
* @param rAtttr the attribute to read
* @param offsetTableOut block table
* @param tableSizeOut size of block table
* @param tableOffsetOut the offset of the block table in the resource fork
* @return 1 on success, 0 on error
*/
static int
hfs_read_zlib_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) {
ssize_t attrReadResult;
hfs_resource_fork_header rfHeader;
uint32_t dataOffset;
uint32_t offsetTableOffset;
char fourBytes[4]; // Size of the offset table, little endian
uint32_t tableSize; // Size of the offset table
char *offsetTableData = NULL;
CMP_OFFSET_ENTRY *offsetTable = NULL;
size_t indx;
// Read the resource fork header
attrReadResult = tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader,
sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != sizeof(hfs_resource_fork_header)) {
error_returned
(" %s: trying to read the resource fork header", __func__);
return 0;
}
// Begin to parse the resource fork. For now, we just need the data offset.
dataOffset = tsk_getu32(TSK_BIG_ENDIAN, rfHeader.dataOffset);
// The resource's data begins with an offset table, which defines blocks
// of (optionally) zlib-compressed data (so that the OS can do file seeks
// efficiently; each uncompressed block is 64KB).
offsetTableOffset = dataOffset + 4;
// read 4 bytes, the number of table entries, little endian
attrReadResult =
tsk_fs_attr_read(rAttr, offsetTableOffset, fourBytes, 4,
TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != 4) {
error_returned
(" %s: trying to read the offset table size, "
"return value of %u should have been 4", __func__, attrReadResult);
return 0;
}
tableSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes);
// Each table entry is 8 bytes long
offsetTableData = tsk_malloc(tableSize * 8);
if (offsetTableData == NULL) {
error_returned
(" %s: space for the offset table raw data", __func__);
return 0;
}
offsetTable =
(CMP_OFFSET_ENTRY *) tsk_malloc(tableSize *
sizeof(CMP_OFFSET_ENTRY));
if (offsetTable == NULL) {
error_returned
(" %s: space for the offset table", __func__);
goto on_error;
}
attrReadResult = tsk_fs_attr_read(rAttr, offsetTableOffset + 4,
offsetTableData, tableSize * 8, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) tableSize * 8) {
error_returned
(" %s: reading in the compression offset table, "
"return value %u should have been %u", __func__, attrReadResult,
tableSize * 8);
goto on_error;
}
for (indx = 0; indx < tableSize; ++indx) {
offsetTable[indx].offset =
tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8);
offsetTable[indx].length =
tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8 + 4);
}
free(offsetTableData);
*offsetTableOut = offsetTable;
*tableSizeOut = tableSize;
*tableOffsetOut = offsetTableOffset;
return 1;
on_error:
free(offsetTable);
free(offsetTableData);
return 0;
}
/**
* \internal
* Reads the LZVN compression block table from the attribute.
*
* @param rAtttr the attribute to read
* @param offsetTableOut block table
* @param tableSizeOut size of block table
* @param tableOffsetOut the offset of the block table in the resource fork
* @return 1 on success, 0 on error
*/
static int
hfs_read_lzvn_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) {
ssize_t attrReadResult;
char fourBytes[4];
uint32_t tableDataSize;
uint32_t tableSize; // Size of the offset table
char *offsetTableData = NULL;
CMP_OFFSET_ENTRY *offsetTable = NULL;
// The offset table is a sequence of 4-byte offsets of compressed
// blocks. The first 4 bytes is thus the offset of the first block,
// but also 4 times the number of entries in the table.
attrReadResult = tsk_fs_attr_read(rAttr, 0, fourBytes, 4,
TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != 4) {
error_returned
(" %s: trying to read the offset table size, "
"return value of %u should have been 4", __func__, attrReadResult);
return 0;
}
tableDataSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes);
offsetTableData = tsk_malloc(tableDataSize);
if (offsetTableData == NULL) {
error_returned
(" %s: space for the offset table raw data", __func__);
return 0;
}
// table entries are 4 bytes, last entry is end of data
tableSize = tableDataSize / 4 - 1;
offsetTable =
(CMP_OFFSET_ENTRY *) tsk_malloc(tableSize *
sizeof(CMP_OFFSET_ENTRY));
if (offsetTable == NULL) {
error_returned
(" %s: space for the offset table", __func__);
goto on_error;
}
attrReadResult = tsk_fs_attr_read(rAttr, 0,
offsetTableData, tableDataSize, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) tableDataSize) {
error_returned
(" %s: reading in the compression offset table, "
"return value %u should have been %u", __func__, attrReadResult,
tableDataSize);
goto on_error;
}
uint32_t a = tableDataSize;
uint32_t b;
size_t i;
for (i = 0; i < tableSize; ++i) {
b = tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + 4*(i+1));
offsetTable[i].offset = a;
offsetTable[i].length = b - a;
a = b;
}
free(offsetTableData);
*offsetTableOut = offsetTable;
*tableSizeOut = tableSize;
*tableOffsetOut = 0;
return 1;
on_error:
free(offsetTable);
free(offsetTableData);
return 0;
}
/**
* \internal
* "Decompress" a block which was stored uncompressed.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_noncompressed_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) {
// actually an uncompressed block of data; just copy
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Copying an uncompressed compression unit\n", __func__);
if ((len - 1) > COMPRESSION_UNIT_SIZE) {
error_detected(TSK_ERR_FS_READ,
"%s: uncompressed block length %u is longer "
"than compression unit size %u", __func__, len - 1,
COMPRESSION_UNIT_SIZE);
return 0;
}
memcpy(uncBuf, rawBuf + 1, len - 1);
*uncLen = len - 1;
return 1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Decompress a block which was stored with ZLIB.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_zlib_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)
{
// see if this block is compressed
if (len > 0 && (rawBuf[0] & 0x0F) != 0x0F) {
// Uncompress the chunk of data
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Inflating the compression unit\n", __func__);
unsigned long bytesConsumed;
int infResult = zlib_inflate(rawBuf, (uint64_t) len,
uncBuf, (uint64_t) COMPRESSION_UNIT_SIZE,
uncLen, &bytesConsumed);
if (infResult != 0) {
error_returned
(" %s: zlib inflation (uncompression) failed",
__func__, infResult);
return 0;
}
if (bytesConsumed != len) {
error_detected(TSK_ERR_FS_READ,
" %s, decompressor did not consume the whole compressed data",
__func__);
return 0;
}
return 1;
}
else {
// actually an uncompressed block of data; just copy
return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen);
}
}
#endif
/**
* \internal
* Decompress a block which was stored with LZVN.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_lzvn_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)
{
// see if this block is compressed
if (len > 0 && rawBuf[0] != 0x06) {
*uncLen = lzvn_decode_buffer(uncBuf, COMPRESSION_UNIT_SIZE, rawBuf, len);
return 1; // apparently this can't fail
}
else {
// actually an uncompressed block of data; just copy
return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen);
}
}
/**
* \internal
* Decompress a block.
*
* @param rAttr the attribute to read
* @param rawBuf the compressed data
* @param uncBuf the decompressed data
* @param offsetTable table of compressed block offsets
* @param offsetTableSize size of table of compressed block offsets
* @param offsetTableOffset offset of table of compressed block offsets
* @param indx index of block to read
* @param decompress_block pointer to decompression function
* @return decompressed size on success, -1 on error
*/
static ssize_t read_and_decompress_block(
const TSK_FS_ATTR* rAttr,
char* rawBuf,
char* uncBuf,
const CMP_OFFSET_ENTRY* offsetTable,
uint32_t offsetTableSize,
uint32_t offsetTableOffset,
size_t indx,
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen)
)
{
// @@@ BC: Looks like we should have bounds checks that indx < offsetTableSize, but we should confirm
ssize_t attrReadResult;
uint32_t offset = offsetTableOffset + offsetTable[indx].offset;
uint32_t len = offsetTable[indx].length;
uint64_t uncLen;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Reading compression unit %d, length %d\n",
__func__, indx, len);
/* Github #383 referenced that if len is 0, then the below code causes
* problems. Added this check, but I don't have data to verify this on.
* it looks like it should at least not crash, but it isn't clear if it
* will also do the right thing and if should actually break here
* instead. */
if (len == 0) {
return 0;
}
if (len > COMPRESSION_UNIT_SIZE + 1) {
error_detected(TSK_ERR_FS_READ,
"%s: block size is too large: %u", __func__, len);
return -1;
}
// Read in the block of compressed data
attrReadResult = tsk_fs_attr_read(rAttr, offset,
rawBuf, len, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) len) {
char msg[] =
"%s%s: reading in the compression offset table, "
"return value %u should have been %u";
if (attrReadResult < 0 ) {
error_returned(msg, " ", __func__, attrReadResult, len);
}
else {
error_detected(TSK_ERR_FS_READ, "", __func__, attrReadResult, len);
}
return -1;
}
if (!decompress_block(rawBuf, len, uncBuf, &uncLen)) {
return -1;
}
// If size is a multiple of COMPRESSION_UNIT_SIZE,
// expected uncompressed length is COMPRESSION_UNIT_SIZE
const uint32_t expUncLen = indx == offsetTableSize - 1 ?
((rAttr->fs_file->meta->size - 1) % COMPRESSION_UNIT_SIZE) + 1 :
COMPRESSION_UNIT_SIZE;
if (uncLen != expUncLen) {
error_detected(TSK_ERR_FS_READ,
"%s: compressed block decompressed to %u bytes, "
"should have been %u bytes", __func__, uncLen, expUncLen);
return -1;
}
// There are now uncLen bytes of uncompressed data available from
// this comp unit.
return (ssize_t)uncLen;
}
/**
* \internal
* Attr walk callback function for compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @param read_block_table pointer to block table read function
* @param decompress_block pointer to decompression function
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_compressed_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr,
int (*read_block_table)(const TSK_FS_ATTR *rAttr,
CMP_OFFSET_ENTRY** offsetTableOut,
uint32_t* tableSizeOut,
uint32_t* tableOffsetOut),
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen))
{
TSK_FS_INFO *fs;
TSK_FS_FILE *fs_file;
const TSK_FS_ATTR *rAttr; // resource fork attribute
char *rawBuf = NULL; // compressed data
char *uncBuf = NULL; // uncompressed data
uint32_t offsetTableOffset;
uint32_t offsetTableSize; // The number of table entries
CMP_OFFSET_ENTRY *offsetTable = NULL;
size_t indx; // index for looping over the offset table
TSK_OFF_T off = 0; // the offset in the uncompressed data stream consumed thus far
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Entered, because this is a compressed file with compressed data in the resource fork\n", __func__);
// clean up any error messages that are lying around
tsk_error_reset();
if ((fs_attr == NULL) || (fs_attr->fs_file == NULL)
|| (fs_attr->fs_file->meta == NULL)
|| (fs_attr->fs_file->fs_info == NULL)) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("%s: Null arguments given\n", __func__);
return 1;
}
// Check that the ATTR being read is the main DATA resource, 128-0,
// because this is the only one that can be compressed in HFS+
if ((fs_attr->id != HFS_FS_ATTR_ID_DATA) ||
(fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) {
error_detected(TSK_ERR_FS_ARG,
"%s: arg specified an attribute %u-%u that is not the data fork, "
"Only the data fork can be compressed.", __func__, fs_attr->type,
fs_attr->id);
return 1;
}
/* This MUST be a compressed attribute */
if (!(fs_attr->flags & TSK_FS_ATTR_COMP)) {
error_detected(TSK_ERR_FS_FWALK,
"%s: called with non-special attribute: %x",
__func__, fs_attr->flags);
return 1;
}
fs = fs_attr->fs_file->fs_info;
fs_file = fs_attr->fs_file;
/******** Open the Resource Fork ***********/
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
(" %s: could not get the attribute for the resource fork of the file", __func__);
return 1;
}
// read the offset table from the fork header
if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) {
return 1;
}
// Allocate two buffers for the raw and uncompressed data
/* Raw data can be COMPRESSION_UNIT_SIZE+1 if the data is not
* compressed and there is a 1-byte flag that indicates that
* the data is not compressed. */
rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1);
if (rawBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE);
if (uncBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
// FOR entry in the table DO
for (indx = 0; indx < offsetTableSize; ++indx) {
ssize_t uncLen; // uncompressed length
unsigned int blockSize;
uint64_t lumpSize;
uint64_t remaining;
char *lumpStart;
switch ((uncLen = read_and_decompress_block(
rAttr, rawBuf, uncBuf,
offsetTable, offsetTableSize, offsetTableOffset, indx,
decompress_block)))
{
case -1:
goto on_error;
case 0:
continue;
default:
break;
}
// Call the a_action callback with "Lumps"
// that are at most the block size.
blockSize = fs->block_size;
remaining = uncLen;
lumpStart = uncBuf;
while (remaining > 0) {
int retval; // action return value
lumpSize = remaining <= blockSize ? remaining : blockSize;
// Apply the callback function
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Calling action on lump of size %"
PRIu64 " offset %" PRIu64 " in the compression unit\n",
__func__, lumpSize, uncLen - remaining);
if (lumpSize > SIZE_MAX) {
error_detected(TSK_ERR_FS_FWALK,
" %s: lumpSize is too large for the action", __func__);
goto on_error;
}
retval = a_action(fs_attr->fs_file, off, 0, lumpStart,
(size_t) lumpSize, // cast OK because of above test
TSK_FS_BLOCK_FLAG_COMP, ptr);
if (retval == TSK_WALK_ERROR) {
error_detected(TSK_ERR_FS | 201,
"%s: callback returned an error", __func__);
goto on_error;
}
else if (retval == TSK_WALK_STOP) {
break;
}
// Find the next lump
off += lumpSize;
remaining -= lumpSize;
lumpStart += lumpSize;
}
}
// Done, so free up the allocated resources.
free(offsetTable);
free(rawBuf);
free(uncBuf);
return 0;
on_error:
free(offsetTable);
free(rawBuf);
free(uncBuf);
return 1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Attr walk callback function for ZLIB compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_zlib_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr)
{
return hfs_attr_walk_compressed_rsrc(
fs_attr, flags, a_action, ptr,
hfs_read_zlib_block_table,
hfs_decompress_zlib_block
);
}
#endif
/**
* \internal
* Attr walk callback function for LZVN compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_lzvn_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr)
{
return hfs_attr_walk_compressed_rsrc(
fs_attr, flags, a_action, ptr,
hfs_read_lzvn_block_table,
hfs_decompress_lzvn_block
);
}
/**
* \internal
* Read a compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @param read_block_table pointer to block table read function
* @param decompress_block pointer to decompression function
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_compressed_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len,
int (*read_block_table)(const TSK_FS_ATTR *rAttr,
CMP_OFFSET_ENTRY** offsetTableOut,
uint32_t* tableSizeOut,
uint32_t* tableOffsetOut),
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen))
{
TSK_FS_FILE *fs_file;
const TSK_FS_ATTR *rAttr;
char *rawBuf = NULL;
char *uncBuf = NULL;
uint32_t offsetTableOffset;
uint32_t offsetTableSize; // Size of the offset table
CMP_OFFSET_ENTRY *offsetTable = NULL;
TSK_OFF_T indx; // index for looping over the offset table
TSK_OFF_T startUnit = 0;
uint32_t startUnitOffset = 0;
TSK_OFF_T endUnit = 0;
uint64_t bytesCopied;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: called because this file is compressed, with data in the resource fork\n", __func__);
// Reading zero bytes? OK at any offset, I say!
if (a_len == 0)
return 0;
if (a_offset < 0) {
error_detected(TSK_ERR_FS_ARG,
"%s: reading from file at a negative offset",
__func__);
return -1;
}
if (a_len > SIZE_MAX / 2) {
error_detected(TSK_ERR_FS_ARG,
"%s: trying to read more than SIZE_MAX/2 is not supported.",
__func__);
return -1;
}
if ((a_fs_attr == NULL) || (a_fs_attr->fs_file == NULL)
|| (a_fs_attr->fs_file->meta == NULL)
|| (a_fs_attr->fs_file->fs_info == NULL)) {
error_detected(TSK_ERR_FS_ARG,
"%s: NULL parameters passed", __func__);
return -1;
}
// This should be a compressed file. If not, that's an error!
if (!(a_fs_attr->flags & TSK_FS_ATTR_COMP)) {
error_detected(TSK_ERR_FS_ARG,
"%s: called with non-special attribute: %x",
__func__, a_fs_attr->flags);
return -1;
}
// Check that the ATTR being read is the main DATA resource, 4352-0,
// because this is the only one that can be compressed in HFS+
if ((a_fs_attr->id != HFS_FS_ATTR_ID_DATA) ||
(a_fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) {
error_detected(TSK_ERR_FS_ARG,
"%s: arg specified an attribute %u-%u that is not the data fork, "
"Only the data fork can be compressed.", __func__,
a_fs_attr->type, a_fs_attr->id);
return -1;
}
/******** Open the Resource Fork ***********/
// The file
fs_file = a_fs_attr->fs_file;
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
(" %s: could not get the attribute for the resource fork of the file", __func__);
return -1;
}
// read the offset table from the fork header
if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) {
return -1;
}
// Compute the range of compression units needed for the request
startUnit = a_offset / COMPRESSION_UNIT_SIZE;
startUnitOffset = a_offset % COMPRESSION_UNIT_SIZE;
endUnit = (a_offset + a_len - 1) / COMPRESSION_UNIT_SIZE;
if (startUnit >= offsetTableSize || endUnit >= offsetTableSize) {
error_detected(TSK_ERR_FS_ARG,
"%s: range of bytes requested %lld - %lld falls past the "
"end of the uncompressed stream %llu\n",
__func__, a_offset, a_offset + a_len,
offsetTable[offsetTableSize-1].offset +
offsetTable[offsetTableSize-1].length);
goto on_error;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: reading compression units: %" PRIuOFF
" to %" PRIuOFF "\n", __func__, startUnit, endUnit);
bytesCopied = 0;
// Allocate buffers for the raw and uncompressed data
/* Raw data can be COMPRESSION_UNIT_SIZE+1 if the zlib data is not
* compressed and there is a 1-byte flag that indicates that
* the data is not compressed. */
rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1);
if (rawBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE);
if (uncBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
// Read from the indicated comp units
for (indx = startUnit; indx <= endUnit; ++indx) {
uint64_t uncLen;
char *uncBufPtr = uncBuf;
size_t bytesToCopy;
switch ((uncLen = read_and_decompress_block(
rAttr, rawBuf, uncBuf,
offsetTable, offsetTableSize, offsetTableOffset, (size_t)indx,
decompress_block)))
{
case -1:
goto on_error;
case 0:
continue;
default:
break;
}
// If this is the first comp unit, then we must skip over the
// startUnitOffset bytes.
if (indx == startUnit) {
uncLen -= startUnitOffset;
uncBufPtr += startUnitOffset;
}
// How many bytes to copy from this compression unit?
if (bytesCopied + uncLen < (uint64_t) a_len) // cast OK because a_len > 0
bytesToCopy = (size_t) uncLen; // uncLen <= size of compression unit, which is small, so cast is OK
else
bytesToCopy = (size_t) (((uint64_t) a_len) - bytesCopied); // diff <= compression unit size, so cast is OK
// Copy into the output buffer, and update bookkeeping.
memcpy(a_buf + bytesCopied, uncBufPtr, bytesToCopy);
bytesCopied += bytesToCopy;
}
// Well, we don't know (without a lot of work) what the
// true uncompressed size of the stream is. All we know is the "upper bound" which
// assumes that all of the compression units expand to their full size. If we did
// know the true size, then we could reject requests that go beyond the end of the
// stream. Instead, we treat the stream as if it is padded out to the full size of
// the last compression unit with zeros.
// Have we read and copied all of the bytes requested?
if (bytesCopied < a_len) {
// set the remaining bytes to zero
memset(a_buf + bytesCopied, 0, a_len - (size_t) bytesCopied); // cast OK because diff must be < compression unit size
}
free(offsetTable);
free(rawBuf);
free(uncBuf);
return (ssize_t) bytesCopied; // cast OK, cannot be greater than a_len which cannot be greater than SIZE_MAX/2 (rounded down).
on_error:
free(offsetTable);
free(rawBuf);
free(uncBuf);
return -1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Read a ZLIB compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_zlib_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len)
{
return hfs_file_read_compressed_rsrc(
a_fs_attr, a_offset, a_buf, a_len,
hfs_read_zlib_block_table,
hfs_decompress_zlib_block
);
}
#endif
/**
* \internal
* Read an LZVN compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_lzvn_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len)
{
return hfs_file_read_compressed_rsrc(
a_fs_attr, a_offset, a_buf, a_len,
hfs_read_lzvn_block_table,
hfs_decompress_lzvn_block
);
}
/**
* \internal
* "Decompress" an uncompressed attr
*
* HFS+ compression schemes allow for some blocks to be stored uncompressed.
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1
*/
static int hfs_decompress_noncompressed_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) {
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Leading byte, 0x%02x, indicates that the data is not really compressed.\n"
"%s: Loading the default DATA attribute.", __func__, rawBuf[0], __func__);
*dstBuf = rawBuf + 1; // + 1 indicator byte
*dstSize = uncSize;
*dstBufFree = FALSE;
return 1;
}
/**
* \internal
* Decompress a ZLIB compressed attr
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1 on success, 0 on error
*/
static int hfs_decompress_zlib_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree)
{
// ZLIB blocks cannot start with 0xF as the low nibble, so that's used
// as the flag for noncompressed blocks
if ((rawBuf[0] & 0x0F) == 0x0F) {
return hfs_decompress_noncompressed_attr(
rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree);
}
else {
#ifdef HAVE_LIBZ
char* uncBuf = NULL;
uint64_t uLen;
unsigned long bytesConsumed;
int infResult;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Uncompressing (inflating) data.", __func__);
// Uncompress the remainder of the attribute, and load as 128-0
// Note: cast is OK because uncSize will be quite modest, < 4000.
uncBuf = (char *) tsk_malloc((size_t) uncSize + 100); // add some extra space
if (uncBuf == NULL) {
error_returned
(" - %s, space for the uncompressed attr", __func__);
return 0;
}
infResult = zlib_inflate(rawBuf, (uint64_t) rawSize,
uncBuf, (uint64_t) (uncSize + 100),
&uLen, &bytesConsumed);
if (infResult != 0) {
error_returned
(" %s, zlib could not uncompress attr", __func__);
free(uncBuf);
return 0;
}
if (bytesConsumed != rawSize) {
error_detected(TSK_ERR_FS_READ,
" %s, decompressor did not consume the whole compressed data",
__func__);
free(uncBuf);
return 0;
}
*dstBuf = uncBuf;
*dstSize = uncSize;
*dstBufFree = TRUE;
#else
// ZLIB compression library is not available, so we will load a
// zero-length default DATA attribute. Without this, icat may
// misbehave.
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: ZLIB not available, so loading an empty default DATA attribute.\n", __func__);
// Dummy is one byte long, so the ptr is not null, but we set the
// length to zero bytes, so it is never read.
static uint8_t dummy[1];
*dstBuf = dummy;
*dstSize = 0;
*dstBufFree = FALSE;
#endif
}
return 1;
}
/**
* \internal
* Decompress an LZVN compressed attr
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1 on success, 0 on error
*/
static int hfs_decompress_lzvn_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree)
{
// LZVN blocks cannot start with 0x06, so that's used as the flag for
// noncompressed blocks
if (rawBuf[0] == 0x06) {
return hfs_decompress_noncompressed_attr(
rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree);
}
char* uncBuf = (char *) tsk_malloc((size_t) uncSize);
*dstSize = lzvn_decode_buffer(uncBuf, uncSize, rawBuf, rawSize);
*dstBuf = uncBuf;
*dstBufFree = TRUE;
return 1;
}
/**
* \internal
* Read a compressed attr
*
* @param fs_file the file
* @param cmpType compression type
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @param decompress_attr pointer to the decompression function
* @return 1 on success, 0 on error
*/
static int
hfs_file_read_compressed_attr(TSK_FS_FILE* fs_file,
uint8_t cmpType,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize,
int (*decompress_attr)(char* rawBuf,
uint32_t rawSize,
uint64_t uncSize,
char** dstBuf,
uint64_t* dstSize,
int* dstBufFree))
{
// Data is inline. We will load the uncompressed data as a
// resident attribute.
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Compressed data is inline in the attribute, will load this as the default DATA attribute.\n", __func__);
if (attributeLength <= 16) {
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: WARNING, Compression Record of type %u is not followed by"
" compressed data. No data will be loaded into the DATA"
" attribute.\n", __func__, cmpType);
// oddly, this is not actually considered an error
return 1;
}
TSK_FS_ATTR *fs_attr_unc;
// There is data following the compression record, as there should be.
if ((fs_attr_unc = tsk_fs_attrlist_getnew(
fs_file->meta->attr, TSK_FS_ATTR_RES)) == NULL)
{
error_returned(" - %s, FS_ATTR for uncompressed data", __func__);
return 0;
}
char* dstBuf;
uint64_t dstSize;
int dstBufFree = FALSE;
if (!decompress_attr(buffer + 16, attributeLength - 16, uncSize,
&dstBuf, &dstSize, &dstBufFree)) {
return 0;
}
if (dstSize != uncSize) {
error_detected(TSK_ERR_FS_READ,
" %s, actual uncompressed size not equal to the size in the compression record", __func__);
goto on_error;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Loading decompressed data as default DATA attribute.",
__func__);
// Load the remainder of the attribute as 128-0
// set the details in the fs_attr structure.
// Note, we are loading this as a RESIDENT attribute.
if (tsk_fs_attr_set_str(fs_file,
fs_attr_unc, "DATA",
TSK_FS_ATTR_TYPE_HFS_DATA,
HFS_FS_ATTR_ID_DATA, dstBuf,
dstSize))
{
error_returned(" - %s", __func__);
goto on_error;
}
if (dstBufFree) {
free(dstBuf);
}
return 1;
on_error:
if (dstBufFree) {
free(dstBuf);
}
return 0;
}
/**
* \internal
* Read a ZLIB compressed attr
*
* @param fs_file the file
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @return 1 on success, 0 on error
*/
static int hfs_file_read_zlib_attr(TSK_FS_FILE* fs_file,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize)
{
return hfs_file_read_compressed_attr(
fs_file, DECMPFS_TYPE_ZLIB_ATTR,
buffer, attributeLength, uncSize,
hfs_decompress_zlib_attr
);
}
/**
* \internal
* Read an LZVN compressed attr
*
* @param fs_file the file
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @return 1 on success, 0 on error
*/
static int hfs_file_read_lzvn_attr(TSK_FS_FILE* fs_file,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize)
{
return hfs_file_read_compressed_attr(
fs_file, DECMPFS_TYPE_LZVN_ATTR,
buffer, attributeLength, uncSize,
hfs_decompress_lzvn_attr
);
}
typedef struct {
TSK_FS_INFO *fs; // the HFS file system
TSK_FS_FILE *file; // the Attributes file, if open
hfs_btree_header_record *header; // the Attributes btree header record.
// For Convenience, unpacked values.
TSK_ENDIAN_ENUM endian;
uint32_t rootNode;
uint16_t nodeSize;
uint16_t maxKeyLen;
} ATTR_FILE_T;
/** \internal
* Open the Attributes file, and read the btree header record. Fill in the fields of the ATTR_FILE_T struct.
*
* @param fs -- the HFS file system
* @param header -- the header record struct
*
* @return 1 on error, 0 on success
*/
static uint8_t
open_attr_file(TSK_FS_INFO * fs, ATTR_FILE_T * attr_file)
{
ssize_t cnt; // will hold bytes read
hfs_btree_header_record *hrec;
// clean up any error messages that are lying around
tsk_error_reset();
if (fs == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("open_attr_file: fs is NULL");
return 1;
}
if (attr_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("open_attr_file: attr_file is NULL");
return 1;
}
// Open the Attributes File
attr_file->file =
tsk_fs_file_open_meta(fs, NULL, HFS_ATTRIBUTES_FILE_ID);
if (attr_file->file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr
("open_attr_file: could not open the Attributes file");
return 1;
}
// Allocate some space for the Attributes btree header record (which
// is passed back to the caller)
hrec = (hfs_btree_header_record *)
malloc(sizeof(hfs_btree_header_record));
if (hrec == NULL) {
tsk_error_set_errno(TSK_ERR_FS);
tsk_error_set_errstr
("open_attr_file: could not malloc space for Attributes header record");
return 1;
}
// Read the btree header record
cnt = tsk_fs_file_read(attr_file->file,
14,
(char *) hrec,
sizeof(hfs_btree_header_record), (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)sizeof(hfs_btree_header_record)) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr
("open_attr_file: could not open the Attributes file");
tsk_fs_file_close(attr_file->file);
free(hrec);
return 1;
}
// Fill in the fields of the attr_file struct (which was passed in by the caller)
attr_file->fs = fs;
attr_file->header = hrec;
attr_file->endian = fs->endian;
attr_file->nodeSize = tsk_getu16(attr_file->endian, hrec->nodesize);
attr_file->rootNode = tsk_getu32(attr_file->endian, hrec->rootNode);
attr_file->maxKeyLen = tsk_getu16(attr_file->endian, hrec->maxKeyLen);
return 0;
}
/** \internal
* Closes and frees the data structures associated with ATTR_FILE_T
*/
static uint8_t
close_attr_file(ATTR_FILE_T * attr_file)
{
if (attr_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr("close_attr_file: NULL attr_file arg");
return 1;
}
if (attr_file->file != NULL) {
tsk_fs_file_close(attr_file->file);
attr_file->file = NULL;
}
free(attr_file->header);
attr_file->header = NULL;
attr_file->rootNode = 0;
attr_file->nodeSize = 0;
// Note that we leave the fs component alone.
return 0;
}
static const char *
hfs_attrTypeName(uint32_t typeNum)
{
switch (typeNum) {
case TSK_FS_ATTR_TYPE_HFS_DEFAULT:
return "DFLT";
case TSK_FS_ATTR_TYPE_HFS_DATA:
return "DATA";
case TSK_FS_ATTR_TYPE_HFS_EXT_ATTR:
return "ExATTR";
case TSK_FS_ATTR_TYPE_HFS_COMP_REC:
return "CMPF";
case TSK_FS_ATTR_TYPE_HFS_RSRC:
return "RSRC";
default:
return "UNKN";
}
}
// TODO: Function description missing here no idea what it is supposed to return
// in which circumstances.
static uint8_t
hfs_load_extended_attrs(TSK_FS_FILE * fs_file,
unsigned char *isCompressed, unsigned char *cmpType,
uint64_t *uncompressedSize)
{
TSK_FS_INFO *fs = fs_file->fs_info;
uint64_t fileID;
ATTR_FILE_T attrFile;
uint8_t *nodeData;
TSK_ENDIAN_ENUM endian;
hfs_btree_node *nodeDescriptor; // The node descriptor
uint32_t nodeID; // The number or ID of the Attributes file node to read.
hfs_btree_key_attr *keyB; // ptr to the key of the Attr file record.
unsigned char done; // Flag to indicate that we are done looping over leaf nodes
uint16_t attribute_counter = 2; // The ID of the next attribute to be loaded.
HFS_INFO *hfs;
char *buffer = NULL; // buffer to hold the attribute
TSK_LIST *nodeIDs_processed = NULL; // Keep track of node IDs to prevent an infinite loop
ssize_t cnt; // count of chars read from file.
tsk_error_reset();
// The CNID (or inode number) of the file
// Note that in TSK such numbers are 64 bits, but in HFS+ they are only 32 bits.
fileID = fs_file->meta->addr;
if (fs == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_load_extended_attrs: NULL fs arg");
return 1;
}
hfs = (HFS_INFO *) fs;
if (!hfs->has_attributes_file) {
// No attributes file, and so, no extended attributes
return 0;
}
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Processing file %" PRIuINUM "\n",
fileID);
}
// Open the Attributes File
if (open_attr_file(fs, &attrFile)) {
error_returned
("hfs_load_extended_attrs: could not open Attributes file");
return 1;
}
// Is the Attributes file empty?
if (attrFile.rootNode == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Attributes file is empty\n");
close_attr_file(&attrFile);
*isCompressed = FALSE;
*cmpType = 0;
return 0;
}
// A place to hold one node worth of data
nodeData = (uint8_t *) malloc(attrFile.nodeSize);
if (nodeData == NULL) {
error_detected(TSK_ERR_AUX_MALLOC,
"hfs_load_extended_attrs: Could not malloc space for an Attributes file node");
goto on_error;
}
// Initialize these
*isCompressed = FALSE;
*cmpType = 0;
endian = attrFile.fs->endian;
// Start with the root node
nodeID = attrFile.rootNode;
// While loop, over nodes in path from root node to the correct LEAF node.
while (1) {
uint16_t numRec; // Number of records in the node
int recIndx; // index for looping over records
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Reading Attributes File node with ID %"
PRIu32 "\n", nodeID);
}
/* Make sure we do not get into an infinite loop */
if (tsk_list_find(nodeIDs_processed, nodeID)) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Infinite loop detected - trying to read node %" PRIu32 " which has already been processed", nodeID);
goto on_error;
}
/* Read the node */
cnt = tsk_fs_file_read(attrFile.file,
(TSK_OFF_T)nodeID * attrFile.nodeSize,
(char *) nodeData,
attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)attrFile.nodeSize) {
error_returned
("hfs_load_extended_attrs: Could not read in a node from the Attributes File");
goto on_error;
}
/* Save this node ID to the list of processed nodes */
if (tsk_list_add(&nodeIDs_processed, nodeID)) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Could not save nodeID to the list of processed nodes");
goto on_error;
}
/** Node has a:
* Descriptor
* Set of records
* Table at the end with pointers to the records
*/
// Parse the Node header
nodeDescriptor = (hfs_btree_node *) nodeData;
// If we are at a leaf node, then we have found the right node
if (nodeDescriptor->type == HFS_ATTR_NODE_LEAF) {
break;
}
// This had better be an INDEX node, if not its an error
else if (nodeDescriptor->type != HFS_ATTR_NODE_INDEX) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Reached a non-INDEX and non-LEAF node in searching the Attributes File");
goto on_error;
}
// OK, we are in an INDEX node. loop over the records to find the last one whose key is
// smaller than or equal to the desired key
numRec = tsk_getu16(endian, nodeDescriptor->num_rec);
if (numRec == 0) {
// This is wrong, there must always be at least 1 record in an INDEX node.
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs:Attributes File index node %"
PRIu32 " has zero records", nodeID);
goto on_error;
}
for (recIndx = 0; recIndx < numRec; ++recIndx) {
uint16_t keyLength;
int comp; // comparison result
char *compStr; // comparison result, as a string
uint8_t *recData; // pointer to the data part of the record
uint32_t keyFileID;
// The offset to the record is stored in table at end of node
uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is
uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry);
//uint8_t * nextRecOffsetData = &nodeData[attrFile.nodeSize - 2* (recIndx+2)];
// make sure the record and first fields are in the buffer
if (recOffset + 14 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute (offset too big)");
goto on_error;
}
// Pointer to first byte of record
uint8_t *recordBytes = &nodeData[recOffset];
// Cast that to the Attributes file key (n.b., the key is the first thing in the record)
keyB = (hfs_btree_key_attr *) recordBytes;
// Is this key less than what we are seeking?
//int comp = comp_attr_key(endian, keyB, fileID, attrName, startBlock);
keyFileID = tsk_getu32(endian, keyB->file_id);
if (keyFileID < fileID) {
comp = -1;
compStr = "less than";
}
else if (keyFileID > fileID) {
comp = 1;
compStr = "greater than";
}
else {
comp = 0;
compStr = "equal to";
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: INDEX record %d, fileID %"
PRIu32 " is %s the file ID we are seeking, %" PRIu32
".\n", recIndx, keyFileID, compStr, fileID);
if (comp > 0) {
// The key of this record is greater than what we are seeking
if (recIndx == 0) {
// This is the first record, so no records are appropriate
// Nothing in this btree will match. We can stop right here.
goto on_exit;
}
// This is not the first record, so, the previous record's child is the one we want.
break;
}
// CASE: key in this record matches the key we are seeking. The previous record's child
// is the one we want. However, if this is the first record, then we want THIS record's child.
if (comp == 0 && recIndx != 0) {
break;
}
// Extract the child node ID from the record data (stored after the key)
keyLength = tsk_getu16(endian, keyB->key_len);
// make sure the fields we care about are still in the buffer
// +2 is because key_len doesn't include its own length
// +4 is because of the amount of data we read from the data
if (recOffset + keyLength + 2 + 4 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
recData = &recordBytes[keyLength + 2];
// Data must start on an even offset from the beginning of the record.
// So, correct this if needed.
if ((recData - recordBytes) % 2) {
recData += 1;
}
// The next four bytes should be the Node ID of the child of this node.
nodeID = tsk_getu32(endian, recData);
// At this point, either comp<0 or comp=0 && recIndx=0. In the latter case we want to
// descend to the child of this node, so we break.
if (recIndx == 0 && comp == 0) {
break;
}
// CASE: key in this record is less than key we seek. comp < 0
// So, continue looping over records in this node.
} // END loop over records
} // END while loop over Nodes in path from root to LEAF node
// At this point nodeData holds the contents of a LEAF node with the right range of keys
// and nodeDescriptor points to the descriptor of that node.
// Loop over successive LEAF nodes, starting with this one
done = FALSE;
while (!done) {
uint16_t numRec; // number of records
unsigned int recIndx; // index for looping over records
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Attributes File LEAF Node %"
PRIu32 ".\n", nodeID);
numRec = tsk_getu16(endian, nodeDescriptor->num_rec);
// Note, leaf node could have one (or maybe zero) records
// Loop over the records in this node
for (recIndx = 0; recIndx < numRec; ++recIndx) {
// The offset to the record is stored in table at end of node
uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is
uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry);
int comp; // comparison result
char *compStr; // comparison result as a string
uint32_t keyFileID;
// make sure the record and first fields are in the buffer
if (recOffset + 14 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute (offset too big)");
goto on_error;
}
// Pointer to first byte of record
uint8_t *recordBytes = &nodeData[recOffset];
// Cast that to the Attributes file key
keyB = (hfs_btree_key_attr *) recordBytes;
// Compare recordBytes key to the key that we are seeking
keyFileID = tsk_getu32(endian, keyB->file_id);
//fprintf(stdout, " Key file ID = %lu\n", keyFileID);
if (keyFileID < fileID) {
comp = -1;
compStr = "less than";
}
else if (keyFileID > fileID) {
comp = 1;
compStr = "greater than";
}
else {
comp = 0;
compStr = "equal to";
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: LEAF Record key file ID %"
PRIu32 " is %s the desired file ID %" PRIu32 "\n",
keyFileID, compStr, fileID);
// Are they the same?
if (comp == 0) {
// Yes, so load this attribute
uint8_t *recData; // pointer to the data part of the recordBytes
hfs_attr_data *attrData;
uint32_t attributeLength;
uint32_t nameLength;
uint32_t recordType;
uint16_t keyLength;
int conversionResult;
char nameBuff[HFS_MAX_ATTR_NAME_LEN_UTF8_B+1];
TSK_FS_ATTR_TYPE_ENUM attrType;
TSK_FS_ATTR *fs_attr; // Points to the attribute to be loaded.
keyLength = tsk_getu16(endian, keyB->key_len);
// make sure the fields we care about are still in the buffer
// +2 because key_len doesn't include its own length
// +16 for the amount of data we'll read from data
if (recOffset + keyLength + 2 + 16 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
recData = &recordBytes[keyLength + 2];
// Data must start on an even offset from the beginning of the record.
// So, correct this if needed.
if ((recData - recordBytes) % 2) {
recData += 1;
}
attrData = (hfs_attr_data *) recData;
// Check we can process the record type before allocating memory
recordType = tsk_getu32(endian, attrData->record_type);
if (recordType != HFS_ATTR_RECORD_INLINE_DATA) {
error_detected(TSK_ERR_FS_UNSUPTYPE,
"hfs_load_extended_attrs: Unsupported record type: (%d)",
recordType);
goto on_error;
}
// This is the length of the useful data, not including the record header
attributeLength = tsk_getu32(endian, attrData->attr_size);
// Check the attribute fits in the node
//if (recordType != HFS_ATTR_RECORD_INLINE_DATA) {
if (recOffset + keyLength + 2 + attributeLength > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
// attr_name_len is in UTF_16 chars
nameLength = tsk_getu16(endian, keyB->attr_name_len);
if (2 * nameLength > HFS_MAX_ATTR_NAME_LEN_UTF16_B) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: Name length in bytes (%d) > max name length in bytes (%d).",
2*nameLength, HFS_MAX_ATTR_NAME_LEN_UTF16_B);
goto on_error;
}
if ((int32_t)(2*nameLength) > keyLength - 12) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: Name length in bytes (%d) > remaining struct length (%d).",
2*nameLength, keyLength - 12);
goto on_error;
}
buffer = tsk_malloc(attributeLength);
if (buffer == NULL) {
error_detected(TSK_ERR_AUX_MALLOC,
"hfs_load_extended_attrs: Could not malloc space for the attribute.");
goto on_error;
}
memcpy(buffer, attrData->attr_data, attributeLength);
// Use the "attr_name" part of the key as the attribute name
// but must convert to UTF8. Unfortunately, there does not seem to
// be any easy way to determine how long the converted string will
// be because UTF8 is a variable length encoding. However, the longest
// it will be is 3 * the max number of UTF16 code units. Add one for null
// termination. (thanks Judson!)
conversionResult = hfs_UTF16toUTF8(fs, keyB->attr_name,
nameLength, nameBuff, HFS_MAX_ATTR_NAME_LEN_UTF8_B+1, 0);
if (conversionResult != 0) {
error_returned
("-- hfs_load_extended_attrs could not convert the attr_name in the btree key into a UTF8 attribute name");
goto on_error;
}
// What is the type of this attribute? If it is a compression record, then
// use TSK_FS_ATTR_TYPE_HFS_COMP_REC. Else, use TSK_FS_ATTR_TYPE_HFS_EXT_ATTR
// Only "inline data" kind of record is handled.
if (strcmp(nameBuff, "com.apple.decmpfs") == 0 &&
tsk_getu32(endian, attrData->record_type) == HFS_ATTR_RECORD_INLINE_DATA) {
// Now, look at the compression record
DECMPFS_DISK_HEADER *cmph = (DECMPFS_DISK_HEADER *) buffer;
*cmpType =
tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type);
uint64_t uncSize = tsk_getu64(TSK_LIT_ENDIAN,
cmph->uncompressed_size);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: This attribute is a compression record.\n");
attrType = TSK_FS_ATTR_TYPE_HFS_COMP_REC;
*isCompressed = TRUE; // The data is governed by a compression record (but might not be compressed)
*uncompressedSize = uncSize;
switch (*cmpType) {
// Data is inline. We will load the uncompressed
// data as a resident attribute.
case DECMPFS_TYPE_ZLIB_ATTR:
if (!hfs_file_read_zlib_attr(
fs_file, buffer, attributeLength, uncSize))
{
goto on_error;
}
break;
case DECMPFS_TYPE_LZVN_ATTR:
if (!hfs_file_read_lzvn_attr(
fs_file, buffer, attributeLength, uncSize))
{
goto on_error;
}
break;
// Data is compressed in the resource fork
case DECMPFS_TYPE_ZLIB_RSRC:
case DECMPFS_TYPE_LZVN_RSRC:
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Compressed data is in the file Resource Fork.\n", __func__);
break;
}
}
else { // Attrbute name is NOT com.apple.decmpfs
attrType = TSK_FS_ATTR_TYPE_HFS_EXT_ATTR;
} // END if attribute name is com.apple.decmpfs ELSE clause
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_RES)) == NULL) {
error_returned(" - hfs_load_extended_attrs");
goto on_error;
}
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: loading attribute %s, type %u (%s)\n",
nameBuff, (uint32_t) attrType,
hfs_attrTypeName((uint32_t) attrType));
}
// set the details in the fs_attr structure
if (tsk_fs_attr_set_str(fs_file, fs_attr, nameBuff,
attrType, attribute_counter, buffer,
attributeLength)) {
error_returned(" - hfs_load_extended_attrs");
goto on_error;
}
free(buffer);
buffer = NULL;
++attribute_counter;
} // END if comp == 0
if (comp == 1) {
// since this record key is greater than our search key, all
// subsequent records will also be greater.
done = TRUE;
break;
}
} // END loop over records in one LEAF node
/*
* We get to this point if either:
*
* 1. We finish the loop over records and we are still loading attributes
* for the given file. In this case we are NOT done, and must read in
* the next leaf node, and process its records. The following code
* loads the next leaf node before we return to the top of the loop.
*
* 2. We "broke" out of the loop over records because we found a key that
* whose file ID is greater than the one we are working on. In that case
* we are done. The following code does not run, and we exit the
* while loop over successive leaf nodes.
*/
if (!done) {
// We did not finish loading the attributes when we got to the end of that node,
// so we must get the next node, and continue.
// First determine the nodeID of the next LEAF node
uint32_t newNodeID = tsk_getu32(endian, nodeDescriptor->flink);
//fprintf(stdout, "Next Node ID = %u\n", newNodeID);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Processed last record of THIS node, still gathering attributes.\n");
// If we are at the very last leaf node in the btree, then
// this "flink" will be zero. We break out of this loop over LEAF nodes.
if (newNodeID == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: But, there are no more leaf nodes, so we are done.\n");
break;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Reading the next LEAF node %"
PRIu32 ".\n", nodeID);
nodeID = newNodeID;
cnt = tsk_fs_file_read(attrFile.file,
nodeID * attrFile.nodeSize,
(char *) nodeData,
attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)attrFile.nodeSize) {
error_returned
("hfs_load_extended_attrs: Could not read in the next LEAF node from the Attributes File btree");
goto on_error;
}
// Parse the Node header
nodeDescriptor = (hfs_btree_node *) nodeData;
// If we are NOT leaf node, then this is an error
if (nodeDescriptor->type != HFS_ATTR_NODE_LEAF) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: found a non-LEAF node as a successor to a LEAF node");
goto on_error;
}
} // END if(! done)
} // END while(! done) loop over successive LEAF nodes
on_exit:
free(nodeData);
tsk_list_free(nodeIDs_processed);
close_attr_file(&attrFile);
return 0;
on_error:
free(buffer);
free(nodeData);
tsk_list_free(nodeIDs_processed);
close_attr_file(&attrFile);
return 1;
}
typedef struct RES_DESCRIPTOR {
char type[5]; // type is really 4 chars, but we will null-terminate
uint16_t id;
uint32_t offset;
uint32_t length;
char *name; // NULL if a name is not defined for this resource
struct RES_DESCRIPTOR *next;
} RES_DESCRIPTOR;
void
free_res_descriptor(RES_DESCRIPTOR * rd)
{
RES_DESCRIPTOR *nxt;
if (rd == NULL)
return;
nxt = rd->next;
free(rd->name);
free(rd);
free_res_descriptor(nxt); // tail recursive
}
/**
* The purpose of this function is to parse the resource fork of a file, and to return
* a data structure that is, in effect, a table of contents for the resource fork. The
* data structure is a null-terminated linked list of entries. Each one describes one
* resource. If the resource fork is empty, or if there is not a resource fork at all,
* or an error occurs, this function returns NULL.
*
* A non-NULL answer should be freed by the caller, using free_res_descriptor.
*
*/
static RES_DESCRIPTOR *
hfs_parse_resource_fork(TSK_FS_FILE * fs_file)
{
RES_DESCRIPTOR *result = NULL;
RES_DESCRIPTOR *last = NULL;
TSK_FS_INFO *fs_info;
hfs_fork *fork_info;
hfs_fork *resForkInfo;
uint64_t resSize;
const TSK_FS_ATTR *rAttr;
hfs_resource_fork_header rfHeader;
hfs_resource_fork_header *resHead;
uint32_t dataOffset;
uint32_t mapOffset;
uint32_t mapLength;
char *map;
ssize_t attrReadResult;
ssize_t attrReadResult1;
ssize_t attrReadResult2;
hfs_resource_fork_map_header *mapHdr;
uint16_t typeListOffset;
uint16_t nameListOffset;
unsigned char hasNameList;
char *nameListBegin = NULL;
hfs_resource_type_list *typeList;
uint16_t numTypes;
hfs_resource_type_list_item *tlItem;
int mindx; // index for looping over resource types
if (fs_file == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: null fs_file");
return NULL;
}
if (fs_file->meta == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: fs_file has null metadata");
return NULL;
}
if (fs_file->meta->content_ptr == NULL) {
if (tsk_verbose)
fprintf(stderr,
"hfs_parse_resource_fork: fs_file has null fork data structures, so no resources.\n");
return NULL;
}
// Extract the fs
fs_info = fs_file->fs_info;
if (fs_info == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: null fs within fs_info");
return NULL;
}
// Try to look at the Resource Fork for an HFS+ file
// Should be able to cast this to hfs_fork *
fork_info = (hfs_fork *) fs_file->meta->content_ptr; // The data fork
// The resource fork is the second one.
resForkInfo = &fork_info[1];
resSize = tsk_getu64(fs_info->endian, resForkInfo->logic_sz);
//uint32_t numBlocks = tsk_getu32(fs_info->endian, resForkInfo->total_blk);
//uint32_t clmpSize = tsk_getu32(fs_info->endian, resForkInfo->clmp_sz);
// Hmm, certainly no resources here!
if (resSize == 0) {
return NULL;
}
// OK, resource size must be > 0
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
("hfs_parse_resource_fork: could not get the resource fork attribute");
return NULL;
}
// JUST read the resource fork header
attrReadResult1 =
tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader,
sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult1 < 0
|| attrReadResult1 != sizeof(hfs_resource_fork_header)) {
error_returned
(" hfs_parse_resource_fork: trying to read the resource fork header");
return NULL;
}
// Begin to parse the resource fork
resHead = &rfHeader;
dataOffset = tsk_getu32(fs_info->endian, resHead->dataOffset);
mapOffset = tsk_getu32(fs_info->endian, resHead->mapOffset);
//uint32_t dataLength = tsk_getu32(fs_info->endian, resHead->dataLength);
mapLength = tsk_getu32(fs_info->endian, resHead->mapLength);
// Read in the WHOLE map
map = (char *) tsk_malloc(mapLength);
if (map == NULL) {
error_returned
("- hfs_parse_resource_fork: could not allocate space for the resource fork map");
return NULL;
}
attrReadResult =
tsk_fs_attr_read(rAttr, (uint64_t) mapOffset, map,
(size_t) mapLength, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult < 0 || attrReadResult != (ssize_t) mapLength) {
error_returned
("- hfs_parse_resource_fork: could not read the map");
free(map);
return NULL;
}
mapHdr = (hfs_resource_fork_map_header *) map;
typeListOffset = tsk_getu16(fs_info->endian, mapHdr->typeListOffset);
nameListOffset = tsk_getu16(fs_info->endian, mapHdr->nameListOffset);
if (nameListOffset >= mapLength || nameListOffset == 0) {
hasNameList = FALSE;
}
else {
hasNameList = TRUE;
nameListBegin = map + nameListOffset;
}
typeList = (hfs_resource_type_list *) (map + typeListOffset);
numTypes = tsk_getu16(fs_info->endian, typeList->typeCount) + 1;
for (mindx = 0; mindx < numTypes; ++mindx) {
uint16_t numRes;
uint16_t refOff;
int pindx; // index for looping over resources
uint16_t rID;
uint32_t rOffset;
tlItem = &(typeList->type[mindx]);
numRes = tsk_getu16(fs_info->endian, tlItem->count) + 1;
refOff = tsk_getu16(fs_info->endian, tlItem->offset);
for (pindx = 0; pindx < numRes; ++pindx) {
int16_t nameOffset;
char *nameBuffer;
RES_DESCRIPTOR *rsrc;
char lenBuff[4]; // first 4 bytes of a resource encodes its length
uint32_t rLen; // Resource length
hfs_resource_refListItem *item =
((hfs_resource_refListItem *) (((uint8_t *) typeList) +
refOff)) + pindx;
nameOffset = tsk_gets16(fs_info->endian, item->resNameOffset);
nameBuffer = NULL;
if (hasNameList && nameOffset != -1) {
char *name = nameListBegin + nameOffset;
uint8_t nameLen = (uint8_t) name[0];
nameBuffer = tsk_malloc(nameLen + 1);
if (nameBuffer == NULL) {
error_returned
("hfs_parse_resource_fork: allocating space for the name of a resource");
free_res_descriptor(result);
return NULL;
}
memcpy(nameBuffer, name + 1, nameLen);
nameBuffer[nameLen] = (char) 0;
}
else {
nameBuffer = tsk_malloc(7);
if (nameBuffer == NULL) {
error_returned
("hfs_parse_resource_fork: allocating space for the (null) name of a resource");
free_res_descriptor(result);
return NULL;
}
memcpy(nameBuffer, "<none>", 6);
nameBuffer[6] = (char) 0;
}
rsrc = (RES_DESCRIPTOR *) tsk_malloc(sizeof(RES_DESCRIPTOR));
if (rsrc == NULL) {
error_returned
("hfs_parse_resource_fork: space for a resource descriptor");
free_res_descriptor(result);
return NULL;
}
// Build the linked list
if (result == NULL)
result = rsrc;
if (last != NULL)
last->next = rsrc;
last = rsrc;
rsrc->next = NULL;
rID = tsk_getu16(fs_info->endian, item->resID);
rOffset =
tsk_getu24(fs_info->endian,
item->resDataOffset) + dataOffset;
// Just read the first four bytes of the resource to get its length. It MUST
// be at least 4 bytes long
attrReadResult2 = tsk_fs_attr_read(rAttr, (uint64_t) rOffset,
lenBuff, (size_t) 4, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult2 != 4) {
error_returned
("- hfs_parse_resource_fork: could not read the 4-byte length at beginning of resource");
free_res_descriptor(result);
return NULL;
}
rLen = tsk_getu32(TSK_BIG_ENDIAN, lenBuff); //TODO
rsrc->id = rID;
rsrc->offset = rOffset + 4;
memcpy(rsrc->type, tlItem->type, 4);
rsrc->type[4] = (char) 0;
rsrc->length = rLen;
rsrc->name = nameBuffer;
} // END loop over resources of one type
} // END loop over resource types
return result;
}
static uint8_t
hfs_load_attrs(TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs;
HFS_INFO *hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
hfs_fork *forkx;
unsigned char resource_fork_has_contents = FALSE;
unsigned char compression_flag = FALSE;
unsigned char isCompressed = FALSE;
unsigned char compDataInRSRCFork = FALSE;
unsigned char cmpType = 0;
uint64_t uncompressedSize;
uint64_t logicalSize; // of a fork
// clean up any error messages that are lying around
tsk_error_reset();
if ((fs_file == NULL) || (fs_file->meta == NULL)
|| (fs_file->fs_info == NULL)) {
error_detected(TSK_ERR_FS_ARG,
"hfs_load_attrs: fs_file or meta is NULL");
return 1;
}
fs = (TSK_FS_INFO *) fs_file->fs_info;
hfs = (HFS_INFO *) fs;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Processing file %" PRIuINUM "\n",
fs_file->meta->addr);
// see if we have already loaded the runs
if (fs_file->meta->attr_state == TSK_FS_META_ATTR_STUDIED) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Attributes already loaded\n");
return 0;
}
else if (fs_file->meta->attr_state == TSK_FS_META_ATTR_ERROR) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Previous attempt to load attributes resulted in error\n");
return 1;
}
// Now (re)-initialize the attrlist that will hold the list of attributes
if (fs_file->meta->attr != NULL) {
tsk_fs_attrlist_markunused(fs_file->meta->attr);
}
else if (fs_file->meta->attr == NULL) {
fs_file->meta->attr = tsk_fs_attrlist_alloc();
}
/****************** EXTENDED ATTRIBUTES *******************************/
// We do these first, so that we can detect the mode of compression, if
// any. We need to know that mode in order to handle the forks.
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the HFS+ extended attributes\n");
if (hfs_load_extended_attrs(fs_file, &isCompressed,
&cmpType, &uncompressedSize)) {
error_returned(" - hfs_load_attrs A");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
// TODO: What about DECMPFS_TYPE_RAW_RSRC?
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_RSRC:
case DECMPFS_TYPE_LZVN_RSRC:
compDataInRSRCFork = TRUE;
break;
default:
compDataInRSRCFork = FALSE;
break;
}
if (isCompressed) {
fs_file->meta->size = uncompressedSize;
}
// This is the flag indicating compression, from the Catalog File record.
compression_flag = (fs_file->meta->flags & TSK_FS_META_FLAG_COMP) != 0;
if (compression_flag && !isCompressed) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, HFS marks this as a"
" compressed file, but no compression record was found.\n");
}
if (isCompressed && !compression_flag) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, this file has a compression"
" record, but the HFS compression flag is not set.\n");
}
/************* FORKS (both) ************************************/
// Process the data and resource forks. We only do this if the
// fork data structures are non-null, so test that:
if (fs_file->meta->content_ptr != NULL) {
/************** DATA FORK STUFF ***************************/
// Get the data fork data-structure
forkx = (hfs_fork *) fs_file->meta->content_ptr;
// If this is a compressed file, then either this attribute is already loaded
// because the data was in the compression record, OR
// the compressed data is in the resource fork. We will load those runs when
// we handle the resource fork.
if (!isCompressed) {
// We only load this attribute if this fork has non-zero length
// or if this is a REG or LNK file. Otherwise, we skip
logicalSize = tsk_getu64(fs->endian, forkx->logic_sz);
if (logicalSize > 0 ||
fs_file->meta->type == TSK_FS_META_TYPE_REG ||
fs_file->meta->type == TSK_FS_META_TYPE_LNK) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the data fork attribute\n");
// get an attribute structure to store the data in
if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_load_attrs");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
if (logicalSize > 0) {
// Convert runs of blocks to the TSK internal form
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_load_attrs");
return 1;
}
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run,
"", TSK_FS_ATTR_TYPE_HFS_DATA,
HFS_FS_ATTR_ID_DATA, logicalSize, logicalSize,
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size, 0,
0)) {
error_returned(" - hfs_load_attrs (DATA)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr,
TRUE)) {
error_returned(" - hfs_load_attrs B");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
}
else {
// logicalSize == 0, but this is either a REG or LNK file
// so, it should have a DATA fork attribute of zero length.
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
0, 0, 0, 0, 0)) {
error_returned(" - hfs_load_attrs (non-file)");
return 1;
}
}
} // END logicalSize>0 or REG or LNK file type
} // END if not Compressed
/************** RESOURCE FORK STUFF ************************************/
// Get the resource fork.
//Note that content_ptr points to an array of two
// hfs_fork data structures, the second of which
// describes the blocks of the resource fork.
forkx = &((hfs_fork *) fs_file->meta->content_ptr)[1];
logicalSize = tsk_getu64(fs->endian, forkx->logic_sz);
// Skip if the length of the resource fork is zero
if (logicalSize > 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the resource fork\n");
resource_fork_has_contents = TRUE;
// get an attribute structure to store the resource fork data in. We will
// reuse the fs_attr variable, since we are done with the data fork.
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_load_attrs (RSRC)");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
// convert the resource fork to the TSK format
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_load_attrs");
return 1;
}
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "RSRC",
TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC,
tsk_getu64(fs->endian, forkx->logic_sz),
tsk_getu64(fs->endian, forkx->logic_sz),
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size, 0, 0)) {
error_returned(" - hfs_load_attrs (RSRC)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs for the resource fork.
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr, FALSE)) {
error_returned(" - hfs_load_attrs C");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
if (isCompressed && compDataInRSRCFork) {
// OK, we are going to load those same resource fork blocks as the "DATA"
// attribute, but will mark it as compressed.
// get an attribute structure to store the resource fork data in. We will
// reuse the fs_attr variable, since we are done with the data fork.
if (tsk_verbose)
tsk_fprintf(stderr,
"File is compressed with data in the resource fork. "
"Loading the default DATA attribute.\n");
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA)");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_RSRC:
#ifdef HAVE_LIBZ
fs_attr->w = hfs_attr_walk_zlib_rsrc;
fs_attr->r = hfs_file_read_zlib_rsrc;
#else
// We don't have zlib, so the uncompressed data is not
// available to us; however, we must have a default DATA
// attribute, or icat will misbehave.
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: No zlib compression library, so setting a zero-length default DATA attribute.\n");
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "DATA",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, 0,
0, 0, 0, 0)) {
error_returned(" - hfs_load_attrs (non-file)");
return 1;
}
#endif
break;
case DECMPFS_TYPE_LZVN_RSRC:
fs_attr->w = hfs_attr_walk_lzvn_rsrc;
fs_attr->r = hfs_file_read_lzvn_rsrc;
break;
}
// convert the resource fork to the TSK format
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned
(" - hfs_load_attrs, RSRC fork as DATA fork");
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Loading RSRC fork block runs as the default DATA attribute.\n");
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "DECOMP",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
logicalSize,
logicalSize,
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size,
TSK_FS_ATTR_COMP | TSK_FS_ATTR_NONRES, 0)) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs for the resource fork.
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr, FALSE)) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: setting the \"special\" function pointers to inflate compressed data.\n");
}
} // END resource fork size > 0
} // END the fork data structures are non-NULL
if (isCompressed && compDataInRSRCFork && !resource_fork_has_contents) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, compression record claims that compressed data"
" is in the Resource Fork, but that fork is empty or non-existent.\n");
}
// Finish up.
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/** \internal
* Get allocation status of file system block.
* adapted from IsAllocationBlockUsed from:
* http://developer.apple.com/technotes/tn/tn1150.html
*
* @param hfs File system being analyzed
* @param b Block address
* @returns 1 if allocated, 0 if not, -1 on error
*/
static int8_t
hfs_block_is_alloc(HFS_INFO * hfs, TSK_DADDR_T a_addr)
{
TSK_FS_INFO *fs = &(hfs->fs_info);
TSK_OFF_T b;
size_t b2;
// lazy loading
if (hfs->blockmap_file == NULL) {
if ((hfs->blockmap_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_ALLOCATION_FILE_ID)) == NULL) {
tsk_error_errstr2_concat(" - Loading blockmap file");
return -1;
}
/* cache the data attribute */
hfs->blockmap_attr =
tsk_fs_attrlist_get(hfs->blockmap_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->blockmap_attr) {
tsk_error_errstr2_concat
(" - Data Attribute not found in Blockmap File");
return -1;
}
hfs->blockmap_cache_start = -1;
hfs->blockmap_cache_len = 0;
}
// get the byte offset
b = (TSK_OFF_T) a_addr / 8;
if (b > hfs->blockmap_file->meta->size) {
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("hfs_block_is_alloc: block %" PRIuDADDR
" is too large for bitmap (%" PRIuOFF ")", a_addr,
hfs->blockmap_file->meta->size);
return -1;
}
// see if it is in the cache
if ((hfs->blockmap_cache_start == -1)
|| (hfs->blockmap_cache_start > b)
|| (hfs->blockmap_cache_start + hfs->blockmap_cache_len <= (size_t) b)) {
ssize_t cnt = tsk_fs_attr_read(hfs->blockmap_attr, b,
hfs->blockmap_cache,
sizeof(hfs->blockmap_cache), 0);
if (cnt < 1) {
tsk_error_set_errstr2
("hfs_block_is_alloc: Error reading block bitmap at offset %"
PRIuOFF, b);
return -1;
}
hfs->blockmap_cache_start = b;
hfs->blockmap_cache_len = cnt;
}
b2 = (size_t) (b - hfs->blockmap_cache_start);
return (hfs->blockmap_cache[b2] & (1 << (7 - (a_addr % 8)))) != 0;
}
TSK_FS_BLOCK_FLAG_ENUM
hfs_block_getflags(TSK_FS_INFO * a_fs, TSK_DADDR_T a_addr)
{
return (hfs_block_is_alloc((HFS_INFO *) a_fs, a_addr) == 1) ?
TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC;
}
static uint8_t
hfs_block_walk(TSK_FS_INFO * fs, TSK_DADDR_T start_blk,
TSK_DADDR_T end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM flags,
TSK_FS_BLOCK_WALK_CB action, void *ptr)
{
char *myname = "hfs_block_walk";
HFS_INFO *hfs = (HFS_INFO *) fs;
TSK_FS_BLOCK *fs_block;
TSK_DADDR_T addr;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: start_blk: %" PRIuDADDR " end_blk: %"
PRIuDADDR " flags: %" PRIu32 "\n", myname, start_blk, end_blk,
flags);
// clean up any error messages that are lying around
tsk_error_reset();
/*
* Sanity checks.
*/
if (start_blk < fs->first_block || start_blk > fs->last_block) {
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("%s: invalid start block number: %" PRIuDADDR
"", myname, start_blk);
return 1;
}
if (end_blk < fs->first_block || end_blk > fs->last_block) {
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("%s: invalid last block number: %" PRIuDADDR
"", myname, end_blk);
return 1;
}
if (start_blk > end_blk)
XSWAP(start_blk, end_blk);
/* Sanity check on flags -- make sure at least one ALLOC is set */
if (((flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) &&
((flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) {
flags |=
(TSK_FS_BLOCK_WALK_FLAG_ALLOC |
TSK_FS_BLOCK_WALK_FLAG_UNALLOC);
}
if (((flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) &&
((flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) {
flags |=
(TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META);
}
if ((fs_block = tsk_fs_block_alloc(fs)) == NULL) {
return 1;
}
/*
* Iterate
*/
for (addr = start_blk; addr <= end_blk; ++addr) {
int retval;
int myflags;
/* identify if the block is allocated or not */
myflags = hfs_block_is_alloc(hfs, addr) ?
TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC;
// test if we should call the callback with this one
if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC)
&& (!(flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC)))
continue;
else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC)
&& (!(flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC)))
continue;
if (flags & TSK_FS_BLOCK_WALK_FLAG_AONLY)
myflags |= TSK_FS_BLOCK_FLAG_AONLY;
if (tsk_fs_block_get_flag(fs, fs_block, addr,
(TSK_FS_BLOCK_FLAG_ENUM) myflags) == NULL) {
tsk_fs_block_free(fs_block);
return 1;
}
retval = action(fs_block, ptr);
if (TSK_WALK_STOP == retval) {
break;
}
else if (TSK_WALK_ERROR == retval) {
tsk_fs_block_free(fs_block);
return 1;
}
}
tsk_fs_block_free(fs_block);
return 0;
}
uint8_t
hfs_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 action, void *ptr)
{
TSK_INUM_T inum;
TSK_FS_FILE *fs_file;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_inode_walk: start_inum: %" PRIuINUM " end_inum: %"
PRIuINUM " flags: %" PRIu32 "\n", start_inum, end_inum, flags);
/*
* Sanity checks.
*/
if (start_inum < fs->first_inum || start_inum > fs->last_inum) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("inode_walk: Start inode: %" PRIuINUM "",
start_inum);
return 1;
}
else if (end_inum < fs->first_inum || end_inum > fs->last_inum
|| end_inum < start_inum) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("inode_walk: End inode: %" PRIuINUM "",
end_inum);
return 1;
}
/* If ORPHAN is wanted, then make sure that the flags are correct */
if (flags & TSK_FS_META_FLAG_ORPHAN) {
flags |= TSK_FS_META_FLAG_UNALLOC;
flags &= ~TSK_FS_META_FLAG_ALLOC;
flags |= TSK_FS_META_FLAG_USED;
flags &= ~TSK_FS_META_FLAG_UNUSED;
}
else {
if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) &&
((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) {
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_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(HFS_FILE_CONTENT_LEN)) == NULL)
return 1;
if (start_inum > end_inum)
XSWAP(start_inum, end_inum);
for (inum = start_inum; inum <= end_inum; ++inum) {
int retval;
if (hfs_inode_lookup(fs, fs_file, inum)) {
// deleted files may not exist in the catalog
if (tsk_error_get_errno() == TSK_ERR_FS_INODE_NUM) {
tsk_error_reset();
continue;
}
else {
return 1;
}
}
if ((fs_file->meta->flags & flags) != fs_file->meta->flags)
continue;
/* call action */
retval = action(fs_file, 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;
}
}
tsk_fs_file_close(fs_file);
return 0;
}
/* return the name of a file at a given inode
* in a newly-allocated string, or NULL on error
*/
char *
hfs_get_inode_name(TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
HFS_ENTRY entry;
char *fn = NULL;
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return NULL;
fn = malloc(HFS_MAXNAMLEN + 1);
if (fn == NULL)
return NULL;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH)) {
free(fn);
return NULL;
}
return fn;
}
/* print the name of a file at a given inode
* returns 0 on success, 1 on error */
static uint8_t
print_inode_name(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
char fn[HFS_MAXNAMLEN + 1];
HFS_ENTRY entry;
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return 1;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH))
return 1;
tsk_fprintf(hFile, "%s", fn);
return 0;
}
/* tail recursive function to print a path... prints the parent path, then
* appends / and the name of the given inode. prints nothing for root
* returns 0 on success, 1 on failure
*/
static uint8_t
print_parent_path(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
char fn[HFS_MAXNAMLEN + 1];
HFS_ENTRY entry;
if (inum == HFS_ROOT_INUM)
return 0;
if (inum <= HFS_ROOT_INUM) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr("print_parent_path: out-of-range inode %"
PRIuINUM, inum);
return 1;
}
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return 1;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1,
HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL))
return 1;
if (print_parent_path(hFile, fs, (TSK_INUM_T) tsk_getu32(fs->endian,
entry.thread.parent_cnid)))
return 1;
tsk_fprintf(hFile, "/%s", fn);
return 0;
}
/* print the file name corresponding to an inode, in brackets after a space.
* uses Unix path conventions, and does not include the volume name.
* returns 0 on success, 1 on failure
*/
static uint8_t
print_inode_file(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
tsk_fprintf(hFile, " [");
if (inum == HFS_ROOT_INUM)
tsk_fprintf(hFile, "/");
else {
if (print_parent_path(hFile, fs, inum)) {
tsk_fprintf(hFile, "unknown]");
return 1;
}
}
tsk_fprintf(hFile, "]");
return 0;
}
static uint8_t
hfs_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 for HFS yet");
return 1;
}
static uint8_t
hfs_fsstat(TSK_FS_INFO * fs, FILE * hFile)
{
// char *myname = "hfs_fsstat";
HFS_INFO *hfs = (HFS_INFO *) fs;
hfs_plus_vh *sb = hfs->fs;
time_t mac_time;
TSK_INUM_T inode;
char timeBuf[128];
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_fstat: called\n");
tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "File System Type: ");
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSPLUS)
tsk_fprintf(hFile, "HFS+\n");
else if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX)
tsk_fprintf(hFile, "HFSX\n");
else
tsk_fprintf(hFile, "Unknown\n");
// print name and number of version
tsk_fprintf(hFile, "File System Version: ");
switch (tsk_getu16(fs->endian, hfs->fs->version)) {
case 4:
tsk_fprintf(hFile, "HFS+\n");
break;
case 5:
tsk_fprintf(hFile, "HFSX\n");
break;
default:
tsk_fprintf(hFile, "Unknown (%" PRIu16 ")\n",
tsk_getu16(fs->endian, hfs->fs->version));
break;
}
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX) {
tsk_fprintf(hFile, "Case Sensitive: %s\n",
hfs->is_case_sensitive ? "yes" : "no");
}
if (hfs->hfs_wrapper_offset > 0) {
tsk_fprintf(hFile,
"File system is embedded in an HFS wrapper at offset %" PRIuOFF
"\n", hfs->hfs_wrapper_offset);
}
tsk_fprintf(hFile, "\nVolume Name: ");
if (print_inode_name(hFile, fs, HFS_ROOT_INUM))
return 1;
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Volume Identifier: %08" PRIx32 "%08" PRIx32 "\n",
tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID1]),
tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID2]));
// print last mounted info
tsk_fprintf(hFile, "\nLast Mounted By: ");
if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSPLUS)
tsk_fprintf(hFile, "Mac OS X\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSJ)
tsk_fprintf(hFile, "Mac OS X, Journaled\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSK)
tsk_fprintf(hFile, "failed journal replay\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSCK)
tsk_fprintf(hFile, "fsck_hfs\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_OS89)
tsk_fprintf(hFile, "Mac OS 8.1 - 9.2.2\n");
else
tsk_fprintf(hFile, "Unknown (%" PRIx32 "\n",
tsk_getu32(fs->endian, sb->last_mnt_ver));
/* State of the file system */
if ((tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_UNMOUNTED)
&& (!(tsk_getu32(fs->endian,
hfs->fs->attr) & HFS_VH_ATTR_INCONSISTENT)))
tsk_fprintf(hFile, "Volume Unmounted Properly\n");
else
tsk_fprintf(hFile, "Volume Unmounted Improperly\n");
tsk_fprintf(hFile, "Mount Count: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->write_cnt));
// Dates
// (creation date is in local time zone, not UTC, according to TN 1150)
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->cr_date));
tsk_fprintf(hFile, "\nCreation Date: \t%s\n",
tsk_fs_time_to_str(mktime(gmtime(&mac_time)), timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->m_date));
tsk_fprintf(hFile, "Last Written Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian,
hfs->fs->bkup_date));
tsk_fprintf(hFile, "Last Backup Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->chk_date));
tsk_fprintf(hFile, "Last Checked Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_SOFTWARE_LOCK)
tsk_fprintf(hFile, "Software write protect enabled\n");
/* Print journal information */
if (tsk_getu32(fs->endian, sb->attr) & HFS_VH_ATTR_JOURNALED) {
tsk_fprintf(hFile, "\nJournal Info Block: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->jinfo_blk));
}
tsk_fprintf(hFile, "\nMETADATA INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "Range: %" PRIuINUM " - %" PRIuINUM "\n",
fs->first_inum, fs->last_inum);
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT]);
tsk_fprintf(hFile, "Bootable Folder ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_START]);
tsk_fprintf(hFile, "Startup App ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_OPEN]);
tsk_fprintf(hFile, "Startup Open Folder ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT9]);
tsk_fprintf(hFile, "Mac OS 8/9 Blessed System Folder ID: %" PRIuINUM,
inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOTX]);
tsk_fprintf(hFile, "Mac OS X Blessed System Folder ID: %" PRIuINUM,
inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Number of files: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->file_cnt));
tsk_fprintf(hFile, "Number of folders: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->fldr_cnt));
tsk_fprintf(hFile, "\nCONTENT INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "Block Range: %" PRIuDADDR " - %" PRIuDADDR "\n",
fs->first_block, fs->last_block);
if (fs->last_block != fs->last_block_act)
tsk_fprintf(hFile,
"Total Range in Image: %" PRIuDADDR " - %" PRIuDADDR "\n",
fs->first_block, fs->last_block_act);
tsk_fprintf(hFile, "Allocation Block Size: %u\n", fs->block_size);
tsk_fprintf(hFile, "Number of Free Blocks: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->free_blks));
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_BADBLOCKS)
tsk_fprintf(hFile, "Volume has bad blocks\n");
return 0;
}
/************************* istat *******************************/
/**
* Text encoding names defined in TN1150, Table 2.
*/
static char *
text_encoding_name(uint32_t enc)
{
switch (enc) {
case 0:
return "MacRoman";
case 1:
return "MacJapanese";
case 2:
return "MacChineseTrad";
case 4:
return "MacKorean";
case 5:
return "MacArabic";
case 6:
return "MacHebrew";
case 7:
return "MacGreek";
case 8:
return "MacCyrillic";
case 9:
return "MacDevanagari";
case 10:
return "MacGurmukhi";
case 11:
return "MacGujarati";
case 12:
return "MacOriya";
case 13:
return "MacBengali";
case 14:
return "MacTamil";
case 15:
return "Telugu";
case 16:
return "MacKannada";
case 17:
return "MacMalayalam";
case 18:
return "MacSinhalese";
case 19:
return "MacBurmese";
case 20:
return "MacKhmer";
case 21:
return "MacThai";
case 22:
return "MacLaotian";
case 23:
return "MacGeorgian";
case 24:
return "MacArmenian";
case 25:
return "MacChineseSimp";
case 26:
return "MacTibetan";
case 27:
return "MacMongolian";
case 28:
return "MacEthiopic";
case 29:
return "MacCentralEurRoman";
case 30:
return "MacVietnamese";
case 31:
return "MacExtArabic";
case 33:
return "MacSymbol";
case 34:
return "MacDingbats";
case 35:
return "MacTurkish";
case 36:
return "MacCroatian";
case 37:
return "MacIcelandic";
case 38:
return "MacRomanian";
case 49:
case 140:
return "MacFarsi";
case 48:
case 152:
return "MacUkrainian";
default:
return "Unknown encoding";
}
}
#define HFS_PRINT_WIDTH 8
typedef struct {
FILE *hFile;
int idx;
TSK_DADDR_T startBlock;
uint32_t blockCount;
unsigned char accumulating;
} HFS_PRINT_ADDR;
static void
output_print_addr(HFS_PRINT_ADDR * print)
{
if (!print->accumulating)
return;
if (print->blockCount == 1) {
tsk_fprintf(print->hFile, "%" PRIuDADDR " ", print->startBlock);
print->idx += 1;
}
else if (print->blockCount > 1) {
tsk_fprintf(print->hFile, "%" PRIuDADDR "-%" PRIuDADDR " ",
print->startBlock, print->startBlock + print->blockCount - 1);
print->idx += 2;
}
if (print->idx >= HFS_PRINT_WIDTH) {
tsk_fprintf(print->hFile, "\n");
print->idx = 0;
}
}
static TSK_WALK_RET_ENUM
print_addr_act(TSK_FS_FILE * fs_file, TSK_OFF_T a_off, TSK_DADDR_T addr,
char *buf, size_t size, TSK_FS_BLOCK_FLAG_ENUM flags, void *ptr)
{
HFS_PRINT_ADDR *print = (HFS_PRINT_ADDR *) ptr;
if (print->accumulating) {
if (addr == print->startBlock + print->blockCount) {
++print->blockCount;
}
else {
output_print_addr(print);
print->startBlock = addr;
print->blockCount = 1;
}
}
else {
print->startBlock = addr;
print->blockCount = 1;
print->accumulating = TRUE;
}
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 name 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
hfs_istat(TSK_FS_INFO * fs, TSK_FS_ISTAT_FLAG_ENUM istat_flags, FILE * hFile, TSK_INUM_T inum,
TSK_DADDR_T numblock, int32_t sec_skew)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
TSK_FS_FILE *fs_file;
char hfs_mode[12];
HFS_PRINT_ADDR print;
HFS_ENTRY entry;
char timeBuf[128];
// Compression ATTR, if there is one:
const TSK_FS_ATTR *compressionAttr = NULL;
RES_DESCRIPTOR *rd; // descriptor of a resource
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_istat: inum: %" PRIuINUM " numblock: %" PRIu32 "\n",
inum, numblock);
if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {
error_returned("hfs_istat: getting metadata for the file");
return 1;
}
if (inum >= HFS_FIRST_USER_CNID) {
int rslt;
tsk_fprintf(hFile, "File Path: ");
rslt = print_parent_path(hFile, fs, inum);
if (rslt != 0)
tsk_fprintf(hFile, " Error in printing path\n");
else
tsk_fprintf(hFile, "\n");
}
else {
// All of the files in this inum range have names without nulls,
// slashes or control characters. So, it is OK to print this UTF8
// string this way.
if (fs_file->meta->name2 != NULL)
tsk_fprintf(hFile, "File Name: %s\n",
fs_file->meta->name2->name);
}
tsk_fprintf(hFile, "Catalog Record: %" PRIuINUM "\n", inum);
tsk_fprintf(hFile, "%sAllocated\n",
(fs_file->meta->flags & TSK_FS_META_FLAG_UNALLOC) ? "Not " : "");
tsk_fprintf(hFile, "Type:\t");
if (fs_file->meta->type == TSK_FS_META_TYPE_REG)
tsk_fprintf(hFile, "File\n");
else if (TSK_FS_IS_DIR_META(fs_file->meta->type))
tsk_fprintf(hFile, "Folder\n");
else
tsk_fprintf(hFile, "\n");
tsk_fs_meta_make_ls(fs_file->meta, hfs_mode, sizeof(hfs_mode));
tsk_fprintf(hFile, "Mode:\t%s\n", hfs_mode);
tsk_fprintf(hFile, "Size:\t%" PRIuOFF "\n", fs_file->meta->size);
if (fs_file->meta->link)
tsk_fprintf(hFile, "Symbolic link to:\t%s\n", fs_file->meta->link);
tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n",
fs_file->meta->uid, fs_file->meta->gid);
tsk_fprintf(hFile, "Link count:\t%d\n", fs_file->meta->nlink);
if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE) == 0) {
hfs_uni_str *nm = &entry.thread.name;
char name_buf[HFS_MAXNAMLEN + 1];
TSK_INUM_T par_cnid; // parent CNID
tsk_fprintf(hFile, "\n");
hfs_UTF16toUTF8(fs, nm->unicode, (int) tsk_getu16(fs->endian,
nm->length), &name_buf[0], HFS_MAXNAMLEN + 1,
HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL);
tsk_fprintf(hFile, "File Name: %s\n", name_buf);
// Test here to see if this is a hard link.
par_cnid = tsk_getu32(fs->endian, &(entry.thread.parent_cnid));
if ((hfs->has_meta_dir_crtime && par_cnid == hfs->meta_dir_inum) ||
(hfs->has_meta_crtime && par_cnid == hfs->meta_inum)) {
int instr = strncmp(name_buf, "iNode", 5);
int drstr = strncmp(name_buf, "dir_", 4);
if (instr == 0 &&
hfs->has_meta_crtime && par_cnid == hfs->meta_inum) {
tsk_fprintf(hFile, "This is a hard link to a file\n");
}
else if (drstr == 0 &&
hfs->has_meta_dir_crtime &&
par_cnid == hfs->meta_dir_inum) {
tsk_fprintf(hFile, "This is a hard link to a folder.\n");
}
}
/* The cat.perm union contains file-type specific values.
* Print them if they are relevant. */
if ((fs_file->meta->type == TSK_FS_META_TYPE_CHR) ||
(fs_file->meta->type == TSK_FS_META_TYPE_BLK)) {
tsk_fprintf(hFile, "Device ID:\t%" PRIu32 "\n",
tsk_getu32(fs->endian, entry.cat.std.perm.special.raw));
}
else if ((tsk_getu32(fs->endian,
entry.cat.std.u_info.file_type) ==
HFS_HARDLINK_FILE_TYPE)
&& (tsk_getu32(fs->endian,
entry.cat.std.u_info.file_cr) ==
HFS_HARDLINK_FILE_CREATOR)) {
// technically, the creation date of this item should be the same as either the
// creation date of the "HFS+ Private Data" folder or the creation date of the root folder
tsk_fprintf(hFile, "Hard link inode number\t %" PRIu32 "\n",
tsk_getu32(fs->endian, entry.cat.std.perm.special.inum));
}
tsk_fprintf(hFile, "Admin flags: %" PRIu8,
entry.cat.std.perm.a_flags);
if (entry.cat.std.perm.a_flags != 0) {
tsk_fprintf(hFile, " - ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_ARCHIVED)
tsk_fprintf(hFile, "archived ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_IMMUTABLE)
tsk_fprintf(hFile, "immutable ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_APPEND)
tsk_fprintf(hFile, "append-only ");
}
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Owner flags: %" PRIu8,
entry.cat.std.perm.o_flags);
if (entry.cat.std.perm.o_flags != 0) {
tsk_fprintf(hFile, " - ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_NODUMP)
tsk_fprintf(hFile, "no-dump ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_IMMUTABLE)
tsk_fprintf(hFile, "immutable ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_APPEND)
tsk_fprintf(hFile, "append-only ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_OPAQUE)
tsk_fprintf(hFile, "opaque ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
tsk_fprintf(hFile, "compressed ");
}
tsk_fprintf(hFile, "\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_LOCKED)
tsk_fprintf(hFile, "Locked\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_ATTR)
tsk_fprintf(hFile, "Has extended attributes\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_ACL)
tsk_fprintf(hFile, "Has security data (ACLs)\n");
// File_type and file_cr are not relevant for Folders
if ( !TSK_FS_IS_DIR_META(fs_file->meta->type)){
int windx; // loop index
tsk_fprintf(hFile,
"File type:\t%04" PRIx32 " ",
tsk_getu32(fs->endian, entry.cat.std.u_info.file_type));
for (windx = 0; windx < 4; ++windx) {
uint8_t cu = entry.cat.std.u_info.file_type[windx];
if (cu >= 32 && cu <= 126)
tsk_fprintf(hFile, "%c", (char) cu);
else
tsk_fprintf(hFile, " ");
}
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile,
"File creator:\t%04" PRIx32 " ",
tsk_getu32(fs->endian, entry.cat.std.u_info.file_cr));
for (windx = 0; windx < 4; ++windx) {
uint8_t cu = entry.cat.std.u_info.file_cr[windx];
if (cu >= 32 && cu <= 126)
tsk_fprintf(hFile, "%c", (char) cu);
else
tsk_fprintf(hFile, " ");
}
tsk_fprintf(hFile, "\n");
} // END if(not folder)
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_NAME_LOCKED)
tsk_fprintf(hFile, "Name locked\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_HAS_BUNDLE)
tsk_fprintf(hFile, "Has bundle\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_INVISIBLE)
tsk_fprintf(hFile, "Is invisible\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_ALIAS)
tsk_fprintf(hFile, "Is alias\n");
tsk_fprintf(hFile, "Text encoding:\t%" PRIx32 " = %s\n",
tsk_getu32(fs->endian, entry.cat.std.text_enc),
text_encoding_name(tsk_getu32(fs->endian,
entry.cat.std.text_enc)));
if (tsk_getu16(fs->endian,
entry.cat.std.rec_type) == HFS_FILE_RECORD) {
tsk_fprintf(hFile, "Resource fork size:\t%" PRIu64 "\n",
tsk_getu64(fs->endian, entry.cat.resource.logic_sz));
}
}
if (sec_skew != 0) {
tsk_fprintf(hFile, "\nAdjusted times:\n");
if (fs_file->meta->mtime)
fs_file->meta->mtime -= sec_skew;
if (fs_file->meta->atime)
fs_file->meta->atime -= sec_skew;
if (fs_file->meta->ctime)
fs_file->meta->ctime -= sec_skew;
if (fs_file->meta->crtime)
fs_file->meta->crtime -= sec_skew;
if (fs_file->meta->time2.hfs.bkup_time)
fs_file->meta->time2.hfs.bkup_time -= sec_skew;
tsk_fprintf(hFile, "Created:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf));
tsk_fprintf(hFile, "Content Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf));
tsk_fprintf(hFile, "Attributes Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf));
tsk_fprintf(hFile, "Accessed:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->atime, timeBuf));
tsk_fprintf(hFile, "Backed Up:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time,
timeBuf));
if (fs_file->meta->mtime)
fs_file->meta->mtime += sec_skew;
if (fs_file->meta->atime)
fs_file->meta->atime += sec_skew;
if (fs_file->meta->ctime)
fs_file->meta->ctime += sec_skew;
if (fs_file->meta->crtime)
fs_file->meta->crtime += sec_skew;
if (fs_file->meta->time2.hfs.bkup_time)
fs_file->meta->time2.hfs.bkup_time += sec_skew;
tsk_fprintf(hFile, "\nOriginal times:\n");
}
else {
tsk_fprintf(hFile, "\nTimes:\n");
}
tsk_fprintf(hFile, "Created:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf));
tsk_fprintf(hFile, "Content Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf));
tsk_fprintf(hFile, "Attributes Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf));
tsk_fprintf(hFile, "Accessed:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->atime, timeBuf));
tsk_fprintf(hFile, "Backed Up:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time, timeBuf));
// IF this is a regular file, then print out the blocks of the DATA and RSRC forks.
if (tsk_getu16(fs->endian, entry.cat.std.rec_type) == HFS_FILE_RECORD) {
// Only print DATA fork blocks if this file is NOT compressed
// N.B., a compressed file has no data fork, and tsk_fs_file_walk() will
// do the wrong thing!
if (!(entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)) {
if (!(istat_flags & TSK_FS_ISTAT_RUNLIST)) {
tsk_fprintf(hFile, "\nData Fork Blocks:\n");
print.idx = 0;
print.hFile = hFile;
print.accumulating = FALSE;
print.startBlock = 0;
print.blockCount = 0;
if (tsk_fs_file_walk_type(fs_file,
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
(TSK_FS_FILE_WALK_FLAG_AONLY |
TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act,
(void *)&print)) {
tsk_fprintf(hFile, "\nError reading file data fork\n");
tsk_error_print(hFile);
tsk_error_reset();
}
else {
output_print_addr(&print);
if (print.idx != 0)
tsk_fprintf(hFile, "\n");
}
}
}
// Only print out the blocks of the Resource fork if it has nonzero size
if (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) > 0) {
if (! (istat_flags & TSK_FS_ISTAT_RUNLIST)) {
tsk_fprintf(hFile, "\nResource Fork Blocks:\n");
print.idx = 0;
print.hFile = hFile;
print.accumulating = FALSE;
print.startBlock = 0;
print.blockCount = 0;
if (tsk_fs_file_walk_type(fs_file,
TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC,
(TSK_FS_FILE_WALK_FLAG_AONLY |
TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act,
(void *)&print)) {
tsk_fprintf(hFile, "\nError reading file resource fork\n");
tsk_error_print(hFile);
tsk_error_reset();
}
else {
output_print_addr(&print);
if (print.idx != 0)
tsk_fprintf(hFile, "\n");
}
}
}
}
// Force the loading of all attributes.
(void) tsk_fs_file_attr_get(fs_file);
/* Print all of the attributes */
tsk_fprintf(hFile, "\nAttributes: \n");
if (fs_file->meta->attr) {
int cnt, i;
// cycle through the attributes
cnt = tsk_fs_file_attr_getsize(fs_file);
for (i = 0; i < cnt; ++i) {
const char *type; // type of the attribute as a string
const TSK_FS_ATTR *fs_attr =
tsk_fs_file_attr_get_idx(fs_file, i);
if (!fs_attr)
continue;
type = hfs_attrTypeName((uint32_t) fs_attr->type);
// We will need to do something better than this, in the end.
//type = "Data";
/* print the layout if it is non-resident and not "special" */
if (fs_attr->flags & TSK_FS_ATTR_NONRES) {
//NTFS_PRINT_ADDR print_addr;
tsk_fprintf(hFile,
"Type: %s (%" PRIu32 "-%" PRIu16
") Name: %s Non-Resident%s%s%s size: %"
PRIuOFF " init_size: %" PRIuOFF "\n", type,
fs_attr->type, fs_attr->id,
(fs_attr->name) ? fs_attr->name : "N/A",
(fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" :
"",
(fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" :
"",
(fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" :
"", fs_attr->size, fs_attr->nrd.initsize);
if (istat_flags & TSK_FS_ISTAT_RUNLIST) {
if (tsk_fs_attr_print(fs_attr, hFile)) {
tsk_fprintf(hFile, "\nError creating run lists\n");
tsk_error_print(hFile);
tsk_error_reset();
}
}
} // END: non-resident attribute case
else {
tsk_fprintf(hFile,
"Type: %s (%" PRIu32 "-%" PRIu16
") Name: %s Resident%s%s%s size: %"
PRIuOFF "\n",
type,
fs_attr->type,
fs_attr->id,
(fs_attr->name) ? fs_attr->name : "N/A",
(fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" :
"",
(fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" :
"",
(fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" :
"", fs_attr->size);
if (fs_attr->type == TSK_FS_ATTR_TYPE_HFS_COMP_REC) {
if (compressionAttr == NULL) {
compressionAttr = fs_attr;
}
else {
// Problem: there is more than one compression attribute
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_istat: more than one compression attribute");
return 1;
}
}
} // END: else (RESIDENT attribute case)
} // END: for(;;) loop over attributes
} // END: if(fs_file->meta->attr is non-NULL)
if ((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
&& (compressionAttr == NULL))
tsk_fprintf(hFile,
"WARNING: Compression Flag is set, but there"
" is no compression record for this file.\n");
if (((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) == 0)
&& (compressionAttr != NULL))
tsk_fprintf(hFile,
"WARNING: Compression Flag is NOT set, but there"
" is a compression record for this file.\n");
// IF this is a compressed file
if (compressionAttr != NULL) {
const TSK_FS_ATTR *fs_attr = compressionAttr;
ssize_t attrReadResult;
DECMPFS_DISK_HEADER *cmph;
uint32_t cmpType;
uint64_t uncSize;
uint64_t cmpSize = 0;
// Read the attribute. It cannot be too large because it is stored in
// a btree node
char *aBuf = (char *) tsk_malloc((size_t) fs_attr->size);
if (aBuf == NULL) {
error_returned("hfs_istat: space for a compression attribute");
return 1;
}
attrReadResult = tsk_fs_attr_read(fs_attr, (TSK_OFF_T) 0,
aBuf, (size_t) fs_attr->size,
(TSK_FS_FILE_READ_FLAG_ENUM) 0x00);
if (attrReadResult == -1) {
error_returned("hfs_istat: reading the compression attribute");
free(aBuf);
return 1;
}
else if (attrReadResult < fs_attr->size) {
error_detected(TSK_ERR_FS_READ,
"hfs_istat: could not read the whole compression attribute");
free(aBuf);
return 1;
}
// Now, cast the attr into a compression header
cmph = (DECMPFS_DISK_HEADER *) aBuf;
cmpType = tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type);
uncSize = tsk_getu64(TSK_LIT_ENDIAN, cmph->uncompressed_size);
tsk_fprintf(hFile, "\nCompressed File:\n");
tsk_fprintf(hFile, " Uncompressed size: %llu\n", uncSize);
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_ATTR:
// Data is inline
{
// size of header, with indicator byte if uncompressed
uint32_t off = (cmph->attr_bytes[0] & 0x0F) == 0x0F ? 17 : 16;
cmpSize = fs_attr->size - off;
tsk_fprintf(hFile,
" Data follows compression record in the CMPF attribute\n"
" %" PRIu64 " bytes of data at offset %u, %s compressed\n",
cmpSize, off, off == 16 ? "zlib" : "not");
}
break;
case DECMPFS_TYPE_LZVN_ATTR:
// Data is inline
{
// size of header, with indicator byte if uncompressed
uint32_t off = cmph->attr_bytes[0] == 0x06 ? 17 : 16;
cmpSize = fs_attr->size - off;
tsk_fprintf(hFile,
" Data follows compression record in the CMPF attribute\n"
" %" PRIu64 " bytes of data at offset %u, %s compressed\n",
cmpSize, off, off == 16 ? "lzvn" : "not");
}
break;
case DECMPFS_TYPE_ZLIB_RSRC:
// Data is zlib compressed in the resource fork
tsk_fprintf(hFile,
" Data is zlib compressed in the resource fork\n");
break;
case DECMPFS_TYPE_LZVN_RSRC:
// Data is lzvn compressed in the resource fork
tsk_fprintf(hFile,
" Data is lzvn compressed in the resource fork\n");
break;
default:
tsk_fprintf(hFile, " Compression type is %u: UNKNOWN\n",
cmpType);
}
free(aBuf);
if ((cmpType == DECMPFS_TYPE_ZLIB_RSRC ||
cmpType == DECMPFS_TYPE_LZVN_RSRC)
&& (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) == 0))
tsk_fprintf(hFile,
"WARNING: Compression record indicates compressed data"
" in the RSRC Fork, but that fork is empty.\n");
}
// This will return NULL if there is an error, or if there are no resources
rd = hfs_parse_resource_fork(fs_file);
// TODO: Should check the errnum here to see if there was an error
if (rd != NULL) {
tsk_fprintf(hFile, "\nResources:\n");
while (rd) {
tsk_fprintf(hFile,
" Type: %s \tID: %-5u \tOffset: %-5u \tSize: %-5u \tName: %s\n",
rd->type, rd->id, rd->offset, rd->length, rd->name);
rd = rd->next;
}
}
// This is OK to call with NULL
free_res_descriptor(rd);
tsk_fs_file_close(fs_file);
return 0;
}
static TSK_FS_ATTR_TYPE_ENUM
hfs_get_default_attr_type(const TSK_FS_FILE * a_file)
{
// The HFS+ special files have a default attr type of "Default"
TSK_INUM_T inum = a_file->meta->addr;
if (inum == 3 || // Extents File
inum == 4 || // Catalog File
inum == 5 || // Bad Blocks File
inum == 6 || // Block Map (Allocation File)
inum == 7 || // Startup File
inum == 8 || // Attributes File
inum == 14 || // Not sure if these two will actually work. I don't see
inum == 15) // any code to load the attrs of these files, if they exist.
return TSK_FS_ATTR_TYPE_DEFAULT;
// The "regular" files and symbolic links have a DATA fork with type "DATA"
if (a_file->meta->type == TSK_FS_META_TYPE_REG ||
a_file->meta->type == TSK_FS_META_TYPE_LNK)
// This should be an HFS-specific type.
return TSK_FS_ATTR_TYPE_HFS_DATA;
// We've got to return *something* for every file, so we return this.
return TSK_FS_ATTR_TYPE_DEFAULT;
}
static void
hfs_close(TSK_FS_INFO * fs)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
// We'll grab this lock a bit early.
tsk_take_lock(&(hfs->metadata_dir_cache_lock));
fs->tag = 0;
free(hfs->fs);
if (hfs->catalog_file) {
tsk_fs_file_close(hfs->catalog_file);
hfs->catalog_attr = NULL;
}
if (hfs->blockmap_file) {
tsk_fs_file_close(hfs->blockmap_file);
hfs->blockmap_attr = NULL;
}
if (hfs->meta_dir) {
tsk_fs_dir_close(hfs->meta_dir);
hfs->meta_dir = NULL;
}
if (hfs->dir_meta_dir) {
tsk_fs_dir_close(hfs->dir_meta_dir);
hfs->dir_meta_dir = NULL;
}
if (hfs->extents_file) {
tsk_fs_file_close(hfs->extents_file);
hfs->extents_file = NULL;
}
tsk_release_lock(&(hfs->metadata_dir_cache_lock));
tsk_deinit_lock(&(hfs->metadata_dir_cache_lock));
tsk_fs_free((TSK_FS_INFO *)hfs);
}
/* hfs_open - open an hfs file system
*
* Return NULL on error (or not an HFS or HFS+ file system)
* */
TSK_FS_INFO *
hfs_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset,
TSK_FS_TYPE_ENUM ftype, uint8_t test)
{
HFS_INFO *hfs;
unsigned int len;
TSK_FS_INFO *fs;
ssize_t cnt;
TSK_FS_FILE *file; // The root directory, or the metadata directories
TSK_INUM_T inum; // The inum (or CNID) of the metadata directories
int8_t result; // of tsk_fs_path2inum()
tsk_error_reset();
if (TSK_FS_TYPE_ISHFS(ftype) == 0) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("Invalid FS Type in hfs_open");
return NULL;
}
if ((hfs = (HFS_INFO *) tsk_fs_malloc(sizeof(HFS_INFO))) == NULL)
return NULL;
fs = &(hfs->fs_info);
fs->ftype = TSK_FS_TYPE_HFS;
fs->duname = "Allocation Block";
fs->tag = TSK_FS_INFO_TAG;
fs->flags = 0;
fs->img_info = img_info;
fs->offset = offset;
/*
* Read the superblock.
*/
len = sizeof(hfs_plus_vh);
if ((hfs->fs = (hfs_plus_vh *) tsk_malloc(len)) == NULL) {
fs->tag = 0;
tsk_fs_free((TSK_FS_INFO *)hfs);
return NULL;
}
if (hfs_checked_read_random(fs, (char *) hfs->fs, len,
(TSK_OFF_T) HFS_VH_OFF)) {
tsk_error_set_errstr2("hfs_open: superblock");
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
return NULL;
}
/*
* Verify we are looking at an HFS+ image
*/
if (tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSPLUS) &&
tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSX) &&
tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFS)) {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_MAGIC);
tsk_error_set_errstr("not an HFS+ file system (magic)");
return NULL;
}
/*
* Handle an HFS-wrapped HFS+ image, which is a HFS volume that contains
* the HFS+ volume inside of it.
*/
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFS) {
hfs_mdb *wrapper_sb = (hfs_mdb *) hfs->fs;
// Verify that we are setting a wrapper and not a normal HFS volume
if ((tsk_getu16(fs->endian,
wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSPLUS)
|| (tsk_getu16(fs->endian,
wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSX)) {
TSK_FS_INFO *fs_info2;
// offset in sectors to start of first HFS block
uint16_t drAlBlSt =
tsk_getu16(fs->endian, wrapper_sb->drAlBlSt);
// size of each HFS block
uint32_t drAlBlkSiz =
tsk_getu32(fs->endian, wrapper_sb->drAlBlkSiz);
// start of embedded FS
uint16_t startBlock = tsk_getu16(fs->endian,
wrapper_sb->drEmbedExtent_startBlock);
// calculate the offset; 512 here is intentional.
// TN1150 says "The drAlBlSt field contains the offset, in
// 512-byte blocks, of the wrapper's allocation block 0 relative
// to the start of the volume"
TSK_OFF_T hfsplus_offset =
(drAlBlSt * (TSK_OFF_T) 512) +
(drAlBlkSiz * (TSK_OFF_T) startBlock);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: HFS+/HFSX within HFS wrapper at byte offset %"
PRIuOFF "\n", hfsplus_offset);
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
/* just re-open with the new offset, then record the offset */
if (hfsplus_offset == 0) {
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("HFS+ offset is zero");
return NULL;
}
fs_info2 =
hfs_open(img_info, offset + hfsplus_offset, ftype, test);
if (fs_info2)
((HFS_INFO *) fs_info2)->hfs_wrapper_offset =
hfsplus_offset;
return fs_info2;
}
else {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_MAGIC);
tsk_error_set_errstr
("HFS file systems (other than wrappers HFS+/HFSX file systems) are not supported");
return NULL;
}
}
fs->block_count = tsk_getu32(fs->endian, hfs->fs->blk_cnt);
fs->first_block = 0;
fs->last_block = fs->last_block_act = fs->block_count - 1;
/* this isn't really accurate; fs->block_size reports only the size
of the allocation block; the size of the device block has to be
found from the device (allocation block size should always be
larger than device block size and an even multiple of the device
block size) */
fs->dev_bsize = fs->block_size =
tsk_getu32(fs->endian, hfs->fs->blk_sz);
// determine the last block we have in this image
if (fs->block_size <= 1) {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("HFS+ allocation block size too small");
return NULL;
}
if ((TSK_DADDR_T) ((img_info->size - offset) / fs->block_size) <
fs->block_count)
fs->last_block_act =
(img_info->size - offset) / fs->block_size - 1;
// Initialize the lock
tsk_init_lock(&(hfs->metadata_dir_cache_lock));
/*
* Set function pointers
*/
fs->inode_walk = hfs_inode_walk;
fs->block_walk = hfs_block_walk;
fs->block_getflags = hfs_block_getflags;
fs->load_attrs = hfs_load_attrs;
fs->get_default_attr_type = hfs_get_default_attr_type;
fs->file_add_meta = hfs_inode_lookup;
fs->dir_open_meta = hfs_dir_open_meta;
fs->fsstat = hfs_fsstat;
fs->fscheck = hfs_fscheck;
fs->istat = hfs_istat;
fs->close = hfs_close;
// lazy loading of block map
hfs->blockmap_file = NULL;
hfs->blockmap_attr = NULL;
hfs->blockmap_cache_start = -1;
hfs->blockmap_cache_len = 0;
fs->first_inum = HFS_ROOT_INUM;
fs->root_inum = HFS_ROOT_INUM;
fs->last_inum = HFS_FIRST_USER_CNID - 1; // we will later increase this
fs->inum_count = fs->last_inum - fs->first_inum + 1;
/* We will load the extents file data when we need it */
hfs->extents_file = NULL;
hfs->extents_attr = NULL;
if (tsk_getu32(fs->endian,
hfs->fs->start_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Startup File is not present.\n");
hfs->has_startup_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_open: Startup File is present.\n");
hfs->has_startup_file = TRUE;
}
if (tsk_getu32(fs->endian, hfs->fs->ext_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Extents File (and Badblocks File) is not present.\n");
hfs->has_extents_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Extents File (and BadBlocks File) is present.\n");
hfs->has_extents_file = TRUE;
}
if (tsk_getu32(fs->endian, hfs->fs->attr_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Attributes File is not present.\n");
hfs->has_attributes_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_open: Attributes File is present.\n");
hfs->has_attributes_file = TRUE;
}
/* Load the catalog file though */
if ((hfs->catalog_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_CATALOG_FILE_ID)) == NULL) {
hfs_close(fs);
return NULL;
}
/* cache the data attribute */
hfs->catalog_attr =
tsk_fs_attrlist_get(hfs->catalog_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->catalog_attr) {
hfs_close(fs);
tsk_error_errstr2_concat
(" - Data Attribute not found in Catalog File");
return NULL;
}
// cache the catalog file header
cnt = tsk_fs_attr_read(hfs->catalog_attr, 14,
(char *) &(hfs->catalog_header),
sizeof(hfs_btree_header_record), 0);
if (cnt != sizeof(hfs_btree_header_record)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
hfs_close(fs);
tsk_error_set_errstr2("hfs_open: Error reading catalog header");
return NULL;
}
if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSPLUS)
hfs->is_case_sensitive = 0;
else if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSX) {
if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_SENS)
hfs->is_case_sensitive = 1;
else if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_INSENS)
hfs->is_case_sensitive = 0;
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: invalid value (0x%02" PRIx8
") for key compare type; using case-insensitive\n",
hfs->catalog_header.compType);
hfs->is_case_sensitive = 0;
}
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: unknown HFS+/HFSX version (%" PRIu16 "\n",
tsk_getu16(fs->endian, hfs->fs->version));
hfs->is_case_sensitive = 0;
}
// update the numbers.
fs->last_inum = hfs_find_highest_inum(hfs);
fs->inum_count = fs->last_inum + 1;
snprintf((char *) fs->fs_id, 17, "%08" PRIx32 "%08" PRIx32,
tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID1]),
tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID2]));
fs->fs_id_used = 16;
/* journal */
fs->jblk_walk = hfs_jblk_walk;
fs->jentry_walk = hfs_jentry_walk;
fs->jopen = hfs_jopen;
fs->name_cmp = hfs_name_cmp;
fs->journ_inum = 0;
/* Creation Times */
// First, the root
file = tsk_fs_file_open_meta(fs, NULL, 2);
if (file != NULL) {
hfs->root_crtime = file->meta->crtime;
hfs->has_root_crtime = TRUE;
tsk_fs_file_close(file);
}
else {
hfs->has_root_crtime = FALSE;
}
file = NULL;
// disable hard link traversal while finding the hard
// link directories themselves (to prevent problems if
// there are hard links in the root directory)
hfs->meta_inum = 0;
hfs->meta_dir_inum = 0;
// Now the (file) metadata directory
// The metadata directory is a sub-directory of the root. Its name begins with four nulls, followed
// by "HFS+ Private Data". The file system parsing code replaces nulls in filenames with UTF8_NULL_REPLACE.
// In the released version of TSK, this replacement is the character '^'.
// NOTE: There is a standard Unicode replacement which is 0xfffd in UTF16 and 0xEF 0xBF 0xBD in UTF8.
// Systems that require the standard definition can redefine UTF8_NULL_REPLACE and UTF16_NULL_REPLACE
// in tsk_hfs.h
hfs->has_meta_crtime = FALSE;
result =
tsk_fs_path2inum(fs,
"/" UTF8_NULL_REPLACE UTF8_NULL_REPLACE UTF8_NULL_REPLACE
UTF8_NULL_REPLACE "HFS+ Private Data", &inum, NULL);
if (result == 0) {
TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum);
if (file_tmp != NULL) {
hfs->meta_crtime = file_tmp->meta->crtime;
hfs->has_meta_crtime = TRUE;
hfs->meta_inum = inum;
tsk_fs_file_close(file_tmp);
}
}
// Now, the directory metadata directory
// The "directory" metadata directory, where hardlinked directories actually live, is a subdirectory
// of the root. The beginning of the name of this directory is ".HFS+ Private Directory Data" which
// is followed by a carriage return (ASCII 13).
hfs->has_meta_dir_crtime = FALSE;
result =
tsk_fs_path2inum(fs, "/.HFS+ Private Directory Data\r", &inum,
NULL);
if (result == 0) {
TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum);
if (file_tmp != NULL) {
hfs->metadir_crtime = file_tmp->meta->crtime;
hfs->has_meta_dir_crtime = TRUE;
hfs->meta_dir_inum = inum;
tsk_fs_file_close(file_tmp);
}
}
if (hfs->has_root_crtime && hfs->has_meta_crtime
&& hfs->has_meta_dir_crtime) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Creation times for key folders have been read and cached.\n");
}
if (!hfs->has_root_crtime) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Warning: Could not open the root directory. "
"Hard link detection and some other functions will be impaired\n");
}
else if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_open: The root directory is accessible.\n");
}
if (tsk_verbose) {
if (hfs->has_meta_crtime)
tsk_fprintf(stderr,
"hfs_open: \"/^^^^HFS+ Private Data\" metadata folder is accessible.\n");
else
tsk_fprintf(stderr,
"hfs_open: Optional \"^^^^HFS+ Private Data\" metadata folder is not accessible, or does not exist.\n");
if (hfs->has_meta_dir_crtime)
tsk_fprintf(stderr,
"hfs_open: \"/HFS+ Private Directory Data^\" metadata folder is accessible.\n");
else
tsk_fprintf(stderr,
"hfs_open: Optional \"/HFS+ Private Directory Data^\" metadata folder is not accessible, or does not exist.\n");
}
// These caches will be set, if they are needed.
hfs->meta_dir = NULL;
hfs->dir_meta_dir = NULL;
return fs;
}
/*
* Error Handling
*/
/**
* Call this when an error is first detected. It sets the error code and it also
* sets the primary error string, describing the lowest level of error. (Actually,
* it appends to the error string.)
*
* If the error code is already set, then this appends to the primary error
* string an hex representation of the new error code, plus the new error message.
*
* @param errnum The desired error code
* @param errstr The format string for the error message
*/
void
error_detected(uint32_t errnum, char *errstr, ...)
{
va_list args;
va_start(args, errstr);
{
TSK_ERROR_INFO *errInfo = tsk_error_get_info();
char *loc_errstr = errInfo->errstr;
if (errInfo->t_errno == 0)
errInfo->t_errno = errnum;
else {
//This should not happen! We don't want to wipe out the existing error
//code, so we write the new code into the error string, in hex.
size_t sl = strlen(errstr);
snprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
" Next errnum: 0x%x ", errnum);
}
if (errstr != NULL) {
size_t sl = strlen(loc_errstr);
vsnprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
errstr, args);
}
}
va_end(args);
}
/**
* Call this when a called TSK function returns an error. Presumably, that
* function will have set the error code and the primary error string. This
* *appends* to the secondary error string. It should be called to describe
* the context of the call. If no error code has been set, then this sets a
* default code so that it is not zero.
*
* @param errstr The format string for the error message
*/
void
error_returned(char *errstr, ...)
{
va_list args;
va_start(args, errstr);
{
TSK_ERROR_INFO *errInfo = tsk_error_get_info();
char *loc_errstr2 = errInfo->errstr2;
if (errInfo->t_errno == 0)
errInfo->t_errno = TSK_ERR_AUX_GENERIC;
if (errstr != NULL) {
size_t sl = strlen(loc_errstr2);
vsnprintf(loc_errstr2 + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
errstr, args);
}
}
va_end(args);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_451_0 |
crossvul-cpp_data_bad_351_16 | /*
* PKCS15 emulation layer for TCOS based preformatted cards
*
* Copyright (C) 2011, Peter Koch <pk@opensc-project.org>
*
* 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 2.1 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "common/compat_strlcpy.h"
#include "common/compat_strlcat.h"
#include "internal.h"
#include "pkcs15.h"
#include "cardctl.h"
#include "log.h"
int sc_pkcs15emu_tcos_init_ex(
sc_pkcs15_card_t *p15card,
struct sc_aid *,
sc_pkcs15emu_opt_t *opts);
static int insert_cert(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
int writable,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
struct sc_pkcs15_cert_info cert_info;
struct sc_pkcs15_object cert_obj;
unsigned char cert[20];
int r;
memset(&cert_info, 0, sizeof(cert_info));
cert_info.id.len = 1;
cert_info.id.value[0] = id;
cert_info.authority = 0;
sc_format_path(path, &cert_info.path);
memset(&cert_obj, 0, sizeof(cert_obj));
strlcpy(cert_obj.label, label, sizeof(cert_obj.label));
cert_obj.flags = writable ? SC_PKCS15_CO_FLAG_MODIFIABLE : 0;
if(sc_select_file(card, &cert_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n", path);
return 1;
}
if(sc_read_binary(card, 0, cert, sizeof(cert), 0)<0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"ReadBinary(%s) failed\n", path);
return 2;
}
if(cert[0]!=0x30 || cert[1]!=0x82){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Invalid Cert: %02X:%02X:...\n", cert[0], cert[1]);
return 3;
}
/* some certificates are prefixed by an OID */
if(cert[4]==0x06 && cert[5]<10 && cert[6+cert[5]]==0x30 && cert[7+cert[5]]==0x82){
cert_info.path.index=6+cert[5];
cert_info.path.count=(cert[8+cert[5]]<<8) + cert[9+cert[5]] + 4;
} else {
cert_info.path.index=0;
cert_info.path.count=(cert[2]<<8) + cert[3] + 4;
}
r=sc_pkcs15emu_add_x509_cert(p15card, &cert_obj, &cert_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_x509_cert(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, Index=%d, Count=%d\n", path, cert_info.path.index, cert_info.path.count);
return 0;
}
static int insert_key(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char key_reference,
int key_length,
unsigned char auth_id,
const char *label
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_prkey_info prkey_info;
struct sc_pkcs15_object prkey_obj;
int r, can_sign, can_crypt;
memset(&prkey_info, 0, sizeof(prkey_info));
prkey_info.id.len = 1;
prkey_info.id.value[0] = id;
prkey_info.native = 1;
prkey_info.key_reference = key_reference;
prkey_info.modulus_length = key_length;
sc_format_path(path, &prkey_info.path);
memset(&prkey_obj, 0, sizeof(prkey_obj));
strlcpy(prkey_obj.label, label, sizeof(prkey_obj.label));
prkey_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
prkey_obj.auth_id.len = 1;
prkey_obj.auth_id.value[0] = auth_id;
can_sign=can_crypt=0;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(prkey_info.path.len>=2) prkey_info.path.len-=2;
sc_append_file_id(&prkey_info.path, 0x5349);
if(sc_select_file(card, &prkey_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for Key-Ref %02X\n", key_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==key_reference) ++found;
}
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_KEYD-Record found\n");
return 1;
}
for(i=0;i<r;i+=2+buf[i+1]){
if(buf[i]==0xB6) can_sign++;
if(buf[i]==0xB8) can_crypt++;
}
} else {
if(sc_select_file(card, &prkey_info.path, &f)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&prkey_info.path));
return 1;
}
if (f->prop_attr[1] & 0x04) can_crypt=1;
if (f->prop_attr[1] & 0x08) can_sign=1;
sc_file_free(f);
}
prkey_info.usage= SC_PKCS15_PRKEY_USAGE_SIGN;
if(can_crypt) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_ENCRYPT|SC_PKCS15_PRKEY_USAGE_DECRYPT;
if(can_sign) prkey_info.usage |= SC_PKCS15_PRKEY_USAGE_NONREPUDIATION;
r=sc_pkcs15emu_add_rsa_prkey(p15card, &prkey_obj, &prkey_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_rsa_prkey(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK%s%s\n", path, can_sign ? ", Sign" : "", can_crypt ? ", Crypt" : "");
return 0;
}
static int insert_pin(
sc_pkcs15_card_t *p15card,
const char *path,
unsigned char id,
unsigned char auth_id,
unsigned char pin_reference,
int min_length,
const char *label,
int pin_flags
){
sc_card_t *card=p15card->card;
sc_context_t *ctx=p15card->card->ctx;
sc_file_t *f;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
int r;
memset(&pin_info, 0, sizeof(pin_info));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = id;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = pin_reference;
pin_info.attrs.pin.flags = pin_flags;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = min_length;
pin_info.attrs.pin.stored_length = 16;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.logged_in = SC_PIN_STATE_UNKNOWN;
sc_format_path(path, &pin_info.path);
memset(&pin_obj, 0, sizeof(pin_obj));
strlcpy(pin_obj.label, label, sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_MODIFIABLE | SC_PKCS15_CO_FLAG_PRIVATE;
pin_obj.auth_id.len = auth_id ? 0 : 1;
pin_obj.auth_id.value[0] = auth_id;
if(card->type==SC_CARD_TYPE_TCOS_V3){
unsigned char buf[256];
int i, rec_no=0;
if(pin_info.path.len>=2) pin_info.path.len-=2;
sc_append_file_id(&pin_info.path, 0x5049);
if(sc_select_file(card, &pin_info.path, NULL)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Select(%s) failed\n",
sc_print_path(&pin_info.path));
return 1;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,
"Searching for PIN-Ref %02X\n", pin_reference);
while((r=sc_read_record(card, ++rec_no, buf, sizeof(buf), SC_RECORD_BY_REC_NR))>0){
int found=0, fbz=-1;
if(buf[0]!=0xA0) continue;
for(i=2;i<buf[1]+2;i+=2+buf[i+1]){
if(buf[i]==0x83 && buf[i+1]==1 && buf[i+2]==pin_reference) ++found;
if(buf[i]==0x90) fbz=buf[i+1+buf[i+1]];
}
if(found) pin_info.tries_left=fbz;
if(found) break;
}
if(r<=0){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"No EF_PWDD-Record found\n");
return 1;
}
} else {
if(sc_select_file(card, &pin_info.path, &f)!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL,"Select(%s) failed\n", path);
return 1;
}
pin_info.tries_left=f->prop_attr[3];
sc_file_free(f);
}
r=sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if(r!=SC_SUCCESS){
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "sc_pkcs15emu_add_pin_obj(%s) failed\n", path);
return 4;
}
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "%s: OK, FBZ=%d\n", path, pin_info.tries_left);
return 0;
}
static char *dirpath(char *dir, const char *path){
static char buf[SC_MAX_PATH_STRING_SIZE];
strlcpy(buf,dir,sizeof buf);
strlcat(buf,path,sizeof buf);
return buf;
}
static int detect_netkey(
sc_pkcs15_card_t *p15card
){
sc_card_t *card=p15card->card;
sc_path_t p;
sc_file_t *f;
int keylen;
char dir[10];
const char *c_auth;
/* NKS-Applikation ? */
memset(&p, 0, sizeof(sc_path_t));
p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x03\x01\x02", p.len=7);
if (sc_select_file(card,&p,&f)!=SC_SUCCESS) return 1;
sprintf(dir,"%04X", f->id);
sc_file_free(f);
p15card->tokeninfo->manufacturer_id = strdup("TeleSec GmbH");
p15card->tokeninfo->label = strdup(card->type==SC_CARD_TYPE_TCOS_V3 ? "NetKey V3 Card" : "NetKey Card");
keylen= card->type==SC_CARD_TYPE_TCOS_V3 ? 2048 : 1024;
c_auth= card->type==SC_CARD_TYPE_TCOS_V3 ? "C500" : "C100";
insert_cert(p15card, dirpath(dir,"4331"), 0x45, 1, "Signatur Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4332"), 0x45, 1, "Signatur Zertifikat 2");
insert_cert(p15card, dirpath(dir,"C000"), 0x45, 0, "Telesec Signatur Zertifikat");
insert_cert(p15card, dirpath(dir,"43B1"), 0x46, 1, "Verschluesselungs Zertifikat 1");
insert_cert(p15card, dirpath(dir,"43B2"), 0x46, 1, "Verschluesselungs Zertifikat 2");
insert_cert(p15card, dirpath(dir,"C200"), 0x46, 0, "Telesec Verschluesselungs Zertifikat");
insert_cert(p15card, dirpath(dir,"4371"), 0x47, 1, "Authentifizierungs Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4372"), 0x47, 1, "Authentifizierungs Zertifikat 2");
insert_cert(p15card, dirpath(dir,c_auth), 0x47, 0, "Telesec Authentifizierungs Zertifikat");
insert_cert(p15card, dirpath(dir,"C201"), 0x48, 0, "Telesec 1024bit Zertifikat");
insert_key(p15card, dirpath(dir,"5331"), 0x45, 0x80, keylen, 4, "Signatur Schluessel");
insert_key(p15card, dirpath(dir,"53B1"), 0x46, 0x81, keylen, 3, "Verschluesselungs Schluessel");
insert_key(p15card, dirpath(dir,"5371"), 0x47, 0x82, keylen, 3, "Authentifizierungs Schluessel");
insert_key(p15card, dirpath(dir,"0000"), 0x48, 0x83, 1024, 3, "1024bit Schluessel");
insert_pin(p15card, "5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card, "5001", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_pin(p15card, dirpath(dir,"0000"), 3, 1, 0x83, 6, "NetKey PIN2",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
} else {
insert_pin(p15card, dirpath(dir,"5080"), 3, 1, 0x80, 6, "NetKey PIN0",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
}
insert_pin(p15card, dirpath(dir,"5081"), 4, 1, 0x81, 6, "NetKey PIN1",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
/* SigG-Applikation */
p.len=7; p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x66\x01", p.len=6);
if (sc_select_file(card,&p,&f)==SC_SUCCESS){
sprintf(dir,"%04X", f->id);
sc_file_free(f);
insert_cert(p15card, dirpath(dir,"C000"), 0x49, 1, "SigG Zertifikat 1");
insert_cert(p15card, dirpath(dir,"4331"), 0x49, 1, "SigG Zertifikat 2");
insert_cert(p15card, dirpath(dir,"4332"), 0x49, 1, "SigG Zertifikat 3");
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_key(p15card, dirpath(dir,"0000"), 0x49, 0x84, 2048, 5, "SigG Schluessel");
} else {
insert_key(p15card, dirpath(dir,"5331"), 0x49, 0x80, 1024, 5, "SigG Schluessel");
}
insert_pin(p15card, dirpath(dir,"5081"), 5, 0, 0x81, 6, "SigG PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
if(card->type==SC_CARD_TYPE_TCOS_V3){
insert_pin(p15card, dirpath(dir,"0000"), 6, 0, 0x83, 8, "SigG PIN2",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
}
}
return 0;
}
static int detect_idkey(
sc_pkcs15_card_t *p15card
){
sc_card_t *card=p15card->card;
sc_path_t p;
/* TCKEY-Applikation ? */
memset(&p, 0, sizeof(sc_path_t));
p.type=SC_PATH_TYPE_DF_NAME;
memcpy(p.value, "\xD2\x76\x00\x00\x03\x0C\x01", p.len=7);
if (sc_select_file(card,&p,NULL)!=SC_SUCCESS) return 1;
p15card->tokeninfo->manufacturer_id = strdup("TeleSec GmbH");
p15card->tokeninfo->label = strdup("IDKey Card");
insert_cert(p15card, "DF074331", 0x45, 1, "Signatur Zertifikat 1");
insert_cert(p15card, "DF074332", 0x45, 1, "Signatur Zertifikat 2");
insert_cert(p15card, "DF074333", 0x45, 1, "Signatur Zertifikat 3");
insert_key(p15card, "DF074E03", 0x45, 0x84, 2048, 1, "IDKey1");
insert_key(p15card, "DF074E04", 0x46, 0x85, 2048, 1, "IDKey2");
insert_key(p15card, "DF074E05", 0x47, 0x86, 2048, 1, "IDKey3");
insert_key(p15card, "DF074E06", 0x48, 0x87, 2048, 1, "IDKey4");
insert_key(p15card, "DF074E07", 0x49, 0x88, 2048, 1, "IDKey5");
insert_key(p15card, "DF074E08", 0x4A, 0x89, 2048, 1, "IDKey6");
insert_pin(p15card, "5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card, "5001", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
return 0;
}
static int detect_signtrust(
sc_pkcs15_card_t *p15card
){
if(insert_cert(p15card,"8000DF01C000", 0x45, 1, "Signatur Zertifikat")) return 1;
p15card->tokeninfo->manufacturer_id = strdup("Deutsche Post");
p15card->tokeninfo->label = strdup("SignTrust Card");
insert_cert(p15card,"800082008220", 0x46, 1, "Verschluesselungs Zertifikat");
insert_cert(p15card,"800083008320", 0x47, 1, "Authentifizierungs Zertifikat");
insert_key(p15card,"8000DF015331", 0x45, 0x80, 1024, 1, "Signatur Schluessel");
insert_key(p15card,"800082008210", 0x46, 0x80, 1024, 2, "Verschluesselungs Schluessel");
insert_key(p15card,"800083008310", 0x47, 0x80, 1024, 3, "Authentifizierungs Schluessel");
insert_pin(p15card,"8000DF010000", 1, 0, 0x81, 6, "Signatur PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"800082000040", 2, 0, 0x81, 6, "Verschluesselungs PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"800083000040", 3, 0, 0x81, 6, "Authentifizierungs PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
SC_PKCS15_PIN_FLAG_INITIALIZED
);
return 0;
}
static int detect_datev(
sc_pkcs15_card_t *p15card
){
if(insert_cert(p15card,"3000C500", 0x45, 0, "Signatur Zertifikat")) return 1;
p15card->tokeninfo->manufacturer_id = strdup("DATEV");
p15card->tokeninfo->label = strdup("DATEV Classic");
insert_cert(p15card,"DF02C200", 0x46, 0, "Verschluesselungs Zertifikat");
insert_cert(p15card,"DF02C500", 0x47, 0, "Authentifizierungs Zertifikat");
insert_key(p15card,"30005371", 0x45, 0x82, 1024, 1, "Signatur Schluessel");
insert_key(p15card,"DF0253B1", 0x46, 0x81, 1024, 1, "Verschluesselungs Schluessel");
insert_key(p15card,"DF025371", 0x47, 0x82, 1024, 1, "Authentifizierungs Schluessel");
insert_pin(p15card,"5001", 1, 0, 0x01, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
return 0;
}
static int detect_unicard(
sc_pkcs15_card_t *p15card
){
if(!insert_cert(p15card,"41004352", 0x45, 1, "Zertifikat 1")){
p15card->tokeninfo->manufacturer_id = strdup("JLU Giessen");
p15card->tokeninfo->label = strdup("JLU Giessen Card");
insert_cert(p15card,"41004353", 0x46, 1, "Zertifikat 2");
insert_cert(p15card,"41004354", 0x47, 1, "Zertifikat 3");
insert_key(p15card,"41005103", 0x45, 0x83, 1024, 1, "Schluessel 1");
insert_key(p15card,"41005104", 0x46, 0x84, 1024, 1, "Schluessel 2");
insert_key(p15card,"41005105", 0x47, 0x85, 1024, 1, "Schluessel 3");
} else if(!insert_cert(p15card,"41014352", 0x45, 1, "Zertifikat 1")){
p15card->tokeninfo->manufacturer_id = strdup("TU Darmstadt");
p15card->tokeninfo->label = strdup("TUD Card");
insert_cert(p15card,"41014353", 0x46, 1, "Zertifikat 2");
insert_cert(p15card,"41014354", 0x47, 1, "Zertifikat 3");
insert_key(p15card,"41015103", 0x45, 0x83, 1024, 1, "Schluessel 1");
insert_key(p15card,"41015104", 0x46, 0x84, 1024, 1, "Schluessel 2");
insert_key(p15card,"41015105", 0x47, 0x85, 1024, 1, "Schluessel 3");
} else return 1;
insert_pin(p15card,"5000", 1, 2, 0x00, 6, "PIN",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
);
insert_pin(p15card,"5008", 2, 0, 0x01, 8, "PUK",
SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
);
return 0;
}
int sc_pkcs15emu_tcos_init_ex(
sc_pkcs15_card_t *p15card,
struct sc_aid *aid,
sc_pkcs15emu_opt_t *opts
){
sc_card_t *card = p15card->card;
sc_context_t *ctx = p15card->card->ctx;
sc_serial_number_t serialnr;
char serial[30];
int i, r;
/* check if we have the correct card OS unless SC_PKCS15EMU_FLAGS_NO_CHECK */
i=(opts && (opts->flags & SC_PKCS15EMU_FLAGS_NO_CHECK));
if (!i && card->type!=SC_CARD_TYPE_TCOS_V2 && card->type!=SC_CARD_TYPE_TCOS_V3) return SC_ERROR_WRONG_CARD;
/* get the card serial number */
r = sc_card_ctl(card, SC_CARDCTL_GET_SERIALNR, &serialnr);
if (r < 0) {
sc_debug(ctx, SC_LOG_DEBUG_NORMAL, "unable to get ICCSN\n");
return SC_ERROR_WRONG_CARD;
}
sc_bin_to_hex(serialnr.value, serialnr.len , serial, sizeof(serial), 0);
serial[19] = '\0';
p15card->tokeninfo->serial_number = strdup(serial);
if(!detect_netkey(p15card)) return SC_SUCCESS;
if(!detect_idkey(p15card)) return SC_SUCCESS;
if(!detect_unicard(p15card)) return SC_SUCCESS;
if(!detect_signtrust(p15card)) return SC_SUCCESS;
if(!detect_datev(p15card)) return SC_SUCCESS;
return SC_ERROR_INTERNAL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_351_16 |
crossvul-cpp_data_bad_5106_0 | /* airpdcap.c
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* 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.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*/
/*
* The files matching airpcap*.[ch] were originally developed as part of
* Wireshark's support for AirPcap adapters. However, they've been used
* for general 802.11 decryption for quite some time. It might make sense
* to rename them accordingly.
*/
/****************************************************************************/
/* File includes */
#include "config.h"
#include <glib.h>
#include <wsutil/crc32.h>
#include <wsutil/rc4.h>
#include <wsutil/sha1.h>
#include <wsutil/sha2.h>
#include <wsutil/md5.h>
#include <wsutil/pint.h>
#include <wsutil/aes.h>
#include <epan/tvbuff.h>
#include <epan/to_str.h>
#include <epan/strutil.h>
#include <epan/crypt/airpdcap_rijndael.h>
#include "airpdcap_system.h"
#include "airpdcap_int.h"
#include "airpdcap_debug.h"
#include "wep-wpadefs.h"
/****************************************************************************/
/****************************************************************************/
/* Constant definitions */
/* EAPOL definitions */
/**
* Length of the EAPOL-Key key confirmation key (KCK) used to calculate
* MIC over EAPOL frame and validate an EAPOL packet (128 bits)
*/
#define AIRPDCAP_WPA_KCK_LEN 16
/**
*Offset of the Key MIC in the EAPOL packet body
*/
#define AIRPDCAP_WPA_MICKEY_OFFSET 77
/**
* Maximum length of the EAPOL packet (it depends on the maximum MAC
* frame size)
*/
#define AIRPDCAP_WPA_MAX_EAPOL_LEN 4095
/**
* EAPOL Key Descriptor Version 1, used for all EAPOL-Key frames to and
* from a STA when neither the group nor pairwise ciphers are CCMP for
* Key Descriptor 1.
* @note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_NOT_CCMP 1
/**
* EAPOL Key Descriptor Version 2, used for all EAPOL-Key frames to and
* from a STA when either the pairwise or the group cipher is AES-CCMP
* for Key Descriptor 2.
* /note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_AES_CCMP 2
/** Define EAPOL Key Descriptor type values: use 254 for WPA and 2 for WPA2 **/
#define AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR 254
#define AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR 2
/****************************************************************************/
/****************************************************************************/
/* Macro definitions */
extern const UINT32 crc32_table[256];
#define CRC(crc, ch) (crc = (crc >> 8) ^ crc32_table[(crc ^ (ch)) & 0xff])
#define AIRPDCAP_GET_TK(ptk) (ptk + 32)
/****************************************************************************/
/****************************************************************************/
/* Type definitions */
/* Internal function prototype declarations */
#ifdef __cplusplus
extern "C" {
#endif
/**
* It is a step of the PBKDF2 (specifically the PKCS #5 v2.0) defined in
* the RFC 2898 to derive a key (used as PMK in WPA)
* @param ppbytes [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param iterations [IN] times to hash the password (4096 for WPA)
* @param count [IN] ???
* @param output [OUT] pointer to a preallocated buffer of
* SHA1_DIGEST_LEN characters that will contain a part of the key
*/
static INT AirPDcapRsnaPwd2PskStep(
const guint8 *ppbytes,
const guint passLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
;
/**
* It calculates the passphrase-to-PSK mapping reccomanded for use with
* RSNAs. This implementation uses the PBKDF2 method defined in the RFC
* 2898.
* @param passphrase [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param output [OUT] calculated PSK (to use as PMK in WPA)
* @note
* Described in 802.11i-2004, page 165
*/
static INT AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
;
static INT AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
;
/**
* It checks whether the specified key is corrected or not.
* @note
* For a standard WEP key the length will be changed to the standard
* length, and the type changed in a generic WEP key.
* @param key [IN] pointer to the key to validate
* @return
* - TRUE: the key contains valid fields and values
* - FALSE: the key has some invalid field or value
*/
static INT AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
;
static INT AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
;
/**
* @param ctx [IN] pointer to the current context
* @param id [IN] id of the association (composed by BSSID and MAC of
* the station)
* @return
* - index of the Security Association structure if found
* - -1, if the specified addresses pair BSSID-STA MAC has not been found
*/
static INT AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static const UCHAR * AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static const UCHAR * AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static void AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
;
/**
* @param sa [IN/OUT] pointer to SA that will hold the key
* @param data [IN] Frame
* @param offset_rsne [IN] RSNE IE offset in the frame
* @param offset_fte [IN] Fast BSS Transition IE offset in the frame
* @param offset_timeout [IN] Timeout Interval IE offset in the frame
* @param offset_link [IN] Link Identifier IE offset in the frame
* @param action [IN] Tdls Action code (response or confirm)
*
* @return
* AIRPDCAP_RET_SUCCESS if Key has been sucessfully derived (and MIC verified)
* AIRPDCAP_RET_UNSUCCESS otherwise
*/
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
;
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Exported function definitions */
#ifdef __cplusplus
extern "C" {
#endif
const guint8 broadcast_mac[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
#define EAPKEY_MIC_LEN 16 /* length of the MIC key for EAPoL_Key packet's MIC using MD5 */
#define NONCE_LEN 32
#define TKIP_GROUP_KEY_LEN 32
#define CCMP_GROUP_KEY_LEN 16
typedef struct {
guint8 type;
guint8 key_information[2]; /* Make this an array to avoid alignment issues */
guint8 key_length[2]; /* Make this an array to avoid alignment issues */
guint8 replay_counter[8];
guint8 key_nonce[NONCE_LEN];
guint8 key_iv[16];
guint8 key_sequence_counter[8]; /* also called the RSC */
guint8 key_id[8];
guint8 key_mic[EAPKEY_MIC_LEN];
guint8 key_data_len[2]; /* Make this an array rather than a U16 to avoid alignment shifting */
} EAPOL_RSN_KEY, * P_EAPOL_RSN_KEY;
/* Minimum possible key data size (at least one GTK KDE with CCMP key) */
#define GROUP_KEY_MIN_LEN 8 + CCMP_GROUP_KEY_LEN
/* Minimum possible group key msg size (group key msg using CCMP as cipher)*/
#define GROUP_KEY_PAYLOAD_LEN_MIN sizeof(EAPOL_RSN_KEY) + GROUP_KEY_MIN_LEN
/* XXX - what if this doesn't get the key? */
static INT
AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* Return a pointer the the requested SA. If it doesn't exist create it. */
static PAIRPDCAP_SEC_ASSOCIATION
AirPDcapGetSaPtr(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
int sa_index;
/* search for a cached Security Association for supplied BSSID and STA MAC */
if ((sa_index=AirPDcapGetSa(ctx, id))==-1) {
/* create a new Security Association if it doesn't currently exist */
if ((sa_index=AirPDcapStoreSa(ctx, id))==-1) {
return NULL;
}
}
/* get the Security Association structure */
return &ctx->sa[sa_index];
}
static INT AirPDcapScanForKeys(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
AIRPDCAP_SEC_ASSOCIATION_ID id
)
{
const UCHAR *addr;
guint bodyLength;
PAIRPDCAP_SEC_ASSOCIATION sta_sa;
PAIRPDCAP_SEC_ASSOCIATION sa;
guint offset = 0;
const guint8 dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x88, 0x8E /* Type: 802.1X authentication */
};
const guint8 bt_dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */
0x00, 0x03 /* Type: Bluetooth Security */
};
const guint8 tdls_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */
0x02, /* Payload Type: TDLS */
0X0C /* Action Category: TDLS */
};
const EAPOL_RSN_KEY *pEAPKey;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapScanForKeys");
/* cache offset in the packet data */
offset = mac_header_len;
/* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */
if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=8;
/* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */
if (data[offset+1]!=3) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not EAPOL-Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* get and check the body length (IEEE 802.1X-2004, pg. 25) */
bodyLength=pntoh16(data+offset+2);
if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "EAPOL body too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip EAPOL MPDU and go to the first byte of the body */
offset+=4;
pEAPKey = (const EAPOL_RSN_KEY *) (data+offset);
/* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */
if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */
pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */
pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not valid key descriptor type", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* start with descriptor body */
offset+=1;
/* search for a cached Security Association for current BSSID and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "No SA for BSSID found", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_REQ_DATA;
}
/* It could be a Pairwise Key exchange, check */
if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE)
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Message too short for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 ||
AIRPDCAP_EAP_ACK(data[offset+1])!=1 ||
AIRPDCAP_EAP_MIC(data[offset]) != 1 ||
AIRPDCAP_EAP_SEC(data[offset]) != 1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Key bitfields not correct for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* force STA address to be the broadcast MAC so we create an SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
/* get the Security Association structure for the broadcast MAC and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */
/* get STA address */
if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) {
memcpy(id.sta, addr, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
#endif
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "SA not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
sta_sa = AirPDcapGetSaPtr(ctx, &id);
if (sta_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Try to extract the group key and install it in the SA */
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1));
} else if (memcmp(data+offset, tdls_header, 10) == 0) {
const guint8 *initiator, *responder;
guint8 action;
guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: TDLS Action Frame", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=10;
/* check if the packet is a TDLS response or confirm */
action = data[offset];
if (action!=1 && action!=2) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not Response nor confirm", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* check status */
offset++;
status=pntoh16(data+offset);
if (status!=0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "TDLS setup not successfull", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip Token + capabilities */
offset+=5;
/* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */
while(offset < (tot_len - 2)) {
if (data[offset] == 48) {
offset_rsne = offset;
} else if (data[offset] == 55) {
offset_fte = offset;
} else if (data[offset] == 56) {
offset_timeout = offset;
} else if (data[offset] == 101) {
offset_link = offset;
}
if (tot_len < offset + data[offset + 1] + 2) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
offset += data[offset + 1] + 2;
}
if (offset_rsne == 0 || offset_fte == 0 ||
offset_timeout == 0 || offset_link == 0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Cannot Find all necessary IEs", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Found RSNE/Fast BSS/Timeout Interval/Link IEs", AIRPDCAP_DEBUG_LEVEL_3);
/* Will create a Security Association between 2 STA. Need to get both MAC address */
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN);
} else {
memcpy(id.sta, responder, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN);
}
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
if (sa->validKey) {
if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) {
/* Already have valid key for this SA, no need to redo key derivation */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* We are opening a new session with the same two STA, save previous sa */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
sa->validKey = FALSE;
}
}
if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action)
== AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Skipping: not an EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
INT AirPDcapPacketProcess(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
UCHAR *decrypt_data,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
gboolean scanHandshake)
{
AIRPDCAP_SEC_ASSOCIATION_ID id;
UCHAR tmp_data[AIRPDCAP_MAX_CAPLEN];
guint tmp_len;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapPacketProcess");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
if (data==NULL || tot_len==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL data or length=0", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
/* check if the packet is of data or robust managment type */
if (!((AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_DATA) ||
(AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_MANAGEMENT &&
(AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DISASS ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DEAUTHENTICATION ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_ACTION)))) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "not data nor robust mgmt packet", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_DATA;
}
/* check correct packet size, to avoid wrong elaboration of encryption algorithms */
if (tot_len < (UINT)(mac_header_len+AIRPDCAP_CRYPTED_DATA_MINLEN)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "minimum length violated", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_WRONG_DATA_SIZE;
}
/* Assume that the decrypt_data field is at least this size. */
if (tot_len > AIRPDCAP_MAX_CAPLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "length too large", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* get STA/BSSID address */
if (AirPDcapGetSaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data), &id) != AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "STA/BSSID not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
/* check if data is encrypted (use the WEP bit in the Frame Control field) */
if (AIRPDCAP_WEP(data[1])==0) {
if (scanHandshake) {
/* data is sent in cleartext, check if is an authentication message or end the process */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Unencrypted data", AIRPDCAP_DEBUG_LEVEL_3);
return (AirPDcapScanForKeys(ctx, data, mac_header_len, tot_len, id));
}
return AIRPDCAP_RET_NO_DATA_ENCRYPTED;
} else {
PAIRPDCAP_SEC_ASSOCIATION sa;
int offset = 0;
/* get the Security Association structure for the STA and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* cache offset in the packet data (to scan encryption data) */
offset = mac_header_len;
if (decrypt_data==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "no decrypt buffer, use local", AIRPDCAP_DEBUG_LEVEL_3);
decrypt_data=tmp_data;
decrypt_len=&tmp_len;
}
/* create new header and data to modify */
*decrypt_len = tot_len;
memcpy(decrypt_data, data, *decrypt_len);
/* encrypted data */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Encrypted data", AIRPDCAP_DEBUG_LEVEL_3);
/* check the Extension IV to distinguish between WEP encryption and WPA encryption */
/* refer to IEEE 802.11i-2004, 8.2.1.2, pag.35 for WEP, */
/* IEEE 802.11i-2004, 8.3.2.2, pag. 45 for TKIP, */
/* IEEE 802.11i-2004, 8.3.3.2, pag. 57 for CCMP */
if (AIRPDCAP_EXTIV(data[offset+3])==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "WEP encryption", AIRPDCAP_DEBUG_LEVEL_3);
return AirPDcapWepMng(ctx, decrypt_data, mac_header_len, decrypt_len, key, sa, offset);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "TKIP or CCMP encryption", AIRPDCAP_DEBUG_LEVEL_3);
/* If index >= 1, then use the group key. This will not work if the AP is using
more than one group key simultaneously. I've not seen this in practice, however.
Usually an AP will rotate between the two key index values of 1 and 2 whenever
it needs to change the group key to be used. */
if (AIRPDCAP_KEY_INDEX(data[offset+3])>=1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "The key index >= 1. This is encrypted with a group key.", AIRPDCAP_DEBUG_LEVEL_3);
/* force STA address to broadcast MAC so we load the SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
/* search for a cached Security Association for current BSSID and broadcast MAC */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL)
return AIRPDCAP_RET_REQ_DATA;
}
/* Decrypt the packet using the appropriate SA */
if (AirPDcapRsnaMng(decrypt_data, mac_header_len, decrypt_len, key, sa, offset) == AIRPDCAP_RET_SUCCESS) {
/* If we successfully decrypted a packet, scan it to see if it contains a key handshake.
The group key handshake could be sent at any time the AP wants to change the key (such as when
it is using key rotation) and it also could be a rekey for the Pairwise key. So we must scan every packet. */
if (scanHandshake) {
return (AirPDcapScanForKeys(ctx, decrypt_data, mac_header_len, *decrypt_len, id));
} else {
return AIRPDCAP_RET_SUCCESS;
}
}
}
}
return AIRPDCAP_RET_UNSUCCESS;
}
INT AirPDcapSetKeys(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
INT i;
INT success;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapSetKeys");
if (ctx==NULL || keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "NULL context or NULL keys array", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
if (keys_nr>AIRPDCAP_MAX_KEYS_NR) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Keys number greater than maximum", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
/* clean key and SA collections before setting new ones */
AirPDcapInitContext(ctx);
/* check and insert keys */
for (i=0, success=0; i<(INT)keys_nr; i++) {
if (AirPDcapValidateKey(keys+i)==TRUE) {
if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PWD key", AIRPDCAP_DEBUG_LEVEL_4);
AirPDcapRsnaPwd2Psk(keys[i].UserPwd.Passphrase, keys[i].UserPwd.Ssid, keys[i].UserPwd.SsidLen, keys[i].KeyData.Wpa.Psk);
}
#ifdef _DEBUG
else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PMK key", AIRPDCAP_DEBUG_LEVEL_4);
} else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WEP key", AIRPDCAP_DEBUG_LEVEL_4);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a key", AIRPDCAP_DEBUG_LEVEL_4);
}
#endif
memcpy(&ctx->keys[success], &keys[i], sizeof(keys[i]));
success++;
}
}
ctx->keys_nr=success;
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return success;
}
static void
AirPDcapCleanKeys(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapCleanKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
return;
}
memset(ctx->keys, 0, sizeof(AIRPDCAP_KEY_ITEM) * AIRPDCAP_MAX_KEYS_NR);
ctx->keys_nr=0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "Keys collection cleaned!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
}
static void
AirPDcapRecurseCleanSA(
PAIRPDCAP_SEC_ASSOCIATION sa)
{
if (sa->next != NULL) {
AirPDcapRecurseCleanSA(sa->next);
g_free(sa->next);
sa->next = NULL;
}
}
static void
AirPDcapCleanSecAssoc(
PAIRPDCAP_CONTEXT ctx)
{
PAIRPDCAP_SEC_ASSOCIATION psa;
int i;
for (psa = ctx->sa, i = 0; i < AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; i++, psa++) {
/* To iterate is human, to recurse, divine */
AirPDcapRecurseCleanSA(psa);
}
}
INT AirPDcapGetKeys(
const PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
UINT i;
UINT j;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapGetKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return 0;
} else if (keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL keys array", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return (INT)ctx->keys_nr;
} else {
for (i=0, j=0; i<ctx->keys_nr && i<keys_nr && i<AIRPDCAP_MAX_KEYS_NR; i++) {
memcpy(&keys[j], &ctx->keys[i], sizeof(keys[j]));
j++;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "Got a key", AIRPDCAP_DEBUG_LEVEL_5);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return j;
}
}
/*
* XXX - This won't be reliable if a packet containing SSID "B" shows
* up in the middle of a 4-way handshake for SSID "A".
* We should probably use a small array or hash table to keep multiple
* SSIDs.
*/
INT AirPDcapSetLastSSID(
PAIRPDCAP_CONTEXT ctx,
CHAR *pkt_ssid,
size_t pkt_ssid_len)
{
if (!ctx || !pkt_ssid || pkt_ssid_len < 1 || pkt_ssid_len > WPA_SSID_MAX_SIZE)
return AIRPDCAP_RET_UNSUCCESS;
memcpy(ctx->pkt_ssid, pkt_ssid, pkt_ssid_len);
ctx->pkt_ssid_len = pkt_ssid_len;
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapInitContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapInitContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
ctx->pkt_ssid_len = 0;
memset(ctx->sa, 0, AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR * sizeof(AIRPDCAP_SEC_ASSOCIATION));
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "Context initialized!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapDestroyContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapDestroyContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
AirPDcapCleanSecAssoc(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "Context destroyed!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Internal function definitions */
#ifdef __cplusplus
extern "C" {
#endif
static INT
AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
INT ret_value=1;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
if (*decrypt_len > try_data_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* allocate a temp buffer for the decryption loop */
try_data=(UCHAR *)g_malloc(try_data_len);
/* start of loop added by GCS */
for(/* sa */; sa != NULL ;sa=sa->next) {
if (sa->validKey==FALSE) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Key not yet valid", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
/* copy the encrypted data into a temp buffer */
memcpy(try_data, decrypt_data, *decrypt_len);
if (sa->wpa.key_ver==1) {
/* CCMP -> HMAC-MD5 is the EAPOL-Key MIC, RC4 is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP", AIRPDCAP_DEBUG_LEVEL_3);
DEBUG_DUMP("ptk", sa->wpa.ptk, 64);
DEBUG_DUMP("ptk portion used", AIRPDCAP_GET_TK(sa->wpa.ptk), 16);
ret_value=AirPDcapTkipDecrypt(try_data+offset, *decrypt_len-offset, try_data+AIRPDCAP_TA_OFFSET, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP failed!", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) and ICV (4bytes) from the end of packet */
*decrypt_len-=12;
break;
} else {
/* AES-CCMP -> HMAC-SHA1-128 is the EAPOL-Key MIC, AES wep_key wrap is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP", AIRPDCAP_DEBUG_LEVEL_3);
ret_value=AirPDcapCcmpDecrypt(try_data, mac_header_len, (INT)*decrypt_len, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value)
continue;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) from the end of packet */
*decrypt_len-=8;
break;
}
}
/* end of loop */
/* none of the keys worked */
if(sa == NULL) {
g_free(try_data);
return ret_value;
}
if (*decrypt_len > try_data_len || *decrypt_len < 8) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
g_free(try_data);
return AIRPDCAP_RET_UNSUCCESS;
}
/* copy the decrypted data into the decrypt buffer GCS*/
memcpy(decrypt_data, try_data, *decrypt_len);
g_free(try_data);
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove TKIP/CCMP header */
offset = mac_header_len;
*decrypt_len-=8;
memmove(decrypt_data+offset, decrypt_data+offset+8, *decrypt_len-offset);
if (key!=NULL) {
if (sa->key!=NULL)
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
else
memset(key, 0, sizeof(AIRPDCAP_KEY_ITEM));
memcpy(key->KeyData.Wpa.Ptk, sa->wpa.ptk, AIRPDCAP_WPA_PTK_LEN); /* copy the PTK to the key structure for future use by wireshark */
if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_TKIP;
else if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_CCMP;
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
UCHAR wep_key[AIRPDCAP_WEP_KEY_MAXLEN+AIRPDCAP_WEP_IVLEN];
size_t keylen;
INT ret_value=1;
INT key_index;
AIRPDCAP_KEY_ITEM *tmp_key;
UINT8 useCache=FALSE;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
try_data = (UCHAR *)g_malloc(try_data_len);
if (sa->key!=NULL)
useCache=TRUE;
for (key_index=0; key_index<(INT)ctx->keys_nr; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
tmp_key=&ctx->keys[key_index];
} else {
if (sa->key!=NULL && sa->key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try cached WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Cached key is not valid, try another WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WEP keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
memset(wep_key, 0, sizeof(wep_key));
memcpy(try_data, decrypt_data, *decrypt_len);
/* Costruct the WEP seed: copy the IV in first 3 bytes and then the WEP key (refer to 802-11i-2004, 8.2.1.4.3, pag. 36) */
memcpy(wep_key, try_data+mac_header_len, AIRPDCAP_WEP_IVLEN);
keylen=tmp_key->KeyData.Wep.WepKeyLen;
memcpy(wep_key+AIRPDCAP_WEP_IVLEN, tmp_key->KeyData.Wep.WepKey, keylen);
ret_value=AirPDcapWepDecrypt(wep_key,
keylen+AIRPDCAP_WEP_IVLEN,
try_data + (mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN),
*decrypt_len-(mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN+AIRPDCAP_CRC_LEN));
if (ret_value == AIRPDCAP_RET_SUCCESS)
memcpy(decrypt_data, try_data, *decrypt_len);
}
if (!ret_value && tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
/* the tried key is the correct one, cached in the Security Association */
sa->key=tmp_key;
if (key!=NULL) {
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
}
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
g_free(try_data);
if (ret_value)
return AIRPDCAP_RET_UNSUCCESS;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "WEP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove ICV (4bytes) from the end of packet */
*decrypt_len-=4;
if (*decrypt_len < 4) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Decryption length too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove IC header */
offset = mac_header_len;
*decrypt_len-=4;
memmove(decrypt_data+offset, decrypt_data+offset+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN, *decrypt_len-offset);
return AIRPDCAP_RET_SUCCESS;
}
/* Refer to IEEE 802.11i-2004, 8.5.3, pag. 85 */
static INT
AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
{
AIRPDCAP_KEY_ITEM *tmp_key, *tmp_pkt_key, pkt_key;
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
INT key_index;
INT ret_value=1;
UCHAR useCache=FALSE;
UCHAR eapol[AIRPDCAP_EAPOL_MAX_LEN];
USHORT eapol_len;
if (sa->key!=NULL)
useCache=TRUE;
/* a 4-way handshake packet use a Pairwise key type (IEEE 802.11i-2004, pg. 79) */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=1) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Group/STAKey message (not used)", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* TODO timeouts? */
/* TODO consider key-index */
/* TODO considera Deauthentications */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake...", AIRPDCAP_DEBUG_LEVEL_5);
/* manage 4-way handshake packets; this step completes the 802.1X authentication process (IEEE 802.11i-2004, pag. 85) */
/* message 1: Authenticator->Supplicant (Sec=0, Mic=0, Ack=1, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=ANonce, MIC=0) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 1", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 1, the Supplicant determines whether the Key Replay Counter field value has been */
/* used before with the current PMKSA. If the Key Replay Counter field value is less than or equal to the current */
/* local value, the Supplicant discards the message. */
/* -> not checked, the Authenticator will be send another Message 1 (hopefully!) */
/* This saves the sa since we are reauthenticating which will overwrite our current sa GCS*/
if( sa->handshake >= 2) {
tmp_sa= g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->validKey=FALSE;
sa->next=tmp_sa;
}
/* save ANonce (from authenticator) to derive the PTK with the SNonce (from the 2 message) */
memcpy(sa->wpa.nonce, data+offset+12, 32);
/* get the Key Descriptor Version (to select algorithm used in decryption -CCMP or TKIP-) */
sa->wpa.key_ver=AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1]);
sa->handshake=1;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* message 2|4: Supplicant->Authenticator (Sec=0|1, Mic=1, Ack=0, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=SNonce|0, MIC=MIC(KCK,EAPOL)) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==0 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
/* Check key data length to differentiate between message 2 or 4, same as in epan/dissectors/packet-ieee80211.c */
if (pntoh16(data+offset+92)) {
/* message 2 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 2", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 2, the Authenticator checks that the key replay counter corresponds to the */
/* outstanding Message 1. If not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, */
/* the Authenticator silently discards Message 2. */
/* -> not checked; the Supplicant will send another message 2 (hopefully!) */
/* now you can derive the PTK */
for (key_index=0; key_index<(INT)ctx->keys_nr || useCache; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
} else {
/* there is a cached key in the security association, if it's a WPA key try it... */
if (sa->key!=NULL &&
(sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try cached WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Cached key is of a wrong type, try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WPA keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)
{
if (tmp_key->KeyType == AIRPDCAP_KEY_TYPE_WPA_PWD && tmp_key->UserPwd.SsidLen == 0 && ctx->pkt_ssid_len > 0 && ctx->pkt_ssid_len <= AIRPDCAP_WPA_SSID_MAX_LEN) {
/* We have a "wildcard" SSID. Use the one from the packet. */
memcpy(&pkt_key, tmp_key, sizeof(pkt_key));
memcpy(&pkt_key.UserPwd.Ssid, ctx->pkt_ssid, ctx->pkt_ssid_len);
pkt_key.UserPwd.SsidLen = ctx->pkt_ssid_len;
AirPDcapRsnaPwd2Psk(pkt_key.UserPwd.Passphrase, pkt_key.UserPwd.Ssid,
pkt_key.UserPwd.SsidLen, pkt_key.KeyData.Wpa.Psk);
tmp_pkt_key = &pkt_key;
} else {
tmp_pkt_key = tmp_key;
}
/* derive the PTK from the BSSID, STA MAC, PMK, SNonce, ANonce */
AirPDcapRsnaPrfX(sa, /* authenticator nonce, bssid, station mac */
tmp_pkt_key->KeyData.Wpa.Psk, /* PSK == PMK */
data+offset+12, /* supplicant nonce */
512,
sa->wpa.ptk);
/* verify the MIC (compare the MIC in the packet included in this message with a MIC calculated with the PTK) */
eapol_len=pntoh16(data+offset-3)+4;
memcpy(eapol, &data[offset-5], (eapol_len<AIRPDCAP_EAPOL_MAX_LEN?eapol_len:AIRPDCAP_EAPOL_MAX_LEN));
ret_value=AirPDcapRsnaMicCheck(eapol, /* eapol frame (header also) */
eapol_len, /* eapol frame length */
sa->wpa.ptk, /* Key Confirmation Key */
AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1])); /* EAPOL-Key description version */
/* If the MIC is valid, the Authenticator checks that the RSN information element bit-wise matches */
/* that from the (Re)Association Request message. */
/* i) TODO If these are not exactly the same, the Authenticator uses MLME-DEAUTHENTICATE.request */
/* primitive to terminate the association. */
/* ii) If they do match bit-wise, the Authenticator constructs Message 3. */
}
if (!ret_value &&
(tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK))
{
/* the temporary key is the correct one, cached in the Security Association */
sa->key=tmp_key;
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
if (ret_value) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "handshake step failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
sa->handshake=2;
sa->validKey=TRUE; /* we can use the key to decode, even if we have not captured the other eapol packets */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* message 4 */
/* TODO "Note that when the 4-Way Handshake is first used Message 4 is sent in the clear." */
/* TODO check MIC and Replay Counter */
/* On reception of Message 4, the Authenticator verifies that the Key Replay Counter field value is one */
/* that it used on this 4-Way Handshake; if it is not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, the */
/* Authenticator silently discards Message 4. */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 4", AIRPDCAP_DEBUG_LEVEL_3);
sa->handshake=4;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
}
/* message 3: Authenticator->Supplicant (Sec=1, Mic=1, Ack=1, Inst=0/1, Key=1(pairwise), KeyRSC=???, Nonce=ANonce, MIC=1) */
if (AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
const EAPOL_RSN_KEY *pEAPKey;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 3", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 3, the Supplicant silently discards the message if the Key Replay Counter field */
/* value has already been used or if the ANonce value in Message 3 differs from the ANonce value in Message 1. */
/* -> not checked, the Authenticator will send another message 3 (hopefully!) */
/* TODO check page 88 (RNS) */
/* If using WPA2 PSK, message 3 will contain an RSN for the group key (GTK KDE).
In order to properly support decrypting WPA2-PSK packets, we need to parse this to get the group key. */
pEAPKey = (const EAPOL_RSN_KEY *)(&(data[offset-1]));
if (pEAPKey->type == AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR){
PAIRPDCAP_SEC_ASSOCIATION broadcast_sa;
AIRPDCAP_SEC_ASSOCIATION_ID id;
/* Get broadcacst SA for the current BSSID */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, sa->saId.bssid, AIRPDCAP_MAC_LEN);
broadcast_sa = AirPDcapGetSaPtr(ctx, &id);
if (broadcast_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sa->wpa.ptk+16, broadcast_sa, tot_len-offset+1));
}
}
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
static INT
AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
{
UCHAR mic[AIRPDCAP_WPA_MICKEY_LEN];
UCHAR c_mic[20]; /* MIC 16 byte, the HMAC-SHA1 use a buffer of 20 bytes */
/* copy the MIC from the EAPOL packet */
memcpy(mic, eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, AIRPDCAP_WPA_MICKEY_LEN);
/* set to 0 the MIC in the EAPOL packet (to calculate the MIC) */
memset(eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, 0, AIRPDCAP_WPA_MICKEY_LEN);
if (key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP) {
/* use HMAC-MD5 for the EAPOL-Key MIC */
md5_hmac(eapol, eapol_len, KCK, AIRPDCAP_WPA_KCK_LEN, c_mic);
} else if (key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP) {
/* use HMAC-SHA1-128 for the EAPOL-Key MIC */
sha1_hmac(KCK, AIRPDCAP_WPA_KCK_LEN, eapol, eapol_len, c_mic);
} else
/* key descriptor version not recognized */
return AIRPDCAP_RET_UNSUCCESS;
/* compare calculated MIC with the Key MIC and return result (0 means success) */
return memcmp(mic, c_mic, AIRPDCAP_WPA_MICKEY_LEN);
}
static INT
AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
{
size_t len;
UCHAR ret=TRUE;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
if (key==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "NULL key", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
return FALSE;
}
switch (key->KeyType) {
case AIRPDCAP_KEY_TYPE_WEP:
/* check key size limits */
len=key->KeyData.Wep.WepKeyLen;
if (len<AIRPDCAP_WEP_KEY_MINLEN || len>AIRPDCAP_WEP_KEY_MAXLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WEP key: key length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WEP_40:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_40_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WEP_104:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_104_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
/* check passphrase and SSID size limits */
len=strlen(key->UserPwd.Passphrase);
if (len<AIRPDCAP_WPA_PASSPHRASE_MIN_LEN || len>AIRPDCAP_WPA_PASSPHRASE_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: passphrase length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
len=key->UserPwd.SsidLen;
if (len>AIRPDCAP_WPA_SSID_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: ssid length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
break;
default:
ret=FALSE;
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapValidateKey");
return ret;
}
static INT
AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT sa_index;
if (ctx->sa_index!=-1) {
/* at least one association was stored */
/* search for the association from sa_index to 0 (most recent added) */
for (sa_index=ctx->sa_index; sa_index>=0; sa_index--) {
if (ctx->sa[sa_index].used) {
if (memcmp(id, &(ctx->sa[sa_index].saId), sizeof(AIRPDCAP_SEC_ASSOCIATION_ID))==0) {
ctx->index=sa_index;
return sa_index;
}
}
}
}
return -1;
}
static INT
AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT last_free;
if (ctx->first_free_index>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
if (ctx->sa[ctx->first_free_index].used) {
/* last addition was in the middle of the array (and the first_free_index was just incremented by 1) */
/* search for a free space from the first_free_index to AIRPDCAP_STA_INFOS_NR (to avoid free blocks in */
/* the middle) */
for (last_free=ctx->first_free_index; last_free<AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; last_free++)
if (!ctx->sa[last_free].used)
break;
if (last_free>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
/* store first free space index */
ctx->first_free_index=last_free;
}
/* use this info */
ctx->index=ctx->first_free_index;
/* reset the info structure */
memset(ctx->sa+ctx->index, 0, sizeof(AIRPDCAP_SEC_ASSOCIATION));
ctx->sa[ctx->index].used=1;
/* set the info structure */
memcpy(&(ctx->sa[ctx->index].saId), id, sizeof(AIRPDCAP_SEC_ASSOCIATION_ID));
/* increment by 1 the first_free_index (heuristic) */
ctx->first_free_index++;
/* set the sa_index if the added index is greater the the sa_index */
if (ctx->index > ctx->sa_index)
ctx->sa_index=ctx->index;
return ctx->index;
}
static INT
AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
if ((AIRPDCAP_TYPE(frame->fc[0])==AIRPDCAP_TYPE_DATA) &&
(AIRPDCAP_DS_BITS(frame->fc[1]) == 0) &&
(memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) != 0) &&
(memcmp(frame->addr1, frame->addr3, AIRPDCAP_MAC_LEN) != 0)) {
/* DATA frame with fromDS=0 ToDS=0 and neither RA or SA is BSSID
=> TDLS traffic. Use highest MAC address for bssid */
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id->sta, frame->addr1, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr2, AIRPDCAP_MAC_LEN);
} else {
memcpy(id->sta, frame->addr2, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr1, AIRPDCAP_MAC_LEN);
}
} else {
const UCHAR *addr;
/* Normal Case: SA between STA and AP */
if ((addr = AirPDcapGetBssidAddress(frame)) != NULL) {
memcpy(id->bssid, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
if ((addr = AirPDcapGetStaAddress(frame)) != NULL) {
memcpy(id->sta, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
}
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "BSSID_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->bssid[0],id->bssid[1],id->bssid[2],id->bssid[3],id->bssid[4],id->bssid[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
g_snprintf(msgbuf, MSGBUF_LEN, "STA_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->sta[0],id->sta[1],id->sta[2],id->sta[3],id->sta[4],id->sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
return AIRPDCAP_RET_SUCCESS;
}
/*
* AirPDcapGetBssidAddress() and AirPDcapGetBssidAddress() are used for
* key caching. In each case, it's more important to return a value than
* to return a _correct_ value, so we fudge addresses in some cases, e.g.
* the BSSID in bridged connections.
* FromDS ToDS Sta BSSID
* 0 0 addr1/2 addr3
* 0 1 addr2 addr1
* 1 0 addr1 addr2
* 1 1 addr2 addr1
*/
static const UCHAR *
AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
if (memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) == 0)
return frame->addr1;
else
return frame->addr2;
case 1:
return frame->addr2;
case 2:
return frame->addr1;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
static const UCHAR *
AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
return frame->addr3;
case 1:
return frame->addr1;
case 2:
return frame->addr2;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) > 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
/* Function used to derive the PTK. Refer to IEEE 802.11I-2004, pag. 74
* and IEEE 802.11i-2004, pag. 164 */
static void
AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
{
UINT8 i;
UCHAR R[100];
INT offset=sizeof("Pairwise key expansion");
UCHAR output[80]; /* allow for sha1 overflow. */
memset(R, 0, 100);
memcpy(R, "Pairwise key expansion", offset);
/* Min(AA, SPA) || Max(AA, SPA) */
if (memcmp(sa->saId.sta, sa->saId.bssid, AIRPDCAP_MAC_LEN) < 0)
{
memcpy(R + offset, sa->saId.sta, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.bssid, AIRPDCAP_MAC_LEN);
}
else
{
memcpy(R + offset, sa->saId.bssid, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.sta, AIRPDCAP_MAC_LEN);
}
offset+=AIRPDCAP_MAC_LEN*2;
/* Min(ANonce,SNonce) || Max(ANonce,SNonce) */
if( memcmp(snonce, sa->wpa.nonce, 32) < 0 )
{
memcpy(R + offset, snonce, 32);
memcpy(R + offset + 32, sa->wpa.nonce, 32);
}
else
{
memcpy(R + offset, sa->wpa.nonce, 32);
memcpy(R + offset + 32, snonce, 32);
}
offset+=32*2;
for(i = 0; i < (x+159)/160; i++)
{
R[offset] = i;
sha1_hmac(pmk, 32, R, 100, &output[20 * i]);
}
memcpy(ptk, output, x/8);
}
#define MAX_SSID_LENGTH 32 /* maximum SSID length */
static INT
AirPDcapRsnaPwd2PskStep(
const guint8 *ppBytes,
const guint ppLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
{
UCHAR digest[MAX_SSID_LENGTH+4]; /* SSID plus 4 bytes of count */
UCHAR digest1[SHA1_DIGEST_LEN];
INT i, j;
if (ssidLength > MAX_SSID_LENGTH) {
/* This "should not happen" */
return AIRPDCAP_RET_UNSUCCESS;
}
memset(digest, 0, sizeof digest);
memset(digest1, 0, sizeof digest1);
/* U1 = PRF(P, S || INT(i)) */
memcpy(digest, ssid, ssidLength);
digest[ssidLength] = (UCHAR)((count>>24) & 0xff);
digest[ssidLength+1] = (UCHAR)((count>>16) & 0xff);
digest[ssidLength+2] = (UCHAR)((count>>8) & 0xff);
digest[ssidLength+3] = (UCHAR)(count & 0xff);
sha1_hmac(ppBytes, ppLength, digest, (guint32) ssidLength+4, digest1);
/* output = U1 */
memcpy(output, digest1, SHA1_DIGEST_LEN);
for (i = 1; i < iterations; i++) {
/* Un = PRF(P, Un-1) */
sha1_hmac(ppBytes, ppLength, digest1, SHA1_DIGEST_LEN, digest);
memcpy(digest1, digest, SHA1_DIGEST_LEN);
/* output = output xor Un */
for (j = 0; j < SHA1_DIGEST_LEN; j++) {
output[j] ^= digest[j];
}
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
{
UCHAR m_output[2*SHA1_DIGEST_LEN];
GByteArray *pp_ba = g_byte_array_new();
memset(m_output, 0, 2*SHA1_DIGEST_LEN);
if (!uri_str_to_bytes(passphrase, pp_ba)) {
g_byte_array_free(pp_ba, TRUE);
return 0;
}
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 1, m_output);
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 2, &m_output[SHA1_DIGEST_LEN]);
memcpy(output, m_output, AIRPDCAP_WPA_PSK_LEN);
g_byte_array_free(pp_ba, TRUE);
return 0;
}
/*
* Returns the decryption_key_t struct given a string describing the key.
* Returns NULL if the input_string cannot be parsed.
*/
decryption_key_t*
parse_key_string(gchar* input_string, guint8 key_type)
{
gchar *key, *tmp_str;
gchar *ssid;
GString *key_string = NULL;
GByteArray *ssid_ba = NULL, *key_ba;
gboolean res;
gchar **tokens;
guint n = 0;
decryption_key_t *dk;
if(input_string == NULL)
return NULL;
/*
* Parse the input_string. WEP and WPA will be just a string
* of hexadecimal characters (if key is wrong, null will be
* returned...).
* WPA-PWD should be in the form
* <key data>[:<ssid>]
*/
switch(key_type)
{
case AIRPDCAP_KEY_TYPE_WEP:
case AIRPDCAP_KEY_TYPE_WEP_40:
case AIRPDCAP_KEY_TYPE_WEP_104:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
if (res && key_ba->len > 0) {
/* Key is correct! It was probably an 'old style' WEP key */
/* Create the decryption_key_t structure, fill it and return it*/
dk = (decryption_key_t *)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WEP;
/* XXX - The current key handling code in the GUI requires
* no separators and lower case */
tmp_str = bytes_to_str(NULL, key_ba->data, key_ba->len);
dk->key = g_string_new(tmp_str);
g_string_ascii_down(dk->key);
dk->bits = key_ba->len * 8;
dk->ssid = NULL;
wmem_free(NULL, tmp_str);
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Key doesn't work */
g_byte_array_free(key_ba, TRUE);
return NULL;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
tokens = g_strsplit(input_string,":",0);
/* Tokens is a null termiated array of strings ... */
while(tokens[n] != NULL)
n++;
if(n < 1)
{
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
/*
* The first token is the key
*/
key = g_strdup(tokens[0]);
ssid = NULL;
/* Maybe there is a second token (an ssid, if everything else is ok) */
if(n >= 2)
{
ssid = g_strdup(tokens[1]);
}
/* Create a new string */
key_string = g_string_new(key);
ssid_ba = NULL;
/* Two (or more) tokens mean that the user entered a WPA-PWD key ... */
if( ((key_string->len) > WPA_KEY_MAX_CHAR_SIZE) || ((key_string->len) < WPA_KEY_MIN_CHAR_SIZE))
{
g_string_free(key_string, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid != NULL) /* more than two tokens found, means that the user specified the ssid */
{
ssid_ba = g_byte_array_new();
if (! uri_str_to_bytes(ssid, ssid_ba)) {
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid_ba->len > WPA_SSID_MAX_CHAR_SIZE)
{
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PWD;
dk->key = g_string_new(key);
dk->bits = 256; /* This is the length of the array pf bytes that will be generated using key+ssid ...*/
dk->ssid = byte_array_dup(ssid_ba); /* NULL if ssid_ba is NULL */
g_string_free(key_string, TRUE);
if (ssid_ba != NULL)
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
if(ssid != NULL)
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return dk;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
/* Two tokens means that the user should have entered a WPA-BIN key ... */
if(!res || ((key_ba->len) != WPA_PSK_KEY_SIZE))
{
g_byte_array_free(key_ba, TRUE);
/* No ssid has been created ... */
return NULL;
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PSK;
dk->key = g_string_new(input_string);
dk->bits = (guint) dk->key->len * 4;
dk->ssid = NULL;
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Type not supported */
return NULL;
}
void
free_key_string(decryption_key_t *dk)
{
if (dk->key)
g_string_free(dk->key, TRUE);
if (dk->ssid)
g_byte_array_free(dk->ssid, TRUE);
g_free(dk);
}
/*
* Returns a newly allocated string representing the given decryption_key_t
* struct, or NULL if something is wrong...
*/
gchar*
get_key_string(decryption_key_t* dk)
{
gchar* output_string = NULL;
if(dk == NULL || dk->key == NULL)
return NULL;
switch(dk->type) {
case AIRPDCAP_KEY_TYPE_WEP:
output_string = g_strdup(dk->key->str);
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
if(dk->ssid == NULL)
output_string = g_strdup(dk->key->str);
else
output_string = g_strdup_printf("%s:%s",
dk->key->str, format_uri(dk->ssid, ":"));
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
output_string = g_strdup(dk->key->str);
break;
default:
return NULL;
}
return output_string;
}
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
{
sha256_hmac_context sha_ctx;
aes_cmac_ctx aes_ctx;
const guint8 *snonce, *anonce, *initiator, *responder, *bssid;
guint8 key_input[SHA256_DIGEST_LEN];
guint8 mic[16], iter[2], length[2], seq_num = action + 1;
/* Get key input */
anonce = &data[offset_fte + 20];
snonce = &data[offset_fte + 52];
sha256_starts(&(sha_ctx.ctx));
if (memcmp(anonce, snonce, AIRPDCAP_WPA_NONCE_LEN) < 0) {
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
} else {
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
}
sha256_finish(&(sha_ctx.ctx), key_input);
/* Derive key */
bssid = &data[offset_link + 2];
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
sha256_hmac_starts(&sha_ctx, key_input, SHA256_DIGEST_LEN);
iter[0] = 1;
iter[1] = 0;
sha256_hmac_update(&sha_ctx, (const guint8 *)&iter, 2);
sha256_hmac_update(&sha_ctx, "TDLS PMK", 8);
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
} else {
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
}
sha256_hmac_update(&sha_ctx, bssid, AIRPDCAP_MAC_LEN);
length[0] = 256 & 0xff;
length[1] = (256 >> 8) & 0xff;
sha256_hmac_update(&sha_ctx, (const guint8 *)&length, 2);
sha256_hmac_finish(&sha_ctx, key_input);
/* Check MIC */
aes_cmac_encrypt_starts(&aes_ctx, key_input, 16);
aes_cmac_encrypt_update(&aes_ctx, initiator, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, responder, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, &seq_num, 1);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_link], data[offset_link + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_rsne], data[offset_rsne + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_timeout], data[offset_timeout + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte], 4);
memset(mic, 0, 16);
aes_cmac_encrypt_update(&aes_ctx, mic, 16);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte + 20], data[offset_fte + 1] + 2 - 20);
aes_cmac_encrypt_finish(&aes_ctx, mic);
if (memcmp(mic, &data[offset_fte + 4],16)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verification failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
memcpy(AIRPDCAP_GET_TK(sa->wpa.ptk), &key_input[16], 16);
memcpy(sa->wpa.nonce, snonce, AIRPDCAP_WPA_NONCE_LEN);
sa->validKey = TRUE;
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verified", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5106_0 |
crossvul-cpp_data_good_5501_0 | /*
* Copyright (C) 2001 MandrakeSoft S.A.
* Copyright 2010 Red Hat, Inc. and/or its affiliates.
*
* MandrakeSoft S.A.
* 43, rue d'Aboukir
* 75002 Paris - France
* http://www.linux-mandrake.com/
* http://www.mandrakesoft.com/
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Yunhong Jiang <yunhong.jiang@intel.com>
* Yaozu (Eddie) Dong <eddie.dong@intel.com>
* Based on Xen 3.1 code.
*/
#include <linux/kvm_host.h>
#include <linux/kvm.h>
#include <linux/mm.h>
#include <linux/highmem.h>
#include <linux/smp.h>
#include <linux/hrtimer.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <asm/processor.h>
#include <asm/page.h>
#include <asm/current.h>
#include <trace/events/kvm.h>
#include "ioapic.h"
#include "lapic.h"
#include "irq.h"
#if 0
#define ioapic_debug(fmt,arg...) printk(KERN_WARNING fmt,##arg)
#else
#define ioapic_debug(fmt, arg...)
#endif
static int ioapic_service(struct kvm_ioapic *vioapic, int irq,
bool line_status);
static unsigned long ioapic_read_indirect(struct kvm_ioapic *ioapic,
unsigned long addr,
unsigned long length)
{
unsigned long result = 0;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
result = ((((IOAPIC_NUM_PINS - 1) & 0xff) << 16)
| (IOAPIC_VERSION_ID & 0xff));
break;
case IOAPIC_REG_APIC_ID:
case IOAPIC_REG_ARB_ID:
result = ((ioapic->id & 0xf) << 24);
break;
default:
{
u32 redir_index = (ioapic->ioregsel - 0x10) >> 1;
u64 redir_content;
if (redir_index < IOAPIC_NUM_PINS)
redir_content =
ioapic->redirtbl[redir_index].bits;
else
redir_content = ~0ULL;
result = (ioapic->ioregsel & 0x1) ?
(redir_content >> 32) & 0xffffffff :
redir_content & 0xffffffff;
break;
}
}
return result;
}
static void rtc_irq_eoi_tracking_reset(struct kvm_ioapic *ioapic)
{
ioapic->rtc_status.pending_eoi = 0;
bitmap_zero(ioapic->rtc_status.dest_map.map, KVM_MAX_VCPU_ID);
}
static void kvm_rtc_eoi_tracking_restore_all(struct kvm_ioapic *ioapic);
static void rtc_status_pending_eoi_check_valid(struct kvm_ioapic *ioapic)
{
if (WARN_ON(ioapic->rtc_status.pending_eoi < 0))
kvm_rtc_eoi_tracking_restore_all(ioapic);
}
static void __rtc_irq_eoi_tracking_restore_one(struct kvm_vcpu *vcpu)
{
bool new_val, old_val;
struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic;
struct dest_map *dest_map = &ioapic->rtc_status.dest_map;
union kvm_ioapic_redirect_entry *e;
e = &ioapic->redirtbl[RTC_GSI];
if (!kvm_apic_match_dest(vcpu, NULL, 0, e->fields.dest_id,
e->fields.dest_mode))
return;
new_val = kvm_apic_pending_eoi(vcpu, e->fields.vector);
old_val = test_bit(vcpu->vcpu_id, dest_map->map);
if (new_val == old_val)
return;
if (new_val) {
__set_bit(vcpu->vcpu_id, dest_map->map);
dest_map->vectors[vcpu->vcpu_id] = e->fields.vector;
ioapic->rtc_status.pending_eoi++;
} else {
__clear_bit(vcpu->vcpu_id, dest_map->map);
ioapic->rtc_status.pending_eoi--;
rtc_status_pending_eoi_check_valid(ioapic);
}
}
void kvm_rtc_eoi_tracking_restore_one(struct kvm_vcpu *vcpu)
{
struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic;
spin_lock(&ioapic->lock);
__rtc_irq_eoi_tracking_restore_one(vcpu);
spin_unlock(&ioapic->lock);
}
static void kvm_rtc_eoi_tracking_restore_all(struct kvm_ioapic *ioapic)
{
struct kvm_vcpu *vcpu;
int i;
if (RTC_GSI >= IOAPIC_NUM_PINS)
return;
rtc_irq_eoi_tracking_reset(ioapic);
kvm_for_each_vcpu(i, vcpu, ioapic->kvm)
__rtc_irq_eoi_tracking_restore_one(vcpu);
}
static void rtc_irq_eoi(struct kvm_ioapic *ioapic, struct kvm_vcpu *vcpu)
{
if (test_and_clear_bit(vcpu->vcpu_id,
ioapic->rtc_status.dest_map.map)) {
--ioapic->rtc_status.pending_eoi;
rtc_status_pending_eoi_check_valid(ioapic);
}
}
static bool rtc_irq_check_coalesced(struct kvm_ioapic *ioapic)
{
if (ioapic->rtc_status.pending_eoi > 0)
return true; /* coalesced */
return false;
}
static int ioapic_set_irq(struct kvm_ioapic *ioapic, unsigned int irq,
int irq_level, bool line_status)
{
union kvm_ioapic_redirect_entry entry;
u32 mask = 1 << irq;
u32 old_irr;
int edge, ret;
entry = ioapic->redirtbl[irq];
edge = (entry.fields.trig_mode == IOAPIC_EDGE_TRIG);
if (!irq_level) {
ioapic->irr &= ~mask;
ret = 1;
goto out;
}
/*
* Return 0 for coalesced interrupts; for edge-triggered interrupts,
* this only happens if a previous edge has not been delivered due
* do masking. For level interrupts, the remote_irr field tells
* us if the interrupt is waiting for an EOI.
*
* RTC is special: it is edge-triggered, but userspace likes to know
* if it has been already ack-ed via EOI because coalesced RTC
* interrupts lead to time drift in Windows guests. So we track
* EOI manually for the RTC interrupt.
*/
if (irq == RTC_GSI && line_status &&
rtc_irq_check_coalesced(ioapic)) {
ret = 0;
goto out;
}
old_irr = ioapic->irr;
ioapic->irr |= mask;
if (edge)
ioapic->irr_delivered &= ~mask;
if ((edge && old_irr == ioapic->irr) ||
(!edge && entry.fields.remote_irr)) {
ret = 0;
goto out;
}
ret = ioapic_service(ioapic, irq, line_status);
out:
trace_kvm_ioapic_set_irq(entry.bits, irq, ret == 0);
return ret;
}
static void kvm_ioapic_inject_all(struct kvm_ioapic *ioapic, unsigned long irr)
{
u32 idx;
rtc_irq_eoi_tracking_reset(ioapic);
for_each_set_bit(idx, &irr, IOAPIC_NUM_PINS)
ioapic_set_irq(ioapic, idx, 1, true);
kvm_rtc_eoi_tracking_restore_all(ioapic);
}
void kvm_ioapic_scan_entry(struct kvm_vcpu *vcpu, ulong *ioapic_handled_vectors)
{
struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic;
struct dest_map *dest_map = &ioapic->rtc_status.dest_map;
union kvm_ioapic_redirect_entry *e;
int index;
spin_lock(&ioapic->lock);
/* Make sure we see any missing RTC EOI */
if (test_bit(vcpu->vcpu_id, dest_map->map))
__set_bit(dest_map->vectors[vcpu->vcpu_id],
ioapic_handled_vectors);
for (index = 0; index < IOAPIC_NUM_PINS; index++) {
e = &ioapic->redirtbl[index];
if (e->fields.trig_mode == IOAPIC_LEVEL_TRIG ||
kvm_irq_has_notifier(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index) ||
index == RTC_GSI) {
if (kvm_apic_match_dest(vcpu, NULL, 0,
e->fields.dest_id, e->fields.dest_mode) ||
(e->fields.trig_mode == IOAPIC_EDGE_TRIG &&
kvm_apic_pending_eoi(vcpu, e->fields.vector)))
__set_bit(e->fields.vector,
ioapic_handled_vectors);
}
}
spin_unlock(&ioapic->lock);
}
void kvm_vcpu_request_scan_ioapic(struct kvm *kvm)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
if (!ioapic)
return;
kvm_make_scan_ioapic_request(kvm);
}
static void ioapic_write_indirect(struct kvm_ioapic *ioapic, u32 val)
{
unsigned index;
bool mask_before, mask_after;
union kvm_ioapic_redirect_entry *e;
switch (ioapic->ioregsel) {
case IOAPIC_REG_VERSION:
/* Writes are ignored. */
break;
case IOAPIC_REG_APIC_ID:
ioapic->id = (val >> 24) & 0xf;
break;
case IOAPIC_REG_ARB_ID:
break;
default:
index = (ioapic->ioregsel - 0x10) >> 1;
ioapic_debug("change redir index %x val %x\n", index, val);
if (index >= IOAPIC_NUM_PINS)
return;
e = &ioapic->redirtbl[index];
mask_before = e->fields.mask;
if (ioapic->ioregsel & 1) {
e->bits &= 0xffffffff;
e->bits |= (u64) val << 32;
} else {
e->bits &= ~0xffffffffULL;
e->bits |= (u32) val;
e->fields.remote_irr = 0;
}
mask_after = e->fields.mask;
if (mask_before != mask_after)
kvm_fire_mask_notifiers(ioapic->kvm, KVM_IRQCHIP_IOAPIC, index, mask_after);
if (e->fields.trig_mode == IOAPIC_LEVEL_TRIG
&& ioapic->irr & (1 << index))
ioapic_service(ioapic, index, false);
kvm_vcpu_request_scan_ioapic(ioapic->kvm);
break;
}
}
static int ioapic_service(struct kvm_ioapic *ioapic, int irq, bool line_status)
{
union kvm_ioapic_redirect_entry *entry = &ioapic->redirtbl[irq];
struct kvm_lapic_irq irqe;
int ret;
if (entry->fields.mask)
return -1;
ioapic_debug("dest=%x dest_mode=%x delivery_mode=%x "
"vector=%x trig_mode=%x\n",
entry->fields.dest_id, entry->fields.dest_mode,
entry->fields.delivery_mode, entry->fields.vector,
entry->fields.trig_mode);
irqe.dest_id = entry->fields.dest_id;
irqe.vector = entry->fields.vector;
irqe.dest_mode = entry->fields.dest_mode;
irqe.trig_mode = entry->fields.trig_mode;
irqe.delivery_mode = entry->fields.delivery_mode << 8;
irqe.level = 1;
irqe.shorthand = 0;
irqe.msi_redir_hint = false;
if (irqe.trig_mode == IOAPIC_EDGE_TRIG)
ioapic->irr_delivered |= 1 << irq;
if (irq == RTC_GSI && line_status) {
/*
* pending_eoi cannot ever become negative (see
* rtc_status_pending_eoi_check_valid) and the caller
* ensures that it is only called if it is >= zero, namely
* if rtc_irq_check_coalesced returns false).
*/
BUG_ON(ioapic->rtc_status.pending_eoi != 0);
ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe,
&ioapic->rtc_status.dest_map);
ioapic->rtc_status.pending_eoi = (ret < 0 ? 0 : ret);
} else
ret = kvm_irq_delivery_to_apic(ioapic->kvm, NULL, &irqe, NULL);
if (ret && irqe.trig_mode == IOAPIC_LEVEL_TRIG)
entry->fields.remote_irr = 1;
return ret;
}
int kvm_ioapic_set_irq(struct kvm_ioapic *ioapic, int irq, int irq_source_id,
int level, bool line_status)
{
int ret, irq_level;
BUG_ON(irq < 0 || irq >= IOAPIC_NUM_PINS);
spin_lock(&ioapic->lock);
irq_level = __kvm_irq_line_state(&ioapic->irq_states[irq],
irq_source_id, level);
ret = ioapic_set_irq(ioapic, irq, irq_level, line_status);
spin_unlock(&ioapic->lock);
return ret;
}
void kvm_ioapic_clear_all(struct kvm_ioapic *ioapic, int irq_source_id)
{
int i;
spin_lock(&ioapic->lock);
for (i = 0; i < KVM_IOAPIC_NUM_PINS; i++)
__clear_bit(irq_source_id, &ioapic->irq_states[i]);
spin_unlock(&ioapic->lock);
}
static void kvm_ioapic_eoi_inject_work(struct work_struct *work)
{
int i;
struct kvm_ioapic *ioapic = container_of(work, struct kvm_ioapic,
eoi_inject.work);
spin_lock(&ioapic->lock);
for (i = 0; i < IOAPIC_NUM_PINS; i++) {
union kvm_ioapic_redirect_entry *ent = &ioapic->redirtbl[i];
if (ent->fields.trig_mode != IOAPIC_LEVEL_TRIG)
continue;
if (ioapic->irr & (1 << i) && !ent->fields.remote_irr)
ioapic_service(ioapic, i, false);
}
spin_unlock(&ioapic->lock);
}
#define IOAPIC_SUCCESSIVE_IRQ_MAX_COUNT 10000
static void __kvm_ioapic_update_eoi(struct kvm_vcpu *vcpu,
struct kvm_ioapic *ioapic, int vector, int trigger_mode)
{
struct dest_map *dest_map = &ioapic->rtc_status.dest_map;
struct kvm_lapic *apic = vcpu->arch.apic;
int i;
/* RTC special handling */
if (test_bit(vcpu->vcpu_id, dest_map->map) &&
vector == dest_map->vectors[vcpu->vcpu_id])
rtc_irq_eoi(ioapic, vcpu);
for (i = 0; i < IOAPIC_NUM_PINS; i++) {
union kvm_ioapic_redirect_entry *ent = &ioapic->redirtbl[i];
if (ent->fields.vector != vector)
continue;
/*
* We are dropping lock while calling ack notifiers because ack
* notifier callbacks for assigned devices call into IOAPIC
* recursively. Since remote_irr is cleared only after call
* to notifiers if the same vector will be delivered while lock
* is dropped it will be put into irr and will be delivered
* after ack notifier returns.
*/
spin_unlock(&ioapic->lock);
kvm_notify_acked_irq(ioapic->kvm, KVM_IRQCHIP_IOAPIC, i);
spin_lock(&ioapic->lock);
if (trigger_mode != IOAPIC_LEVEL_TRIG ||
kvm_lapic_get_reg(apic, APIC_SPIV) & APIC_SPIV_DIRECTED_EOI)
continue;
ASSERT(ent->fields.trig_mode == IOAPIC_LEVEL_TRIG);
ent->fields.remote_irr = 0;
if (!ent->fields.mask && (ioapic->irr & (1 << i))) {
++ioapic->irq_eoi[i];
if (ioapic->irq_eoi[i] == IOAPIC_SUCCESSIVE_IRQ_MAX_COUNT) {
/*
* Real hardware does not deliver the interrupt
* immediately during eoi broadcast, and this
* lets a buggy guest make slow progress
* even if it does not correctly handle a
* level-triggered interrupt. Emulate this
* behavior if we detect an interrupt storm.
*/
schedule_delayed_work(&ioapic->eoi_inject, HZ / 100);
ioapic->irq_eoi[i] = 0;
trace_kvm_ioapic_delayed_eoi_inj(ent->bits);
} else {
ioapic_service(ioapic, i, false);
}
} else {
ioapic->irq_eoi[i] = 0;
}
}
}
void kvm_ioapic_update_eoi(struct kvm_vcpu *vcpu, int vector, int trigger_mode)
{
struct kvm_ioapic *ioapic = vcpu->kvm->arch.vioapic;
spin_lock(&ioapic->lock);
__kvm_ioapic_update_eoi(vcpu, ioapic, vector, trigger_mode);
spin_unlock(&ioapic->lock);
}
static inline struct kvm_ioapic *to_ioapic(struct kvm_io_device *dev)
{
return container_of(dev, struct kvm_ioapic, dev);
}
static inline int ioapic_in_range(struct kvm_ioapic *ioapic, gpa_t addr)
{
return ((addr >= ioapic->base_address &&
(addr < ioapic->base_address + IOAPIC_MEM_LENGTH)));
}
static int ioapic_mmio_read(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
gpa_t addr, int len, void *val)
{
struct kvm_ioapic *ioapic = to_ioapic(this);
u32 result;
if (!ioapic_in_range(ioapic, addr))
return -EOPNOTSUPP;
ioapic_debug("addr %lx\n", (unsigned long)addr);
ASSERT(!(addr & 0xf)); /* check alignment */
addr &= 0xff;
spin_lock(&ioapic->lock);
switch (addr) {
case IOAPIC_REG_SELECT:
result = ioapic->ioregsel;
break;
case IOAPIC_REG_WINDOW:
result = ioapic_read_indirect(ioapic, addr, len);
break;
default:
result = 0;
break;
}
spin_unlock(&ioapic->lock);
switch (len) {
case 8:
*(u64 *) val = result;
break;
case 1:
case 2:
case 4:
memcpy(val, (char *)&result, len);
break;
default:
printk(KERN_WARNING "ioapic: wrong length %d\n", len);
}
return 0;
}
static int ioapic_mmio_write(struct kvm_vcpu *vcpu, struct kvm_io_device *this,
gpa_t addr, int len, const void *val)
{
struct kvm_ioapic *ioapic = to_ioapic(this);
u32 data;
if (!ioapic_in_range(ioapic, addr))
return -EOPNOTSUPP;
ioapic_debug("ioapic_mmio_write addr=%p len=%d val=%p\n",
(void*)addr, len, val);
ASSERT(!(addr & 0xf)); /* check alignment */
switch (len) {
case 8:
case 4:
data = *(u32 *) val;
break;
case 2:
data = *(u16 *) val;
break;
case 1:
data = *(u8 *) val;
break;
default:
printk(KERN_WARNING "ioapic: Unsupported size %d\n", len);
return 0;
}
addr &= 0xff;
spin_lock(&ioapic->lock);
switch (addr) {
case IOAPIC_REG_SELECT:
ioapic->ioregsel = data & 0xFF; /* 8-bit register */
break;
case IOAPIC_REG_WINDOW:
ioapic_write_indirect(ioapic, data);
break;
default:
break;
}
spin_unlock(&ioapic->lock);
return 0;
}
static void kvm_ioapic_reset(struct kvm_ioapic *ioapic)
{
int i;
cancel_delayed_work_sync(&ioapic->eoi_inject);
for (i = 0; i < IOAPIC_NUM_PINS; i++)
ioapic->redirtbl[i].fields.mask = 1;
ioapic->base_address = IOAPIC_DEFAULT_BASE_ADDRESS;
ioapic->ioregsel = 0;
ioapic->irr = 0;
ioapic->irr_delivered = 0;
ioapic->id = 0;
memset(ioapic->irq_eoi, 0x00, sizeof(ioapic->irq_eoi));
rtc_irq_eoi_tracking_reset(ioapic);
}
static const struct kvm_io_device_ops ioapic_mmio_ops = {
.read = ioapic_mmio_read,
.write = ioapic_mmio_write,
};
int kvm_ioapic_init(struct kvm *kvm)
{
struct kvm_ioapic *ioapic;
int ret;
ioapic = kzalloc(sizeof(struct kvm_ioapic), GFP_KERNEL);
if (!ioapic)
return -ENOMEM;
spin_lock_init(&ioapic->lock);
INIT_DELAYED_WORK(&ioapic->eoi_inject, kvm_ioapic_eoi_inject_work);
kvm->arch.vioapic = ioapic;
kvm_ioapic_reset(ioapic);
kvm_iodevice_init(&ioapic->dev, &ioapic_mmio_ops);
ioapic->kvm = kvm;
mutex_lock(&kvm->slots_lock);
ret = kvm_io_bus_register_dev(kvm, KVM_MMIO_BUS, ioapic->base_address,
IOAPIC_MEM_LENGTH, &ioapic->dev);
mutex_unlock(&kvm->slots_lock);
if (ret < 0) {
kvm->arch.vioapic = NULL;
kfree(ioapic);
return ret;
}
kvm_vcpu_request_scan_ioapic(kvm);
return ret;
}
void kvm_ioapic_destroy(struct kvm *kvm)
{
struct kvm_ioapic *ioapic = kvm->arch.vioapic;
cancel_delayed_work_sync(&ioapic->eoi_inject);
kvm_io_bus_unregister_dev(kvm, KVM_MMIO_BUS, &ioapic->dev);
kvm->arch.vioapic = NULL;
kfree(ioapic);
}
int kvm_get_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state)
{
struct kvm_ioapic *ioapic = ioapic_irqchip(kvm);
if (!ioapic)
return -EINVAL;
spin_lock(&ioapic->lock);
memcpy(state, ioapic, sizeof(struct kvm_ioapic_state));
state->irr &= ~ioapic->irr_delivered;
spin_unlock(&ioapic->lock);
return 0;
}
int kvm_set_ioapic(struct kvm *kvm, struct kvm_ioapic_state *state)
{
struct kvm_ioapic *ioapic = ioapic_irqchip(kvm);
if (!ioapic)
return -EINVAL;
spin_lock(&ioapic->lock);
memcpy(ioapic, state, sizeof(struct kvm_ioapic_state));
ioapic->irr = 0;
ioapic->irr_delivered = 0;
kvm_vcpu_request_scan_ioapic(kvm);
kvm_ioapic_inject_all(ioapic, state->irr);
spin_unlock(&ioapic->lock);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5501_0 |
crossvul-cpp_data_good_2661_0 | /* $NetBSD: print-telnet.c,v 1.2 1999/10/11 12:40:12 sjg Exp $ */
/*-
* Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Simon J. Gerraty.
*
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 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.
*/
/*
* @(#)Copyright (c) 1994, Simon J. Gerraty.
*
* This is free software. It comes with NO WARRANTY.
* Permission to use, modify and distribute this source code
* is granted subject to the following conditions.
* 1/ that the above copyright notice and this notice
* are preserved in all copies.
*/
/* \summary: Telnet option printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include "netdissect.h"
static const char tstr[] = " [|telnet]";
#define TELCMDS
#define TELOPTS
/* NetBSD: telnet.h,v 1.9 2001/06/11 01:50:50 wiz Exp */
/*
* Definitions for the TELNET protocol.
*/
#define IAC 255 /* interpret as command: */
#define DONT 254 /* you are not to use option */
#define DO 253 /* please, you use option */
#define WONT 252 /* I won't use option */
#define WILL 251 /* I will use option */
#define SB 250 /* interpret as subnegotiation */
#define GA 249 /* you may reverse the line */
#define EL 248 /* erase the current line */
#define EC 247 /* erase the current character */
#define AYT 246 /* are you there */
#define AO 245 /* abort output--but let prog finish */
#define IP 244 /* interrupt process--permanently */
#define BREAK 243 /* break */
#define DM 242 /* data mark--for connect. cleaning */
#define NOP 241 /* nop */
#define SE 240 /* end sub negotiation */
#define EOR 239 /* end of record (transparent mode) */
#define ABORT 238 /* Abort process */
#define SUSP 237 /* Suspend process */
#define xEOF 236 /* End of file: EOF is already used... */
#define SYNCH 242 /* for telfunc calls */
#ifdef TELCMDS
static const char *telcmds[] = {
"EOF", "SUSP", "ABORT", "EOR",
"SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", "EC",
"EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0,
};
#else
extern char *telcmds[];
#endif
#define TELCMD_FIRST xEOF
#define TELCMD_LAST IAC
#define TELCMD_OK(x) ((unsigned int)(x) <= TELCMD_LAST && \
(unsigned int)(x) >= TELCMD_FIRST)
#define TELCMD(x) telcmds[(x)-TELCMD_FIRST]
/* telnet options */
#define TELOPT_BINARY 0 /* 8-bit data path */
#define TELOPT_ECHO 1 /* echo */
#define TELOPT_RCP 2 /* prepare to reconnect */
#define TELOPT_SGA 3 /* suppress go ahead */
#define TELOPT_NAMS 4 /* approximate message size */
#define TELOPT_STATUS 5 /* give status */
#define TELOPT_TM 6 /* timing mark */
#define TELOPT_RCTE 7 /* remote controlled transmission and echo */
#define TELOPT_NAOL 8 /* negotiate about output line width */
#define TELOPT_NAOP 9 /* negotiate about output page size */
#define TELOPT_NAOCRD 10 /* negotiate about CR disposition */
#define TELOPT_NAOHTS 11 /* negotiate about horizontal tabstops */
#define TELOPT_NAOHTD 12 /* negotiate about horizontal tab disposition */
#define TELOPT_NAOFFD 13 /* negotiate about formfeed disposition */
#define TELOPT_NAOVTS 14 /* negotiate about vertical tab stops */
#define TELOPT_NAOVTD 15 /* negotiate about vertical tab disposition */
#define TELOPT_NAOLFD 16 /* negotiate about output LF disposition */
#define TELOPT_XASCII 17 /* extended ascic character set */
#define TELOPT_LOGOUT 18 /* force logout */
#define TELOPT_BM 19 /* byte macro */
#define TELOPT_DET 20 /* data entry terminal */
#define TELOPT_SUPDUP 21 /* supdup protocol */
#define TELOPT_SUPDUPOUTPUT 22 /* supdup output */
#define TELOPT_SNDLOC 23 /* send location */
#define TELOPT_TTYPE 24 /* terminal type */
#define TELOPT_EOR 25 /* end or record */
#define TELOPT_TUID 26 /* TACACS user identification */
#define TELOPT_OUTMRK 27 /* output marking */
#define TELOPT_TTYLOC 28 /* terminal location number */
#define TELOPT_3270REGIME 29 /* 3270 regime */
#define TELOPT_X3PAD 30 /* X.3 PAD */
#define TELOPT_NAWS 31 /* window size */
#define TELOPT_TSPEED 32 /* terminal speed */
#define TELOPT_LFLOW 33 /* remote flow control */
#define TELOPT_LINEMODE 34 /* Linemode option */
#define TELOPT_XDISPLOC 35 /* X Display Location */
#define TELOPT_OLD_ENVIRON 36 /* Old - Environment variables */
#define TELOPT_AUTHENTICATION 37/* Authenticate */
#define TELOPT_ENCRYPT 38 /* Encryption option */
#define TELOPT_NEW_ENVIRON 39 /* New - Environment variables */
#define TELOPT_EXOPL 255 /* extended-options-list */
#define NTELOPTS (1+TELOPT_NEW_ENVIRON)
#ifdef TELOPTS
static const char *telopts[NTELOPTS+1] = {
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME",
"STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP",
"NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS",
"NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
"DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT",
"SEND LOCATION", "TERMINAL TYPE", "END OF RECORD",
"TACACS UID", "OUTPUT MARKING", "TTYLOC",
"3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW",
"LINEMODE", "XDISPLOC", "OLD-ENVIRON", "AUTHENTICATION",
"ENCRYPT", "NEW-ENVIRON",
0,
};
#define TELOPT_FIRST TELOPT_BINARY
#define TELOPT_LAST TELOPT_NEW_ENVIRON
#define TELOPT_OK(x) ((unsigned int)(x) <= TELOPT_LAST)
#define TELOPT(x) telopts[(x)-TELOPT_FIRST]
#endif
/* sub-option qualifiers */
#define TELQUAL_IS 0 /* option is... */
#define TELQUAL_SEND 1 /* send option */
#define TELQUAL_INFO 2 /* ENVIRON: informational version of IS */
#define TELQUAL_REPLY 2 /* AUTHENTICATION: client version of IS */
#define TELQUAL_NAME 3 /* AUTHENTICATION: client version of IS */
#define LFLOW_OFF 0 /* Disable remote flow control */
#define LFLOW_ON 1 /* Enable remote flow control */
#define LFLOW_RESTART_ANY 2 /* Restart output on any char */
#define LFLOW_RESTART_XON 3 /* Restart output only on XON */
/*
* LINEMODE suboptions
*/
#define LM_MODE 1
#define LM_FORWARDMASK 2
#define LM_SLC 3
#define MODE_EDIT 0x01
#define MODE_TRAPSIG 0x02
#define MODE_ACK 0x04
#define MODE_SOFT_TAB 0x08
#define MODE_LIT_ECHO 0x10
#define MODE_MASK 0x1f
#define SLC_SYNCH 1
#define SLC_BRK 2
#define SLC_IP 3
#define SLC_AO 4
#define SLC_AYT 5
#define SLC_EOR 6
#define SLC_ABORT 7
#define SLC_EOF 8
#define SLC_SUSP 9
#define SLC_EC 10
#define SLC_EL 11
#define SLC_EW 12
#define SLC_RP 13
#define SLC_LNEXT 14
#define SLC_XON 15
#define SLC_XOFF 16
#define SLC_FORW1 17
#define SLC_FORW2 18
#define SLC_MCL 19
#define SLC_MCR 20
#define SLC_MCWL 21
#define SLC_MCWR 22
#define SLC_MCBOL 23
#define SLC_MCEOL 24
#define SLC_INSRT 25
#define SLC_OVER 26
#define SLC_ECR 27
#define SLC_EWR 28
#define SLC_EBOL 29
#define SLC_EEOL 30
#define NSLC 30
/*
* For backwards compatibility, we define SLC_NAMES to be the
* list of names if SLC_NAMES is not defined.
*/
#define SLC_NAMELIST "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR", \
"ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \
"LNEXT", "XON", "XOFF", "FORW1", "FORW2", \
"MCL", "MCR", "MCWL", "MCWR", "MCBOL", \
"MCEOL", "INSRT", "OVER", "ECR", "EWR", \
"EBOL", "EEOL", \
0,
#ifdef SLC_NAMES
const char *slc_names[] = {
SLC_NAMELIST
};
#else
extern char *slc_names[];
#define SLC_NAMES SLC_NAMELIST
#endif
#define SLC_NAME_OK(x) ((unsigned int)(x) <= NSLC)
#define SLC_NAME(x) slc_names[x]
#define SLC_NOSUPPORT 0
#define SLC_CANTCHANGE 1
#define SLC_VARIABLE 2
#define SLC_DEFAULT 3
#define SLC_LEVELBITS 0x03
#define SLC_FUNC 0
#define SLC_FLAGS 1
#define SLC_VALUE 2
#define SLC_ACK 0x80
#define SLC_FLUSHIN 0x40
#define SLC_FLUSHOUT 0x20
#define OLD_ENV_VAR 1
#define OLD_ENV_VALUE 0
#define NEW_ENV_VAR 0
#define NEW_ENV_VALUE 1
#define ENV_ESC 2
#define ENV_USERVAR 3
/*
* AUTHENTICATION suboptions
*/
/*
* Who is authenticating who ...
*/
#define AUTH_WHO_CLIENT 0 /* Client authenticating server */
#define AUTH_WHO_SERVER 1 /* Server authenticating client */
#define AUTH_WHO_MASK 1
#define AUTHTYPE_NULL 0
#define AUTHTYPE_KERBEROS_V4 1
#define AUTHTYPE_KERBEROS_V5 2
#define AUTHTYPE_SPX 3
#define AUTHTYPE_MINK 4
#define AUTHTYPE_CNT 5
#define AUTHTYPE_TEST 99
#ifdef AUTH_NAMES
const char *authtype_names[] = {
"NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", 0,
};
#else
extern char *authtype_names[];
#endif
#define AUTHTYPE_NAME_OK(x) ((unsigned int)(x) < AUTHTYPE_CNT)
#define AUTHTYPE_NAME(x) authtype_names[x]
/*
* ENCRYPTion suboptions
*/
#define ENCRYPT_IS 0 /* I pick encryption type ... */
#define ENCRYPT_SUPPORT 1 /* I support encryption types ... */
#define ENCRYPT_REPLY 2 /* Initial setup response */
#define ENCRYPT_START 3 /* Am starting to send encrypted */
#define ENCRYPT_END 4 /* Am ending encrypted */
#define ENCRYPT_REQSTART 5 /* Request you start encrypting */
#define ENCRYPT_REQEND 6 /* Request you send encrypting */
#define ENCRYPT_ENC_KEYID 7
#define ENCRYPT_DEC_KEYID 8
#define ENCRYPT_CNT 9
#define ENCTYPE_ANY 0
#define ENCTYPE_DES_CFB64 1
#define ENCTYPE_DES_OFB64 2
#define ENCTYPE_CNT 3
#ifdef ENCRYPT_NAMES
const char *encrypt_names[] = {
"IS", "SUPPORT", "REPLY", "START", "END",
"REQUEST-START", "REQUEST-END", "ENC-KEYID", "DEC-KEYID",
0,
};
const char *enctype_names[] = {
"ANY", "DES_CFB64", "DES_OFB64", 0,
};
#else
extern char *encrypt_names[];
extern char *enctype_names[];
#endif
#define ENCRYPT_NAME_OK(x) ((unsigned int)(x) < ENCRYPT_CNT)
#define ENCRYPT_NAME(x) encrypt_names[x]
#define ENCTYPE_NAME_OK(x) ((unsigned int)(x) < ENCTYPE_CNT)
#define ENCTYPE_NAME(x) enctype_names[x]
/* normal */
static const char *cmds[] = {
"IS", "SEND", "INFO",
};
/* 37: Authentication */
static const char *authcmd[] = {
"IS", "SEND", "REPLY", "NAME",
};
static const char *authtype[] = {
"NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK",
"SRP", "RSA", "SSL", NULL, NULL,
"LOKI", "SSA", "KEA_SJ", "KEA_SJ_INTEG", "DSS",
"NTLM",
};
/* 38: Encryption */
static const char *enccmd[] = {
"IS", "SUPPORT", "REPLY", "START", "END",
"REQUEST-START", "REQUEST-END", "END_KEYID", "DEC_KEYID",
};
static const char *enctype[] = {
"NULL", "DES_CFB64", "DES_OFB64", "DES3_CFB64", "DES3_OFB64",
NULL, "CAST5_40_CFB64", "CAST5_40_OFB64", "CAST128_CFB64", "CAST128_OFB64",
};
#define STR_OR_ID(x, tab) \
(((x) < sizeof(tab)/sizeof(tab[0]) && tab[(x)]) ? tab[(x)] : numstr(x))
static char *
numstr(int x)
{
static char buf[20];
snprintf(buf, sizeof(buf), "%#x", x);
return buf;
}
/* sp points to IAC byte */
static int
telnet_parse(netdissect_options *ndo, const u_char *sp, u_int length, int print)
{
int i, x;
u_int c;
const u_char *osp, *p;
#define FETCH(c, sp, length) \
do { \
if (length < 1) \
goto pktend; \
ND_TCHECK(*sp); \
c = *sp++; \
length--; \
} while (0)
osp = sp;
FETCH(c, sp, length);
if (c != IAC)
goto pktend;
FETCH(c, sp, length);
if (c == IAC) { /* <IAC><IAC>! */
if (print)
ND_PRINT((ndo, "IAC IAC"));
goto done;
}
i = c - TELCMD_FIRST;
if (i < 0 || i > IAC - TELCMD_FIRST)
goto pktend;
switch (c) {
case DONT:
case DO:
case WONT:
case WILL:
case SB:
/* DONT/DO/WONT/WILL x */
FETCH(x, sp, length);
if (x >= 0 && x < NTELOPTS) {
if (print)
ND_PRINT((ndo, "%s %s", telcmds[i], telopts[x]));
} else {
if (print)
ND_PRINT((ndo, "%s %#x", telcmds[i], x));
}
if (c != SB)
break;
/* IAC SB .... IAC SE */
p = sp;
while (length > (u_int)(p + 1 - sp)) {
ND_TCHECK2(*p, 2);
if (p[0] == IAC && p[1] == SE)
break;
p++;
}
ND_TCHECK(*p);
if (*p != IAC)
goto pktend;
switch (x) {
case TELOPT_AUTHENTICATION:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authcmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, authtype)));
break;
case TELOPT_ENCRYPT:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enccmd)));
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, enctype)));
break;
default:
if (p <= sp)
break;
FETCH(c, sp, length);
if (print)
ND_PRINT((ndo, " %s", STR_OR_ID(c, cmds)));
break;
}
while (p > sp) {
FETCH(x, sp, length);
if (print)
ND_PRINT((ndo, " %#x", x));
}
/* terminating IAC SE */
if (print)
ND_PRINT((ndo, " SE"));
sp += 2;
break;
default:
if (print)
ND_PRINT((ndo, "%s", telcmds[i]));
goto done;
}
done:
return sp - osp;
trunc:
ND_PRINT((ndo, "%s", tstr));
pktend:
return -1;
#undef FETCH
}
void
telnet_print(netdissect_options *ndo, const u_char *sp, u_int length)
{
int first = 1;
const u_char *osp;
int l;
osp = sp;
ND_TCHECK(*sp);
while (length > 0 && *sp == IAC) {
/*
* Parse the Telnet command without printing it,
* to determine its length.
*/
l = telnet_parse(ndo, sp, length, 0);
if (l < 0)
break;
/*
* now print it
*/
if (ndo->ndo_Xflag && 2 < ndo->ndo_vflag) {
if (first)
ND_PRINT((ndo, "\nTelnet:"));
hex_print_with_offset(ndo, "\n", sp, l, sp - osp);
if (l > 8)
ND_PRINT((ndo, "\n\t\t\t\t"));
else
ND_PRINT((ndo, "%*s\t", (8 - l) * 3, ""));
} else
ND_PRINT((ndo, "%s", (first) ? " [telnet " : ", "));
(void)telnet_parse(ndo, sp, length, 1);
first = 0;
sp += l;
length -= l;
ND_TCHECK(*sp);
}
if (!first) {
if (ndo->ndo_Xflag && 2 < ndo->ndo_vflag)
ND_PRINT((ndo, "\n"));
else
ND_PRINT((ndo, "]"));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2661_0 |
crossvul-cpp_data_bad_157_2 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* Graphics Backend for drawing to ArrayBuffer
* ----------------------------------------------------------------------------
*/
#include "jswrap_arraybuffer.h"
#include "lcd_arraybuffer.h"
#include "jsvar.h"
#include "jsvariterator.h"
// returns the BIT index, so the bottom 3 bits specify the bit in the byte
unsigned int lcdGetPixelIndex_ArrayBuffer(JsGraphics *gfx, int x, int y, int pixelCount) {
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG) {
if (y&1) x = gfx->data.width - (x+pixelCount);
}
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)
return (unsigned int)(((x + (y>>3)*gfx->data.width)<<3) | (y&7));
else
return (unsigned int)((x + y*gfx->data.width)*gfx->data.bpp);
}
unsigned int lcdGetPixel_ArrayBuffer(JsGraphics *gfx, short x, short y) {
unsigned int col = 0;
JsVar *buf = (JsVar*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,1);
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, buf, idx>>3 );
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it);
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
col = ((existing>>bitIdx)&mask);
} else {
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
col |= ((unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it)) << i;
jsvArrayBufferIteratorNext(&it);
}
}
jsvArrayBufferIteratorFree(&it);
return col;
}
// set pixelCount pixels starting at x,y
void lcdSetPixels_ArrayBuffer(JsGraphics *gfx, short x, short y, short pixelCount, unsigned int col) {
JsVar *buf = (JsVar*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,pixelCount);
JsvArrayBufferIterator it;
jsvArrayBufferIteratorNew(&it, buf, idx>>3 );
unsigned int whiteMask = (1U<<gfx->data.bpp)-1;
bool shortCut = (col==0 || (col&whiteMask)==whiteMask) && (!(gfx->data.flags&JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)); // simple black or white fill
while (pixelCount--) { // writing individual bits
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
if (shortCut && idx==0) {
// Basically, if we're aligned and we're filling all 0 or all 1
// then we can go really quickly and can just fill
int wholeBytes = (gfx->data.bpp*(pixelCount+1)) >> 3;
if (wholeBytes) {
char c = (char)(col?0xFF:0);
pixelCount = (short)(pixelCount+1 - (wholeBytes*8/gfx->data.bpp));
while (wholeBytes--) {
jsvArrayBufferIteratorSetByteValue(&it, c);
jsvArrayBufferIteratorNext(&it);
}
continue;
}
}
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)jsvArrayBufferIteratorGetIntegerValue(&it);
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
jsvArrayBufferIteratorSetByteValue(&it, (char)((existing&~(mask<<bitIdx)) | ((col&mask)<<bitIdx)));
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE) {
jsvArrayBufferIteratorNext(&it);
} else {
idx += gfx->data.bpp;
if (idx>=8) jsvArrayBufferIteratorNext(&it);
}
} else { // we're writing whole bytes
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
jsvArrayBufferIteratorSetByteValue(&it, (char)(col >> i));
jsvArrayBufferIteratorNext(&it);
}
}
}
jsvArrayBufferIteratorFree(&it);
}
void lcdSetPixel_ArrayBuffer(JsGraphics *gfx, short x, short y, unsigned int col) {
lcdSetPixels_ArrayBuffer(gfx, x, y, 1, col);
}
void lcdFillRect_ArrayBuffer(struct JsGraphics *gfx, short x1, short y1, short x2, short y2) {
short y;
for (y=y1;y<=y2;y++)
lcdSetPixels_ArrayBuffer(gfx, x1, y, (short)(1+x2-x1), gfx->data.fgColor);
}
#ifndef SAVE_ON_FLASH
// Faster implementation for where we have a flat memory area
unsigned int lcdGetPixel_ArrayBuffer_flat(JsGraphics *gfx, short x, short y) {
unsigned int col = 0;
unsigned char *ptr = (unsigned char*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,1);
ptr += idx>>3;
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)*ptr;
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
col = ((existing>>bitIdx)&mask);
} else {
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
col |= ((unsigned int)*ptr) << i;
ptr++;
}
}
return col;
}
// set pixelCount pixels starting at x,y
// Faster implementation for where we have a flat memory area
void lcdSetPixels_ArrayBuffer_flat(JsGraphics *gfx, short x, short y, short pixelCount, unsigned int col) {
unsigned char *ptr = (unsigned char*)gfx->backendData;
unsigned int idx = lcdGetPixelIndex_ArrayBuffer(gfx,x,y,pixelCount);
ptr += idx>>3;
unsigned int whiteMask = (1U<<gfx->data.bpp)-1;
bool shortCut = (col==0 || (col&whiteMask)==whiteMask) && (!(gfx->data.flags&JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE)); // simple black or white fill
while (pixelCount--) { // writing individual bits
if (gfx->data.bpp&7/*not a multiple of one byte*/) {
idx = idx & 7;
if (shortCut && idx==0) {
// Basically, if we're aligned and we're filling all 0 or all 1
// then we can go really quickly and can just fill
int wholeBytes = (gfx->data.bpp*(pixelCount+1)) >> 3;
if (wholeBytes) {
char c = (char)(col?0xFF:0);
pixelCount = (short)(pixelCount+1 - (wholeBytes*8/gfx->data.bpp));
while (wholeBytes--) {
*ptr = c;
ptr++;
}
continue;
}
}
unsigned int mask = (unsigned int)(1<<gfx->data.bpp)-1;
unsigned int existing = (unsigned int)*ptr;
unsigned int bitIdx = (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_MSB) ? 8-(idx+gfx->data.bpp) : idx;
*ptr = (char)((existing&~(mask<<bitIdx)) | ((col&mask)<<bitIdx));
if (gfx->data.flags & JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE) {
ptr++;
} else {
idx += gfx->data.bpp;
if (idx>=8) ptr++;
}
} else { // we're writing whole bytes
int i;
for (i=0;i<gfx->data.bpp;i+=8) {
*ptr = (char)(col >> i);
ptr++;
}
}
}
}
// Faster implementation for where we have a flat memory area
void lcdSetPixel_ArrayBuffer_flat(JsGraphics *gfx, short x, short y, unsigned int col) {
lcdSetPixels_ArrayBuffer_flat(gfx, x, y, 1, col);
}
// Faster implementation for where we have a flat memory area
void lcdFillRect_ArrayBuffer_flat(struct JsGraphics *gfx, short x1, short y1, short x2, short y2) {
short y;
for (y=y1;y<=y2;y++)
lcdSetPixels_ArrayBuffer_flat(gfx, x1, y, (short)(1+x2-x1), gfx->data.fgColor);
}
#endif // SAVE_ON_FLASH
void lcdInit_ArrayBuffer(JsGraphics *gfx) {
// create buffer
JsVar *buf = jswrap_arraybuffer_constructor(graphicsGetMemoryRequired(gfx));
jsvUnLock2(jsvAddNamedChild(gfx->graphicsVar, buf, "buffer"), buf);
}
void lcdSetCallbacks_ArrayBuffer(JsGraphics *gfx) {
JsVar *buf = jsvObjectGetChild(gfx->graphicsVar, "buffer", 0);
#ifndef SAVE_ON_FLASH
size_t len = 0;
char *dataPtr = jsvGetDataPointer(buf, &len);
#endif
jsvUnLock(buf);
#ifndef SAVE_ON_FLASH
if (dataPtr && len>=graphicsGetMemoryRequired(gfx)) {
// nice fast mode
gfx->backendData = dataPtr;
gfx->setPixel = lcdSetPixel_ArrayBuffer_flat;
gfx->getPixel = lcdGetPixel_ArrayBuffer_flat;
gfx->fillRect = lcdFillRect_ArrayBuffer_flat;
#else
if (false) {
#endif
} else if (jsvIsArrayBuffer(buf)) {
/* NOTE: This is nasty as 'buf' is not locked. HOWEVER we know that
gfx->graphicsVar IS locked, so 'buf' isn't going anywhere */
gfx->backendData = buf;
gfx->setPixel = lcdSetPixel_ArrayBuffer;
gfx->getPixel = lcdGetPixel_ArrayBuffer;
gfx->fillRect = lcdFillRect_ArrayBuffer;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_157_2 |
crossvul-cpp_data_bad_2677_0 | /*
* Copyright (c) 2003 Bruce M. Simpson <bms@spc.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:
* 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Bruce M. Simpson.
* 4. Neither the name of Bruce M. Simpson nor the names of co-
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Bruce M. Simpson 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 Bruce M. Simpson 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.
*/
/* \summary: Ad hoc On-Demand Distance Vector (AODV) Routing printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
struct aodv_rreq {
uint8_t rreq_type; /* AODV message type (1) */
uint8_t rreq_flags; /* various flags */
uint8_t rreq_zero0; /* reserved, set to zero */
uint8_t rreq_hops; /* number of hops from originator */
uint32_t rreq_id; /* request ID */
uint32_t rreq_da; /* destination IPv4 address */
uint32_t rreq_ds; /* destination sequence number */
uint32_t rreq_oa; /* originator IPv4 address */
uint32_t rreq_os; /* originator sequence number */
};
struct aodv_rreq6 {
uint8_t rreq_type; /* AODV message type (1) */
uint8_t rreq_flags; /* various flags */
uint8_t rreq_zero0; /* reserved, set to zero */
uint8_t rreq_hops; /* number of hops from originator */
uint32_t rreq_id; /* request ID */
struct in6_addr rreq_da; /* destination IPv6 address */
uint32_t rreq_ds; /* destination sequence number */
struct in6_addr rreq_oa; /* originator IPv6 address */
uint32_t rreq_os; /* originator sequence number */
};
struct aodv_rreq6_draft_01 {
uint8_t rreq_type; /* AODV message type (16) */
uint8_t rreq_flags; /* various flags */
uint8_t rreq_zero0; /* reserved, set to zero */
uint8_t rreq_hops; /* number of hops from originator */
uint32_t rreq_id; /* request ID */
uint32_t rreq_ds; /* destination sequence number */
uint32_t rreq_os; /* originator sequence number */
struct in6_addr rreq_da; /* destination IPv6 address */
struct in6_addr rreq_oa; /* originator IPv6 address */
};
#define RREQ_JOIN 0x80 /* join (reserved for multicast */
#define RREQ_REPAIR 0x40 /* repair (reserved for multicast */
#define RREQ_GRAT 0x20 /* gratuitous RREP */
#define RREQ_DEST 0x10 /* destination only */
#define RREQ_UNKNOWN 0x08 /* unknown destination sequence num */
#define RREQ_FLAGS_MASK 0xF8 /* mask for rreq_flags */
struct aodv_rrep {
uint8_t rrep_type; /* AODV message type (2) */
uint8_t rrep_flags; /* various flags */
uint8_t rrep_ps; /* prefix size */
uint8_t rrep_hops; /* number of hops from o to d */
uint32_t rrep_da; /* destination IPv4 address */
uint32_t rrep_ds; /* destination sequence number */
uint32_t rrep_oa; /* originator IPv4 address */
uint32_t rrep_life; /* lifetime of this route */
};
struct aodv_rrep6 {
uint8_t rrep_type; /* AODV message type (2) */
uint8_t rrep_flags; /* various flags */
uint8_t rrep_ps; /* prefix size */
uint8_t rrep_hops; /* number of hops from o to d */
struct in6_addr rrep_da; /* destination IPv6 address */
uint32_t rrep_ds; /* destination sequence number */
struct in6_addr rrep_oa; /* originator IPv6 address */
uint32_t rrep_life; /* lifetime of this route */
};
struct aodv_rrep6_draft_01 {
uint8_t rrep_type; /* AODV message type (17) */
uint8_t rrep_flags; /* various flags */
uint8_t rrep_ps; /* prefix size */
uint8_t rrep_hops; /* number of hops from o to d */
uint32_t rrep_ds; /* destination sequence number */
struct in6_addr rrep_da; /* destination IPv6 address */
struct in6_addr rrep_oa; /* originator IPv6 address */
uint32_t rrep_life; /* lifetime of this route */
};
#define RREP_REPAIR 0x80 /* repair (reserved for multicast */
#define RREP_ACK 0x40 /* acknowledgement required */
#define RREP_FLAGS_MASK 0xC0 /* mask for rrep_flags */
#define RREP_PREFIX_MASK 0x1F /* mask for prefix size */
struct rerr_unreach {
uint32_t u_da; /* IPv4 address */
uint32_t u_ds; /* sequence number */
};
struct rerr_unreach6 {
struct in6_addr u_da; /* IPv6 address */
uint32_t u_ds; /* sequence number */
};
struct rerr_unreach6_draft_01 {
struct in6_addr u_da; /* IPv6 address */
uint32_t u_ds; /* sequence number */
};
struct aodv_rerr {
uint8_t rerr_type; /* AODV message type (3 or 18) */
uint8_t rerr_flags; /* various flags */
uint8_t rerr_zero0; /* reserved, set to zero */
uint8_t rerr_dc; /* destination count */
};
#define RERR_NODELETE 0x80 /* don't delete the link */
#define RERR_FLAGS_MASK 0x80 /* mask for rerr_flags */
struct aodv_rrep_ack {
uint8_t ra_type;
uint8_t ra_zero0;
};
#define AODV_RREQ 1 /* route request */
#define AODV_RREP 2 /* route response */
#define AODV_RERR 3 /* error report */
#define AODV_RREP_ACK 4 /* route response acknowledgement */
#define AODV_V6_DRAFT_01_RREQ 16 /* IPv6 route request */
#define AODV_V6_DRAFT_01_RREP 17 /* IPv6 route response */
#define AODV_V6_DRAFT_01_RERR 18 /* IPv6 error report */
#define AODV_V6_DRAFT_01_RREP_ACK 19 /* IPV6 route response acknowledgment */
struct aodv_ext {
uint8_t type; /* extension type */
uint8_t length; /* extension length */
};
struct aodv_hello {
struct aodv_ext eh; /* extension header */
uint8_t interval[4]; /* expect my next hello in
* (n) ms
* NOTE: this is not aligned */
};
#define AODV_EXT_HELLO 1
static void
aodv_extension(netdissect_options *ndo,
const struct aodv_ext *ep, u_int length)
{
const struct aodv_hello *ah;
switch (ep->type) {
case AODV_EXT_HELLO:
ah = (const struct aodv_hello *)(const void *)ep;
ND_TCHECK(*ah);
if (length < sizeof(struct aodv_hello))
goto trunc;
ND_PRINT((ndo, "\n\text HELLO %ld ms",
(unsigned long)EXTRACT_32BITS(&ah->interval)));
break;
default:
ND_PRINT((ndo, "\n\text %u %u", ep->type, ep->length));
break;
}
return;
trunc:
ND_PRINT((ndo, " [|hello]"));
}
static void
aodv_rreq(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rreq *ap = (const struct aodv_rreq *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rreq %u %s%s%s%s%shops %u id 0x%08lx\n"
"\tdst %s seq %lu src %s seq %lu", length,
ap->rreq_type & RREQ_JOIN ? "[J]" : "",
ap->rreq_type & RREQ_REPAIR ? "[R]" : "",
ap->rreq_type & RREQ_GRAT ? "[G]" : "",
ap->rreq_type & RREQ_DEST ? "[D]" : "",
ap->rreq_type & RREQ_UNKNOWN ? "[U] " : " ",
ap->rreq_hops,
(unsigned long)EXTRACT_32BITS(&ap->rreq_id),
ipaddr_string(ndo, &ap->rreq_da),
(unsigned long)EXTRACT_32BITS(&ap->rreq_ds),
ipaddr_string(ndo, &ap->rreq_oa),
(unsigned long)EXTRACT_32BITS(&ap->rreq_os)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_rrep(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rrep *ap = (const struct aodv_rrep *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rrep %u %s%sprefix %u hops %u\n"
"\tdst %s dseq %lu src %s %lu ms", length,
ap->rrep_type & RREP_REPAIR ? "[R]" : "",
ap->rrep_type & RREP_ACK ? "[A] " : " ",
ap->rrep_ps & RREP_PREFIX_MASK,
ap->rrep_hops,
ipaddr_string(ndo, &ap->rrep_da),
(unsigned long)EXTRACT_32BITS(&ap->rrep_ds),
ipaddr_string(ndo, &ap->rrep_oa),
(unsigned long)EXTRACT_32BITS(&ap->rrep_life)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_rerr(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i, dc;
const struct aodv_rerr *ap = (const struct aodv_rerr *)dat;
const struct rerr_unreach *dp;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rerr %s [items %u] [%u]:",
ap->rerr_flags & RERR_NODELETE ? "[D]" : "",
ap->rerr_dc, length));
dp = (const struct rerr_unreach *)(dat + sizeof(*ap));
i = length - sizeof(*ap);
for (dc = ap->rerr_dc; dc != 0; dc--) {
ND_TCHECK(*dp);
if (i < sizeof(*dp))
goto trunc;
ND_PRINT((ndo, " {%s}(%ld)", ipaddr_string(ndo, &dp->u_da),
(unsigned long)EXTRACT_32BITS(&dp->u_ds)));
dp++;
i -= sizeof(*dp);
}
return;
trunc:
ND_PRINT((ndo, "[|rerr]"));
}
static void
aodv_v6_rreq(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rreq6 *ap = (const struct aodv_rreq6 *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " v6 rreq %u %s%s%s%s%shops %u id 0x%08lx\n"
"\tdst %s seq %lu src %s seq %lu", length,
ap->rreq_type & RREQ_JOIN ? "[J]" : "",
ap->rreq_type & RREQ_REPAIR ? "[R]" : "",
ap->rreq_type & RREQ_GRAT ? "[G]" : "",
ap->rreq_type & RREQ_DEST ? "[D]" : "",
ap->rreq_type & RREQ_UNKNOWN ? "[U] " : " ",
ap->rreq_hops,
(unsigned long)EXTRACT_32BITS(&ap->rreq_id),
ip6addr_string(ndo, &ap->rreq_da),
(unsigned long)EXTRACT_32BITS(&ap->rreq_ds),
ip6addr_string(ndo, &ap->rreq_oa),
(unsigned long)EXTRACT_32BITS(&ap->rreq_os)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_v6_rrep(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rrep6 *ap = (const struct aodv_rrep6 *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rrep %u %s%sprefix %u hops %u\n"
"\tdst %s dseq %lu src %s %lu ms", length,
ap->rrep_type & RREP_REPAIR ? "[R]" : "",
ap->rrep_type & RREP_ACK ? "[A] " : " ",
ap->rrep_ps & RREP_PREFIX_MASK,
ap->rrep_hops,
ip6addr_string(ndo, &ap->rrep_da),
(unsigned long)EXTRACT_32BITS(&ap->rrep_ds),
ip6addr_string(ndo, &ap->rrep_oa),
(unsigned long)EXTRACT_32BITS(&ap->rrep_life)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_v6_rerr(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i, dc;
const struct aodv_rerr *ap = (const struct aodv_rerr *)dat;
const struct rerr_unreach6 *dp6;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rerr %s [items %u] [%u]:",
ap->rerr_flags & RERR_NODELETE ? "[D]" : "",
ap->rerr_dc, length));
dp6 = (const struct rerr_unreach6 *)(const void *)(ap + 1);
i = length - sizeof(*ap);
for (dc = ap->rerr_dc; dc != 0; dc--) {
ND_TCHECK(*dp6);
if (i < sizeof(*dp6))
goto trunc;
ND_PRINT((ndo, " {%s}(%ld)", ip6addr_string(ndo, &dp6->u_da),
(unsigned long)EXTRACT_32BITS(&dp6->u_ds)));
dp6++;
i -= sizeof(*dp6);
}
return;
trunc:
ND_PRINT((ndo, "[|rerr]"));
}
static void
aodv_v6_draft_01_rreq(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rreq6_draft_01 *ap = (const struct aodv_rreq6_draft_01 *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rreq %u %s%s%s%s%shops %u id 0x%08lx\n"
"\tdst %s seq %lu src %s seq %lu", length,
ap->rreq_type & RREQ_JOIN ? "[J]" : "",
ap->rreq_type & RREQ_REPAIR ? "[R]" : "",
ap->rreq_type & RREQ_GRAT ? "[G]" : "",
ap->rreq_type & RREQ_DEST ? "[D]" : "",
ap->rreq_type & RREQ_UNKNOWN ? "[U] " : " ",
ap->rreq_hops,
(unsigned long)EXTRACT_32BITS(&ap->rreq_id),
ip6addr_string(ndo, &ap->rreq_da),
(unsigned long)EXTRACT_32BITS(&ap->rreq_ds),
ip6addr_string(ndo, &ap->rreq_oa),
(unsigned long)EXTRACT_32BITS(&ap->rreq_os)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_v6_draft_01_rrep(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i;
const struct aodv_rrep6_draft_01 *ap = (const struct aodv_rrep6_draft_01 *)dat;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rrep %u %s%sprefix %u hops %u\n"
"\tdst %s dseq %lu src %s %lu ms", length,
ap->rrep_type & RREP_REPAIR ? "[R]" : "",
ap->rrep_type & RREP_ACK ? "[A] " : " ",
ap->rrep_ps & RREP_PREFIX_MASK,
ap->rrep_hops,
ip6addr_string(ndo, &ap->rrep_da),
(unsigned long)EXTRACT_32BITS(&ap->rrep_ds),
ip6addr_string(ndo, &ap->rrep_oa),
(unsigned long)EXTRACT_32BITS(&ap->rrep_life)));
i = length - sizeof(*ap);
if (i >= sizeof(struct aodv_ext))
aodv_extension(ndo, (const struct aodv_ext *)(dat + sizeof(*ap)), i);
return;
trunc:
ND_PRINT((ndo, " [|rreq"));
}
static void
aodv_v6_draft_01_rerr(netdissect_options *ndo, const u_char *dat, u_int length)
{
u_int i, dc;
const struct aodv_rerr *ap = (const struct aodv_rerr *)dat;
const struct rerr_unreach6_draft_01 *dp6;
ND_TCHECK(*ap);
if (length < sizeof(*ap))
goto trunc;
ND_PRINT((ndo, " rerr %s [items %u] [%u]:",
ap->rerr_flags & RERR_NODELETE ? "[D]" : "",
ap->rerr_dc, length));
dp6 = (const struct rerr_unreach6_draft_01 *)(const void *)(ap + 1);
i = length - sizeof(*ap);
for (dc = ap->rerr_dc; dc != 0; dc--) {
ND_TCHECK(*dp6);
if (i < sizeof(*dp6))
goto trunc;
ND_PRINT((ndo, " {%s}(%ld)", ip6addr_string(ndo, &dp6->u_da),
(unsigned long)EXTRACT_32BITS(&dp6->u_ds)));
dp6++;
i -= sizeof(*dp6);
}
return;
trunc:
ND_PRINT((ndo, "[|rerr]"));
}
void
aodv_print(netdissect_options *ndo,
const u_char *dat, u_int length, int is_ip6)
{
uint8_t msg_type;
/*
* The message type is the first byte; make sure we have it
* and then fetch it.
*/
ND_TCHECK(*dat);
msg_type = *dat;
ND_PRINT((ndo, " aodv"));
switch (msg_type) {
case AODV_RREQ:
if (is_ip6)
aodv_v6_rreq(ndo, dat, length);
else
aodv_rreq(ndo, dat, length);
break;
case AODV_RREP:
if (is_ip6)
aodv_v6_rrep(ndo, dat, length);
else
aodv_rrep(ndo, dat, length);
break;
case AODV_RERR:
if (is_ip6)
aodv_v6_rerr(ndo, dat, length);
else
aodv_rerr(ndo, dat, length);
break;
case AODV_RREP_ACK:
ND_PRINT((ndo, " rrep-ack %u", length));
break;
case AODV_V6_DRAFT_01_RREQ:
aodv_v6_draft_01_rreq(ndo, dat, length);
break;
case AODV_V6_DRAFT_01_RREP:
aodv_v6_draft_01_rrep(ndo, dat, length);
break;
case AODV_V6_DRAFT_01_RERR:
aodv_v6_draft_01_rerr(ndo, dat, length);
break;
case AODV_V6_DRAFT_01_RREP_ACK:
ND_PRINT((ndo, " rrep-ack %u", length));
break;
default:
ND_PRINT((ndo, " type %u %u", msg_type, length));
}
return;
trunc:
ND_PRINT((ndo, " [|aodv]"));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2677_0 |
crossvul-cpp_data_bad_2707_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 fragmentation header printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "ip6.h"
int
frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(dp->ip6f_offlg);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2707_0 |
crossvul-cpp_data_good_5106_0 | /* airpdcap.c
*
* Copyright (c) 2006 CACE Technologies, Davis (California)
* 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.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
*/
/*
* The files matching airpcap*.[ch] were originally developed as part of
* Wireshark's support for AirPcap adapters. However, they've been used
* for general 802.11 decryption for quite some time. It might make sense
* to rename them accordingly.
*/
/****************************************************************************/
/* File includes */
#include "config.h"
#include <glib.h>
#include <wsutil/crc32.h>
#include <wsutil/rc4.h>
#include <wsutil/sha1.h>
#include <wsutil/sha2.h>
#include <wsutil/md5.h>
#include <wsutil/pint.h>
#include <wsutil/aes.h>
#include <epan/tvbuff.h>
#include <epan/to_str.h>
#include <epan/strutil.h>
#include <epan/crypt/airpdcap_rijndael.h>
#include "airpdcap_system.h"
#include "airpdcap_int.h"
#include "airpdcap_debug.h"
#include "wep-wpadefs.h"
/****************************************************************************/
/****************************************************************************/
/* Constant definitions */
/* EAPOL definitions */
/**
* Length of the EAPOL-Key key confirmation key (KCK) used to calculate
* MIC over EAPOL frame and validate an EAPOL packet (128 bits)
*/
#define AIRPDCAP_WPA_KCK_LEN 16
/**
*Offset of the Key MIC in the EAPOL packet body
*/
#define AIRPDCAP_WPA_MICKEY_OFFSET 77
/**
* Maximum length of the EAPOL packet (it depends on the maximum MAC
* frame size)
*/
#define AIRPDCAP_WPA_MAX_EAPOL_LEN 4095
/**
* EAPOL Key Descriptor Version 1, used for all EAPOL-Key frames to and
* from a STA when neither the group nor pairwise ciphers are CCMP for
* Key Descriptor 1.
* @note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_NOT_CCMP 1
/**
* EAPOL Key Descriptor Version 2, used for all EAPOL-Key frames to and
* from a STA when either the pairwise or the group cipher is AES-CCMP
* for Key Descriptor 2.
* /note
* Defined in 802.11i-2004, page 78
*/
#define AIRPDCAP_WPA_KEY_VER_AES_CCMP 2
/** Define EAPOL Key Descriptor type values: use 254 for WPA and 2 for WPA2 **/
#define AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR 254
#define AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR 2
/****************************************************************************/
/****************************************************************************/
/* Macro definitions */
extern const UINT32 crc32_table[256];
#define CRC(crc, ch) (crc = (crc >> 8) ^ crc32_table[(crc ^ (ch)) & 0xff])
#define AIRPDCAP_GET_TK(ptk) (ptk + 32)
/****************************************************************************/
/****************************************************************************/
/* Type definitions */
/* Internal function prototype declarations */
#ifdef __cplusplus
extern "C" {
#endif
/**
* It is a step of the PBKDF2 (specifically the PKCS #5 v2.0) defined in
* the RFC 2898 to derive a key (used as PMK in WPA)
* @param ppbytes [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param iterations [IN] times to hash the password (4096 for WPA)
* @param count [IN] ???
* @param output [OUT] pointer to a preallocated buffer of
* SHA1_DIGEST_LEN characters that will contain a part of the key
*/
static INT AirPDcapRsnaPwd2PskStep(
const guint8 *ppbytes,
const guint passLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
;
/**
* It calculates the passphrase-to-PSK mapping reccomanded for use with
* RSNAs. This implementation uses the PBKDF2 method defined in the RFC
* 2898.
* @param passphrase [IN] pointer to a password (sequence of between 8 and
* 63 ASCII encoded characters)
* @param ssid [IN] pointer to the SSID string encoded in max 32 ASCII
* encoded characters
* @param output [OUT] calculated PSK (to use as PMK in WPA)
* @note
* Described in 802.11i-2004, page 165
*/
static INT AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
;
static INT AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
;
static INT AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
;
/**
* It checks whether the specified key is corrected or not.
* @note
* For a standard WEP key the length will be changed to the standard
* length, and the type changed in a generic WEP key.
* @param key [IN] pointer to the key to validate
* @return
* - TRUE: the key contains valid fields and values
* - FALSE: the key has some invalid field or value
*/
static INT AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
;
static INT AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
;
/**
* @param ctx [IN] pointer to the current context
* @param id [IN] id of the association (composed by BSSID and MAC of
* the station)
* @return
* - index of the Security Association structure if found
* - -1, if the specified addresses pair BSSID-STA MAC has not been found
*/
static INT AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static INT AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
;
static const UCHAR * AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static const UCHAR * AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
;
static void AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
;
/**
* @param sa [IN/OUT] pointer to SA that will hold the key
* @param data [IN] Frame
* @param offset_rsne [IN] RSNE IE offset in the frame
* @param offset_fte [IN] Fast BSS Transition IE offset in the frame
* @param offset_timeout [IN] Timeout Interval IE offset in the frame
* @param offset_link [IN] Link Identifier IE offset in the frame
* @param action [IN] Tdls Action code (response or confirm)
*
* @return
* AIRPDCAP_RET_SUCCESS if Key has been sucessfully derived (and MIC verified)
* AIRPDCAP_RET_UNSUCCESS otherwise
*/
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
;
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Exported function definitions */
#ifdef __cplusplus
extern "C" {
#endif
const guint8 broadcast_mac[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
#define EAPKEY_MIC_LEN 16 /* length of the MIC key for EAPoL_Key packet's MIC using MD5 */
#define NONCE_LEN 32
#define TKIP_GROUP_KEY_LEN 32
#define CCMP_GROUP_KEY_LEN 16
typedef struct {
guint8 type;
guint8 key_information[2]; /* Make this an array to avoid alignment issues */
guint8 key_length[2]; /* Make this an array to avoid alignment issues */
guint8 replay_counter[8];
guint8 key_nonce[NONCE_LEN];
guint8 key_iv[16];
guint8 key_sequence_counter[8]; /* also called the RSC */
guint8 key_id[8];
guint8 key_mic[EAPKEY_MIC_LEN];
guint8 key_data_len[2]; /* Make this an array rather than a U16 to avoid alignment shifting */
} EAPOL_RSN_KEY, * P_EAPOL_RSN_KEY;
/* Minimum possible key data size (at least one GTK KDE with CCMP key) */
#define GROUP_KEY_MIN_LEN 8 + CCMP_GROUP_KEY_LEN
/* Minimum possible group key msg size (group key msg using CCMP as cipher)*/
#define GROUP_KEY_PAYLOAD_LEN_MIN sizeof(EAPOL_RSN_KEY) + GROUP_KEY_MIN_LEN
/* XXX - what if this doesn't get the key? */
static INT
AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_key, PAIRPDCAP_SEC_ASSOCIATION sa, guint eapol_len)
{
guint8 key_version;
guint8 *key_data;
guint8 *szEncryptedKey;
guint16 key_bytes_len = 0; /* Length of the total key data field */
guint16 key_len; /* Actual group key length */
static AIRPDCAP_KEY_ITEM dummy_key; /* needed in case AirPDcapRsnaMng() wants the key structure */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
/* We skip verifying the MIC of the key. If we were implementing a WPA supplicant we'd want to verify, but for a sniffer it's not needed. */
/* Preparation for decrypting the group key - determine group key data length */
/* depending on whether the pairwise key is TKIP or AES encryption key */
key_version = AIRPDCAP_EAP_KEY_DESCR_VER(pEAPKey->key_information[1]);
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
/* TKIP */
key_bytes_len = pntoh16(pEAPKey->key_length);
}else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES */
key_bytes_len = pntoh16(pEAPKey->key_data_len);
/* AES keys must be at least 128 bits = 16 bytes. */
if (key_bytes_len < 16) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
}
if ((key_bytes_len < GROUP_KEY_MIN_LEN) ||
(eapol_len < sizeof(EAPOL_RSN_KEY)) ||
(key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Encrypted key is in the information element field of the EAPOL key packet */
key_data = (guint8 *)pEAPKey + sizeof(EAPOL_RSN_KEY);
szEncryptedKey = (guint8 *)g_memdup(key_data, key_bytes_len);
DEBUG_DUMP("Encrypted Broadcast key:", szEncryptedKey, key_bytes_len);
DEBUG_DUMP("KeyIV:", pEAPKey->key_iv, 16);
DEBUG_DUMP("decryption_key:", decryption_key, 16);
/* We are rekeying, save old sa */
tmp_sa=(AIRPDCAP_SEC_ASSOCIATION *)g_malloc(sizeof(AIRPDCAP_SEC_ASSOCIATION));
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
/* As we have no concept of the prior association request at this point, we need to deduce the */
/* group key cipher from the length of the key bytes. In WPA this is straightforward as the */
/* keybytes just contain the GTK, and the GTK is only in the group handshake, NOT the M3. */
/* In WPA2 its a little more tricky as the M3 keybytes contain an RSN_IE, but the group handshake */
/* does not. Also there are other (variable length) items in the keybytes which we need to account */
/* for to determine the true key length, and thus the group cipher. */
if (key_version == AIRPDCAP_WPA_KEY_VER_NOT_CCMP){
guint8 new_key[32];
guint8 dummy[256];
/* TKIP key */
/* Per 802.11i, Draft 3.0 spec, section 8.5.2, p. 97, line 4-8, */
/* group key is decrypted using RC4. Concatenate the IV with the 16 byte EK (PTK+16) to get the decryption key */
rc4_state_struct rc4_state;
/* The WPA group key just contains the GTK bytes so deducing the type is straightforward */
/* Note - WPA M3 doesn't contain a group key so we'll only be here for the group handshake */
sa->wpa.key_ver = (key_bytes_len >=TKIP_GROUP_KEY_LEN)?AIRPDCAP_WPA_KEY_VER_NOT_CCMP:AIRPDCAP_WPA_KEY_VER_AES_CCMP;
/* Build the full decryption key based on the IV and part of the pairwise key */
memcpy(new_key, pEAPKey->key_iv, 16);
memcpy(new_key+16, decryption_key, 16);
DEBUG_DUMP("FullDecrKey:", new_key, 32);
crypt_rc4_init(&rc4_state, new_key, sizeof(new_key));
/* Do dummy 256 iterations of the RC4 algorithm (per 802.11i, Draft 3.0, p. 97 line 6) */
crypt_rc4(&rc4_state, dummy, 256);
crypt_rc4(&rc4_state, szEncryptedKey, key_bytes_len);
} else if (key_version == AIRPDCAP_WPA_KEY_VER_AES_CCMP){
/* AES CCMP key */
guint8 key_found;
guint8 key_length;
guint16 key_index;
guint8 *decrypted_data;
/* Unwrap the key; the result is key_bytes_len in length */
decrypted_data = AES_unwrap(decryption_key, 16, szEncryptedKey, key_bytes_len);
/* With WPA2 what we get after Broadcast Key decryption is an actual RSN structure.
The key itself is stored as a GTK KDE
WPA2 IE (1 byte) id = 0xdd, length (1 byte), GTK OUI (4 bytes), key index (1 byte) and 1 reserved byte. Thus we have to
pass pointer to the actual key with 8 bytes offset */
key_found = FALSE;
key_index = 0;
/* Parse Key data until we found GTK KDE */
/* GTK KDE = 00-0F-AC 01 */
while(key_index < (key_bytes_len - 6) && !key_found){
guint8 rsn_id;
guint32 type;
/* Get RSN ID */
rsn_id = decrypted_data[key_index];
type = ((decrypted_data[key_index + 2] << 24) +
(decrypted_data[key_index + 3] << 16) +
(decrypted_data[key_index + 4] << 8) +
(decrypted_data[key_index + 5]));
if (rsn_id == 0xdd && type == 0x000fac01) {
key_found = TRUE;
} else {
key_index += decrypted_data[key_index+1]+2;
}
}
if (key_found){
key_length = decrypted_data[key_index+1] - 6;
if (key_index+8 >= key_bytes_len ||
key_length > key_bytes_len - key_index - 8) {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Skip over the GTK header info, and don't copy past the end of the encrypted data */
memcpy(szEncryptedKey, decrypted_data+key_index+8, key_length);
} else {
g_free(decrypted_data);
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
if (key_length == TKIP_GROUP_KEY_LEN)
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_NOT_CCMP;
else
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
g_free(decrypted_data);
}
key_len = (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)?TKIP_GROUP_KEY_LEN:CCMP_GROUP_KEY_LEN;
if (key_len > key_bytes_len) {
/* the key required for this protocol is longer than the key that we just calculated */
g_free(szEncryptedKey);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Decrypted key is now in szEncryptedKey with len of key_len */
DEBUG_DUMP("Broadcast key:", szEncryptedKey, key_len);
/* Load the proper key material info into the SA */
sa->key = &dummy_key; /* we just need key to be not null because it is checked in AirPDcapRsnaMng(). The WPA key materials are actually in the .wpa structure */
sa->validKey = TRUE;
/* Since this is a GTK and its size is only 32 bytes (vs. the 64 byte size of a PTK), we fake it and put it in at a 32-byte offset so the */
/* AirPDcapRsnaMng() function will extract the right piece of the GTK for decryption. (The first 16 bytes of the GTK are used for decryption.) */
memset(sa->wpa.ptk, 0, sizeof(sa->wpa.ptk));
memcpy(sa->wpa.ptk+32, szEncryptedKey, key_len);
g_free(szEncryptedKey);
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* Return a pointer the the requested SA. If it doesn't exist create it. */
static PAIRPDCAP_SEC_ASSOCIATION
AirPDcapGetSaPtr(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
int sa_index;
/* search for a cached Security Association for supplied BSSID and STA MAC */
if ((sa_index=AirPDcapGetSa(ctx, id))==-1) {
/* create a new Security Association if it doesn't currently exist */
if ((sa_index=AirPDcapStoreSa(ctx, id))==-1) {
return NULL;
}
}
/* get the Security Association structure */
return &ctx->sa[sa_index];
}
static INT AirPDcapScanForKeys(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
AIRPDCAP_SEC_ASSOCIATION_ID id
)
{
const UCHAR *addr;
guint bodyLength;
PAIRPDCAP_SEC_ASSOCIATION sta_sa;
PAIRPDCAP_SEC_ASSOCIATION sa;
guint offset = 0;
const guint8 dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x88, 0x8E /* Type: 802.1X authentication */
};
const guint8 bt_dot1x_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */
0x00, 0x03 /* Type: Bluetooth Security */
};
const guint8 tdls_header[] = {
0xAA, /* DSAP=SNAP */
0xAA, /* SSAP=SNAP */
0x03, /* Control field=Unnumbered frame */
0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */
0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */
0x02, /* Payload Type: TDLS */
0X0C /* Action Category: TDLS */
};
const EAPOL_RSN_KEY *pEAPKey;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapScanForKeys");
/* cache offset in the packet data */
offset = mac_header_len;
/* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */
if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=8;
/* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */
if (data[offset+1]!=3) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not EAPOL-Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* get and check the body length (IEEE 802.1X-2004, pg. 25) */
bodyLength=pntoh16(data+offset+2);
if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "EAPOL body too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip EAPOL MPDU and go to the first byte of the body */
offset+=4;
pEAPKey = (const EAPOL_RSN_KEY *) (data+offset);
/* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */
if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */
pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */
pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not valid key descriptor type", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* start with descriptor body */
offset+=1;
/* search for a cached Security Association for current BSSID and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "No SA for BSSID found", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_REQ_DATA;
}
/* It could be a Pairwise Key exchange, check */
if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE)
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Message too short for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 ||
AIRPDCAP_EAP_ACK(data[offset+1])!=1 ||
AIRPDCAP_EAP_MIC(data[offset]) != 1 ||
AIRPDCAP_EAP_SEC(data[offset]) != 1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Key bitfields not correct for Group Key", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* force STA address to be the broadcast MAC so we create an SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
/* get the Security Association structure for the broadcast MAC and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */
/* get STA address */
if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) {
memcpy(id.sta, addr, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
#endif
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "SA not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
sta_sa = AirPDcapGetSaPtr(ctx, &id);
if (sta_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* Try to extract the group key and install it in the SA */
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1));
} else if (memcmp(data+offset, tdls_header, 10) == 0) {
const guint8 *initiator, *responder;
guint8 action;
guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Authentication: TDLS Action Frame", AIRPDCAP_DEBUG_LEVEL_3);
/* skip LLC header */
offset+=10;
/* check if the packet is a TDLS response or confirm */
action = data[offset];
if (action!=1 && action!=2) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Not Response nor confirm", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* check status */
offset++;
status=pntoh16(data+offset);
if (status!=0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "TDLS setup not successfull", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* skip Token + capabilities */
offset+=5;
/* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */
while(offset < (tot_len - 2)) {
if (data[offset] == 48) {
offset_rsne = offset;
} else if (data[offset] == 55) {
offset_fte = offset;
} else if (data[offset] == 56) {
offset_timeout = offset;
} else if (data[offset] == 101) {
offset_link = offset;
}
if (tot_len < offset + data[offset + 1] + 2) {
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
offset += data[offset + 1] + 2;
}
if (offset_rsne == 0 || offset_fte == 0 ||
offset_timeout == 0 || offset_link == 0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Cannot Find all necessary IEs", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Found RSNE/Fast BSS/Timeout Interval/Link IEs", AIRPDCAP_DEBUG_LEVEL_3);
/* Will create a Security Association between 2 STA. Need to get both MAC address */
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN);
} else {
memcpy(id.sta, responder, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN);
}
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
if (sa->validKey) {
if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) {
/* Already have valid key for this SA, no need to redo key derivation */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* We are opening a new session with the same two STA, save previous sa */
AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->next=tmp_sa;
sa->validKey = FALSE;
}
}
if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action)
== AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapScanForKeys", "Skipping: not an EAPOL packet", AIRPDCAP_DEBUG_LEVEL_3);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapScanForKeys");
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
INT AirPDcapPacketProcess(
PAIRPDCAP_CONTEXT ctx,
const guint8 *data,
const guint mac_header_len,
const guint tot_len,
UCHAR *decrypt_data,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
gboolean scanHandshake)
{
AIRPDCAP_SEC_ASSOCIATION_ID id;
UCHAR tmp_data[AIRPDCAP_MAX_CAPLEN];
guint tmp_len;
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
AIRPDCAP_DEBUG_TRACE_START("AirPDcapPacketProcess");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
if (data==NULL || tot_len==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "NULL data or length=0", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapPacketProcess");
return AIRPDCAP_RET_REQ_DATA;
}
/* check if the packet is of data or robust managment type */
if (!((AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_DATA) ||
(AIRPDCAP_TYPE(data[0])==AIRPDCAP_TYPE_MANAGEMENT &&
(AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DISASS ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_DEAUTHENTICATION ||
AIRPDCAP_SUBTYPE(data[0])==AIRPDCAP_SUBTYPE_ACTION)))) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "not data nor robust mgmt packet", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_DATA;
}
/* check correct packet size, to avoid wrong elaboration of encryption algorithms */
if (tot_len < (UINT)(mac_header_len+AIRPDCAP_CRYPTED_DATA_MINLEN)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "minimum length violated", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_WRONG_DATA_SIZE;
}
/* Assume that the decrypt_data field is at least this size. */
if (tot_len > AIRPDCAP_MAX_CAPLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "length too large", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* get STA/BSSID address */
if (AirPDcapGetSaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data), &id) != AIRPDCAP_RET_SUCCESS) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "STA/BSSID not found", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_REQ_DATA;
}
/* check if data is encrypted (use the WEP bit in the Frame Control field) */
if (AIRPDCAP_WEP(data[1])==0) {
if (scanHandshake) {
/* data is sent in cleartext, check if is an authentication message or end the process */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Unencrypted data", AIRPDCAP_DEBUG_LEVEL_3);
return (AirPDcapScanForKeys(ctx, data, mac_header_len, tot_len, id));
}
return AIRPDCAP_RET_NO_DATA_ENCRYPTED;
} else {
PAIRPDCAP_SEC_ASSOCIATION sa;
int offset = 0;
/* get the Security Association structure for the STA and AP */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
/* cache offset in the packet data (to scan encryption data) */
offset = mac_header_len;
if (decrypt_data==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "no decrypt buffer, use local", AIRPDCAP_DEBUG_LEVEL_3);
decrypt_data=tmp_data;
decrypt_len=&tmp_len;
}
/* create new header and data to modify */
*decrypt_len = tot_len;
memcpy(decrypt_data, data, *decrypt_len);
/* encrypted data */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "Encrypted data", AIRPDCAP_DEBUG_LEVEL_3);
/* check the Extension IV to distinguish between WEP encryption and WPA encryption */
/* refer to IEEE 802.11i-2004, 8.2.1.2, pag.35 for WEP, */
/* IEEE 802.11i-2004, 8.3.2.2, pag. 45 for TKIP, */
/* IEEE 802.11i-2004, 8.3.3.2, pag. 57 for CCMP */
if (AIRPDCAP_EXTIV(data[offset+3])==0) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "WEP encryption", AIRPDCAP_DEBUG_LEVEL_3);
return AirPDcapWepMng(ctx, decrypt_data, mac_header_len, decrypt_len, key, sa, offset);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "TKIP or CCMP encryption", AIRPDCAP_DEBUG_LEVEL_3);
/* If index >= 1, then use the group key. This will not work if the AP is using
more than one group key simultaneously. I've not seen this in practice, however.
Usually an AP will rotate between the two key index values of 1 and 2 whenever
it needs to change the group key to be used. */
if (AIRPDCAP_KEY_INDEX(data[offset+3])>=1){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", "The key index >= 1. This is encrypted with a group key.", AIRPDCAP_DEBUG_LEVEL_3);
/* force STA address to broadcast MAC so we load the SA for the groupkey */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapPacketProcess", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
/* search for a cached Security Association for current BSSID and broadcast MAC */
sa = AirPDcapGetSaPtr(ctx, &id);
if (sa == NULL)
return AIRPDCAP_RET_REQ_DATA;
}
/* Decrypt the packet using the appropriate SA */
if (AirPDcapRsnaMng(decrypt_data, mac_header_len, decrypt_len, key, sa, offset) == AIRPDCAP_RET_SUCCESS) {
/* If we successfully decrypted a packet, scan it to see if it contains a key handshake.
The group key handshake could be sent at any time the AP wants to change the key (such as when
it is using key rotation) and it also could be a rekey for the Pairwise key. So we must scan every packet. */
if (scanHandshake) {
return (AirPDcapScanForKeys(ctx, decrypt_data, mac_header_len, *decrypt_len, id));
} else {
return AIRPDCAP_RET_SUCCESS;
}
}
}
}
return AIRPDCAP_RET_UNSUCCESS;
}
INT AirPDcapSetKeys(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
INT i;
INT success;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapSetKeys");
if (ctx==NULL || keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "NULL context or NULL keys array", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
if (keys_nr>AIRPDCAP_MAX_KEYS_NR) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Keys number greater than maximum", AIRPDCAP_DEBUG_LEVEL_3);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return 0;
}
/* clean key and SA collections before setting new ones */
AirPDcapInitContext(ctx);
/* check and insert keys */
for (i=0, success=0; i<(INT)keys_nr; i++) {
if (AirPDcapValidateKey(keys+i)==TRUE) {
if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PWD key", AIRPDCAP_DEBUG_LEVEL_4);
AirPDcapRsnaPwd2Psk(keys[i].UserPwd.Passphrase, keys[i].UserPwd.Ssid, keys[i].UserPwd.SsidLen, keys[i].KeyData.Wpa.Psk);
}
#ifdef _DEBUG
else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WPA-PMK key", AIRPDCAP_DEBUG_LEVEL_4);
} else if (keys[i].KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a WEP key", AIRPDCAP_DEBUG_LEVEL_4);
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapSetKeys", "Set a key", AIRPDCAP_DEBUG_LEVEL_4);
}
#endif
memcpy(&ctx->keys[success], &keys[i], sizeof(keys[i]));
success++;
}
}
ctx->keys_nr=success;
AIRPDCAP_DEBUG_TRACE_END("AirPDcapSetKeys");
return success;
}
static void
AirPDcapCleanKeys(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapCleanKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
return;
}
memset(ctx->keys, 0, sizeof(AIRPDCAP_KEY_ITEM) * AIRPDCAP_MAX_KEYS_NR);
ctx->keys_nr=0;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapCleanKeys", "Keys collection cleaned!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapCleanKeys");
}
static void
AirPDcapRecurseCleanSA(
PAIRPDCAP_SEC_ASSOCIATION sa)
{
if (sa->next != NULL) {
AirPDcapRecurseCleanSA(sa->next);
g_free(sa->next);
sa->next = NULL;
}
}
static void
AirPDcapCleanSecAssoc(
PAIRPDCAP_CONTEXT ctx)
{
PAIRPDCAP_SEC_ASSOCIATION psa;
int i;
for (psa = ctx->sa, i = 0; i < AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; i++, psa++) {
/* To iterate is human, to recurse, divine */
AirPDcapRecurseCleanSA(psa);
}
}
INT AirPDcapGetKeys(
const PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_KEY_ITEM keys[],
const size_t keys_nr)
{
UINT i;
UINT j;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapGetKeys");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return 0;
} else if (keys==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "NULL keys array", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return (INT)ctx->keys_nr;
} else {
for (i=0, j=0; i<ctx->keys_nr && i<keys_nr && i<AIRPDCAP_MAX_KEYS_NR; i++) {
memcpy(&keys[j], &ctx->keys[i], sizeof(keys[j]));
j++;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetKeys", "Got a key", AIRPDCAP_DEBUG_LEVEL_5);
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapGetKeys");
return j;
}
}
/*
* XXX - This won't be reliable if a packet containing SSID "B" shows
* up in the middle of a 4-way handshake for SSID "A".
* We should probably use a small array or hash table to keep multiple
* SSIDs.
*/
INT AirPDcapSetLastSSID(
PAIRPDCAP_CONTEXT ctx,
CHAR *pkt_ssid,
size_t pkt_ssid_len)
{
if (!ctx || !pkt_ssid || pkt_ssid_len < 1 || pkt_ssid_len > WPA_SSID_MAX_SIZE)
return AIRPDCAP_RET_UNSUCCESS;
memcpy(ctx->pkt_ssid, pkt_ssid, pkt_ssid_len);
ctx->pkt_ssid_len = pkt_ssid_len;
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapInitContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapInitContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
ctx->pkt_ssid_len = 0;
memset(ctx->sa, 0, AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR * sizeof(AIRPDCAP_SEC_ASSOCIATION));
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapInitContext", "Context initialized!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapInitContext");
return AIRPDCAP_RET_SUCCESS;
}
INT AirPDcapDestroyContext(
PAIRPDCAP_CONTEXT ctx)
{
AIRPDCAP_DEBUG_TRACE_START("AirPDcapDestroyContext");
if (ctx==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "NULL context", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_UNSUCCESS;
}
AirPDcapCleanKeys(ctx);
AirPDcapCleanSecAssoc(ctx);
ctx->first_free_index=0;
ctx->index=-1;
ctx->sa_index=-1;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapDestroyContext", "Context destroyed!", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_END("AirPDcapDestroyContext");
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/****************************************************************************/
/* Internal function definitions */
#ifdef __cplusplus
extern "C" {
#endif
static INT
AirPDcapRsnaMng(
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
INT ret_value=1;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
if (*decrypt_len > try_data_len) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* allocate a temp buffer for the decryption loop */
try_data=(UCHAR *)g_malloc(try_data_len);
/* start of loop added by GCS */
for(/* sa */; sa != NULL ;sa=sa->next) {
if (sa->validKey==FALSE) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Key not yet valid", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
/* copy the encrypted data into a temp buffer */
memcpy(try_data, decrypt_data, *decrypt_len);
if (sa->wpa.key_ver==1) {
/* CCMP -> HMAC-MD5 is the EAPOL-Key MIC, RC4 is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP", AIRPDCAP_DEBUG_LEVEL_3);
DEBUG_DUMP("ptk", sa->wpa.ptk, 64);
DEBUG_DUMP("ptk portion used", AIRPDCAP_GET_TK(sa->wpa.ptk), 16);
ret_value=AirPDcapTkipDecrypt(try_data+offset, *decrypt_len-offset, try_data+AIRPDCAP_TA_OFFSET, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value){
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP failed!", AIRPDCAP_DEBUG_LEVEL_3);
continue;
}
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "TKIP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) and ICV (4bytes) from the end of packet */
*decrypt_len-=12;
break;
} else {
/* AES-CCMP -> HMAC-SHA1-128 is the EAPOL-Key MIC, AES wep_key wrap is the EAPOL-Key encryption algorithm */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP", AIRPDCAP_DEBUG_LEVEL_3);
ret_value=AirPDcapCcmpDecrypt(try_data, mac_header_len, (INT)*decrypt_len, AIRPDCAP_GET_TK(sa->wpa.ptk));
if (ret_value)
continue;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "CCMP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove MIC (8bytes) from the end of packet */
*decrypt_len-=8;
break;
}
}
/* end of loop */
/* none of the keys worked */
if(sa == NULL) {
g_free(try_data);
return ret_value;
}
if (*decrypt_len > try_data_len || *decrypt_len < 8) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsnaMng", "Invalid decryption length", AIRPDCAP_DEBUG_LEVEL_3);
g_free(try_data);
return AIRPDCAP_RET_UNSUCCESS;
}
/* copy the decrypted data into the decrypt buffer GCS*/
memcpy(decrypt_data, try_data, *decrypt_len);
g_free(try_data);
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove TKIP/CCMP header */
offset = mac_header_len;
*decrypt_len-=8;
memmove(decrypt_data+offset, decrypt_data+offset+8, *decrypt_len-offset);
if (key!=NULL) {
if (sa->key!=NULL)
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
else
memset(key, 0, sizeof(AIRPDCAP_KEY_ITEM));
memcpy(key->KeyData.Wpa.Ptk, sa->wpa.ptk, AIRPDCAP_WPA_PTK_LEN); /* copy the PTK to the key structure for future use by wireshark */
if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_TKIP;
else if (sa->wpa.key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP)
key->KeyType=AIRPDCAP_KEY_TYPE_CCMP;
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapWepMng(
PAIRPDCAP_CONTEXT ctx,
UCHAR *decrypt_data,
guint mac_header_len,
guint *decrypt_len,
PAIRPDCAP_KEY_ITEM key,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset)
{
UCHAR wep_key[AIRPDCAP_WEP_KEY_MAXLEN+AIRPDCAP_WEP_IVLEN];
size_t keylen;
INT ret_value=1;
INT key_index;
AIRPDCAP_KEY_ITEM *tmp_key;
UINT8 useCache=FALSE;
UCHAR *try_data;
guint try_data_len = *decrypt_len;
try_data = (UCHAR *)g_malloc(try_data_len);
if (sa->key!=NULL)
useCache=TRUE;
for (key_index=0; key_index<(INT)ctx->keys_nr; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
tmp_key=&ctx->keys[key_index];
} else {
if (sa->key!=NULL && sa->key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try cached WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Cached key is not valid, try another WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WEP keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Try WEP key...", AIRPDCAP_DEBUG_LEVEL_3);
memset(wep_key, 0, sizeof(wep_key));
memcpy(try_data, decrypt_data, *decrypt_len);
/* Costruct the WEP seed: copy the IV in first 3 bytes and then the WEP key (refer to 802-11i-2004, 8.2.1.4.3, pag. 36) */
memcpy(wep_key, try_data+mac_header_len, AIRPDCAP_WEP_IVLEN);
keylen=tmp_key->KeyData.Wep.WepKeyLen;
memcpy(wep_key+AIRPDCAP_WEP_IVLEN, tmp_key->KeyData.Wep.WepKey, keylen);
ret_value=AirPDcapWepDecrypt(wep_key,
keylen+AIRPDCAP_WEP_IVLEN,
try_data + (mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN),
*decrypt_len-(mac_header_len+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN+AIRPDCAP_CRC_LEN));
if (ret_value == AIRPDCAP_RET_SUCCESS)
memcpy(decrypt_data, try_data, *decrypt_len);
}
if (!ret_value && tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WEP) {
/* the tried key is the correct one, cached in the Security Association */
sa->key=tmp_key;
if (key!=NULL) {
memcpy(key, sa->key, sizeof(AIRPDCAP_KEY_ITEM));
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
}
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
g_free(try_data);
if (ret_value)
return AIRPDCAP_RET_UNSUCCESS;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "WEP DECRYPTED!!!", AIRPDCAP_DEBUG_LEVEL_3);
/* remove ICV (4bytes) from the end of packet */
*decrypt_len-=4;
if (*decrypt_len < 4) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapWepMng", "Decryption length too short", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
/* remove protection bit */
decrypt_data[1]&=0xBF;
/* remove IC header */
offset = mac_header_len;
*decrypt_len-=4;
memmove(decrypt_data+offset, decrypt_data+offset+AIRPDCAP_WEP_IVLEN+AIRPDCAP_WEP_KIDLEN, *decrypt_len-offset);
return AIRPDCAP_RET_SUCCESS;
}
/* Refer to IEEE 802.11i-2004, 8.5.3, pag. 85 */
static INT
AirPDcapRsna4WHandshake(
PAIRPDCAP_CONTEXT ctx,
const UCHAR *data,
AIRPDCAP_SEC_ASSOCIATION *sa,
INT offset,
const guint tot_len)
{
AIRPDCAP_KEY_ITEM *tmp_key, *tmp_pkt_key, pkt_key;
AIRPDCAP_SEC_ASSOCIATION *tmp_sa;
INT key_index;
INT ret_value=1;
UCHAR useCache=FALSE;
UCHAR eapol[AIRPDCAP_EAPOL_MAX_LEN];
USHORT eapol_len;
if (sa->key!=NULL)
useCache=TRUE;
/* a 4-way handshake packet use a Pairwise key type (IEEE 802.11i-2004, pg. 79) */
if (AIRPDCAP_EAP_KEY(data[offset+1])!=1) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Group/STAKey message (not used)", AIRPDCAP_DEBUG_LEVEL_5);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
/* TODO timeouts? */
/* TODO consider key-index */
/* TODO considera Deauthentications */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake...", AIRPDCAP_DEBUG_LEVEL_5);
/* manage 4-way handshake packets; this step completes the 802.1X authentication process (IEEE 802.11i-2004, pag. 85) */
/* message 1: Authenticator->Supplicant (Sec=0, Mic=0, Ack=1, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=ANonce, MIC=0) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==0)
{
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 1", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 1, the Supplicant determines whether the Key Replay Counter field value has been */
/* used before with the current PMKSA. If the Key Replay Counter field value is less than or equal to the current */
/* local value, the Supplicant discards the message. */
/* -> not checked, the Authenticator will be send another Message 1 (hopefully!) */
/* This saves the sa since we are reauthenticating which will overwrite our current sa GCS*/
if( sa->handshake >= 2) {
tmp_sa= g_new(AIRPDCAP_SEC_ASSOCIATION, 1);
memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION));
sa->validKey=FALSE;
sa->next=tmp_sa;
}
/* save ANonce (from authenticator) to derive the PTK with the SNonce (from the 2 message) */
memcpy(sa->wpa.nonce, data+offset+12, 32);
/* get the Key Descriptor Version (to select algorithm used in decryption -CCMP or TKIP-) */
sa->wpa.key_ver=AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1]);
sa->handshake=1;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
/* message 2|4: Supplicant->Authenticator (Sec=0|1, Mic=1, Ack=0, Inst=0, Key=1(pairwise), KeyRSC=0, Nonce=SNonce|0, MIC=MIC(KCK,EAPOL)) */
if (AIRPDCAP_EAP_INST(data[offset+1])==0 &&
AIRPDCAP_EAP_ACK(data[offset+1])==0 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
/* Check key data length to differentiate between message 2 or 4, same as in epan/dissectors/packet-ieee80211.c */
if (pntoh16(data+offset+92)) {
/* message 2 */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 2", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 2, the Authenticator checks that the key replay counter corresponds to the */
/* outstanding Message 1. If not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, */
/* the Authenticator silently discards Message 2. */
/* -> not checked; the Supplicant will send another message 2 (hopefully!) */
/* now you can derive the PTK */
for (key_index=0; key_index<(INT)ctx->keys_nr || useCache; key_index++) {
/* use the cached one, or try all keys */
if (!useCache) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
} else {
/* there is a cached key in the security association, if it's a WPA key try it... */
if (sa->key!=NULL &&
(sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
sa->key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Try cached WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=sa->key;
} else {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "Cached key is of a wrong type, try WPA key...", AIRPDCAP_DEBUG_LEVEL_3);
tmp_key=&ctx->keys[key_index];
}
}
/* obviously, try only WPA keys... */
if (tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK)
{
if (tmp_key->KeyType == AIRPDCAP_KEY_TYPE_WPA_PWD && tmp_key->UserPwd.SsidLen == 0 && ctx->pkt_ssid_len > 0 && ctx->pkt_ssid_len <= AIRPDCAP_WPA_SSID_MAX_LEN) {
/* We have a "wildcard" SSID. Use the one from the packet. */
memcpy(&pkt_key, tmp_key, sizeof(pkt_key));
memcpy(&pkt_key.UserPwd.Ssid, ctx->pkt_ssid, ctx->pkt_ssid_len);
pkt_key.UserPwd.SsidLen = ctx->pkt_ssid_len;
AirPDcapRsnaPwd2Psk(pkt_key.UserPwd.Passphrase, pkt_key.UserPwd.Ssid,
pkt_key.UserPwd.SsidLen, pkt_key.KeyData.Wpa.Psk);
tmp_pkt_key = &pkt_key;
} else {
tmp_pkt_key = tmp_key;
}
/* derive the PTK from the BSSID, STA MAC, PMK, SNonce, ANonce */
AirPDcapRsnaPrfX(sa, /* authenticator nonce, bssid, station mac */
tmp_pkt_key->KeyData.Wpa.Psk, /* PSK == PMK */
data+offset+12, /* supplicant nonce */
512,
sa->wpa.ptk);
/* verify the MIC (compare the MIC in the packet included in this message with a MIC calculated with the PTK) */
eapol_len=pntoh16(data+offset-3)+4;
memcpy(eapol, &data[offset-5], (eapol_len<AIRPDCAP_EAPOL_MAX_LEN?eapol_len:AIRPDCAP_EAPOL_MAX_LEN));
ret_value=AirPDcapRsnaMicCheck(eapol, /* eapol frame (header also) */
eapol_len, /* eapol frame length */
sa->wpa.ptk, /* Key Confirmation Key */
AIRPDCAP_EAP_KEY_DESCR_VER(data[offset+1])); /* EAPOL-Key description version */
/* If the MIC is valid, the Authenticator checks that the RSN information element bit-wise matches */
/* that from the (Re)Association Request message. */
/* i) TODO If these are not exactly the same, the Authenticator uses MLME-DEAUTHENTICATE.request */
/* primitive to terminate the association. */
/* ii) If they do match bit-wise, the Authenticator constructs Message 3. */
}
if (!ret_value &&
(tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PWD ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PSK ||
tmp_key->KeyType==AIRPDCAP_KEY_TYPE_WPA_PMK))
{
/* the temporary key is the correct one, cached in the Security Association */
sa->key=tmp_key;
break;
} else {
/* the cached key was not valid, try other keys */
if (useCache==TRUE) {
useCache=FALSE;
key_index--;
}
}
}
if (ret_value) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "handshake step failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
sa->handshake=2;
sa->validKey=TRUE; /* we can use the key to decode, even if we have not captured the other eapol packets */
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
} else {
/* message 4 */
/* TODO "Note that when the 4-Way Handshake is first used Message 4 is sent in the clear." */
/* TODO check MIC and Replay Counter */
/* On reception of Message 4, the Authenticator verifies that the Key Replay Counter field value is one */
/* that it used on this 4-Way Handshake; if it is not, it silently discards the message. */
/* If the calculated MIC does not match the MIC that the Supplicant included in the EAPOL-Key frame, the */
/* Authenticator silently discards Message 4. */
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 4", AIRPDCAP_DEBUG_LEVEL_3);
sa->handshake=4;
return AIRPDCAP_RET_SUCCESS_HANDSHAKE;
}
}
/* message 3: Authenticator->Supplicant (Sec=1, Mic=1, Ack=1, Inst=0/1, Key=1(pairwise), KeyRSC=???, Nonce=ANonce, MIC=1) */
if (AIRPDCAP_EAP_ACK(data[offset+1])==1 &&
AIRPDCAP_EAP_MIC(data[offset])==1)
{
const EAPOL_RSN_KEY *pEAPKey;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapRsna4WHandshake", "4-way handshake message 3", AIRPDCAP_DEBUG_LEVEL_3);
/* On reception of Message 3, the Supplicant silently discards the message if the Key Replay Counter field */
/* value has already been used or if the ANonce value in Message 3 differs from the ANonce value in Message 1. */
/* -> not checked, the Authenticator will send another message 3 (hopefully!) */
/* TODO check page 88 (RNS) */
/* If using WPA2 PSK, message 3 will contain an RSN for the group key (GTK KDE).
In order to properly support decrypting WPA2-PSK packets, we need to parse this to get the group key. */
pEAPKey = (const EAPOL_RSN_KEY *)(&(data[offset-1]));
if (pEAPKey->type == AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR){
PAIRPDCAP_SEC_ASSOCIATION broadcast_sa;
AIRPDCAP_SEC_ASSOCIATION_ID id;
/* Get broadcacst SA for the current BSSID */
memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN);
memcpy(id.bssid, sa->saId.bssid, AIRPDCAP_MAC_LEN);
broadcast_sa = AirPDcapGetSaPtr(ctx, &id);
if (broadcast_sa == NULL){
return AIRPDCAP_RET_REQ_DATA;
}
return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sa->wpa.ptk+16, broadcast_sa, tot_len-offset+1));
}
}
return AIRPDCAP_RET_NO_VALID_HANDSHAKE;
}
static INT
AirPDcapRsnaMicCheck(
UCHAR *eapol,
USHORT eapol_len,
UCHAR KCK[AIRPDCAP_WPA_KCK_LEN],
USHORT key_ver)
{
UCHAR mic[AIRPDCAP_WPA_MICKEY_LEN];
UCHAR c_mic[20]; /* MIC 16 byte, the HMAC-SHA1 use a buffer of 20 bytes */
/* copy the MIC from the EAPOL packet */
memcpy(mic, eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, AIRPDCAP_WPA_MICKEY_LEN);
/* set to 0 the MIC in the EAPOL packet (to calculate the MIC) */
memset(eapol+AIRPDCAP_WPA_MICKEY_OFFSET+4, 0, AIRPDCAP_WPA_MICKEY_LEN);
if (key_ver==AIRPDCAP_WPA_KEY_VER_NOT_CCMP) {
/* use HMAC-MD5 for the EAPOL-Key MIC */
md5_hmac(eapol, eapol_len, KCK, AIRPDCAP_WPA_KCK_LEN, c_mic);
} else if (key_ver==AIRPDCAP_WPA_KEY_VER_AES_CCMP) {
/* use HMAC-SHA1-128 for the EAPOL-Key MIC */
sha1_hmac(KCK, AIRPDCAP_WPA_KCK_LEN, eapol, eapol_len, c_mic);
} else
/* key descriptor version not recognized */
return AIRPDCAP_RET_UNSUCCESS;
/* compare calculated MIC with the Key MIC and return result (0 means success) */
return memcmp(mic, c_mic, AIRPDCAP_WPA_MICKEY_LEN);
}
static INT
AirPDcapValidateKey(
PAIRPDCAP_KEY_ITEM key)
{
size_t len;
UCHAR ret=TRUE;
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
if (key==NULL) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "NULL key", AIRPDCAP_DEBUG_LEVEL_5);
AIRPDCAP_DEBUG_TRACE_START("AirPDcapValidateKey");
return FALSE;
}
switch (key->KeyType) {
case AIRPDCAP_KEY_TYPE_WEP:
/* check key size limits */
len=key->KeyData.Wep.WepKeyLen;
if (len<AIRPDCAP_WEP_KEY_MINLEN || len>AIRPDCAP_WEP_KEY_MAXLEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WEP key: key length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WEP_40:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_40_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WEP_104:
/* set the standard length and use a generic WEP key type */
key->KeyData.Wep.WepKeyLen=AIRPDCAP_WEP_104_KEY_LEN;
key->KeyType=AIRPDCAP_KEY_TYPE_WEP;
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
/* check passphrase and SSID size limits */
len=strlen(key->UserPwd.Passphrase);
if (len<AIRPDCAP_WPA_PASSPHRASE_MIN_LEN || len>AIRPDCAP_WPA_PASSPHRASE_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: passphrase length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
len=key->UserPwd.SsidLen;
if (len>AIRPDCAP_WPA_SSID_MAX_LEN) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapValidateKey", "WPA-PWD key: ssid length not accepted", AIRPDCAP_DEBUG_LEVEL_5);
ret=FALSE;
}
break;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
break;
default:
ret=FALSE;
}
AIRPDCAP_DEBUG_TRACE_END("AirPDcapValidateKey");
return ret;
}
static INT
AirPDcapGetSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT sa_index;
if (ctx->sa_index!=-1) {
/* at least one association was stored */
/* search for the association from sa_index to 0 (most recent added) */
for (sa_index=ctx->sa_index; sa_index>=0; sa_index--) {
if (ctx->sa[sa_index].used) {
if (memcmp(id, &(ctx->sa[sa_index].saId), sizeof(AIRPDCAP_SEC_ASSOCIATION_ID))==0) {
ctx->index=sa_index;
return sa_index;
}
}
}
}
return -1;
}
static INT
AirPDcapStoreSa(
PAIRPDCAP_CONTEXT ctx,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
INT last_free;
if (ctx->first_free_index>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
if (ctx->sa[ctx->first_free_index].used) {
/* last addition was in the middle of the array (and the first_free_index was just incremented by 1) */
/* search for a free space from the first_free_index to AIRPDCAP_STA_INFOS_NR (to avoid free blocks in */
/* the middle) */
for (last_free=ctx->first_free_index; last_free<AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR; last_free++)
if (!ctx->sa[last_free].used)
break;
if (last_free>=AIRPDCAP_MAX_SEC_ASSOCIATIONS_NR) {
/* there is no empty space available. FAILURE */
return -1;
}
/* store first free space index */
ctx->first_free_index=last_free;
}
/* use this info */
ctx->index=ctx->first_free_index;
/* reset the info structure */
memset(ctx->sa+ctx->index, 0, sizeof(AIRPDCAP_SEC_ASSOCIATION));
ctx->sa[ctx->index].used=1;
/* set the info structure */
memcpy(&(ctx->sa[ctx->index].saId), id, sizeof(AIRPDCAP_SEC_ASSOCIATION_ID));
/* increment by 1 the first_free_index (heuristic) */
ctx->first_free_index++;
/* set the sa_index if the added index is greater the the sa_index */
if (ctx->index > ctx->sa_index)
ctx->sa_index=ctx->index;
return ctx->index;
}
static INT
AirPDcapGetSaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame,
AIRPDCAP_SEC_ASSOCIATION_ID *id)
{
#ifdef _DEBUG
#define MSGBUF_LEN 255
CHAR msgbuf[MSGBUF_LEN];
#endif
if ((AIRPDCAP_TYPE(frame->fc[0])==AIRPDCAP_TYPE_DATA) &&
(AIRPDCAP_DS_BITS(frame->fc[1]) == 0) &&
(memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) != 0) &&
(memcmp(frame->addr1, frame->addr3, AIRPDCAP_MAC_LEN) != 0)) {
/* DATA frame with fromDS=0 ToDS=0 and neither RA or SA is BSSID
=> TDLS traffic. Use highest MAC address for bssid */
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0) {
memcpy(id->sta, frame->addr1, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr2, AIRPDCAP_MAC_LEN);
} else {
memcpy(id->sta, frame->addr2, AIRPDCAP_MAC_LEN);
memcpy(id->bssid, frame->addr1, AIRPDCAP_MAC_LEN);
}
} else {
const UCHAR *addr;
/* Normal Case: SA between STA and AP */
if ((addr = AirPDcapGetBssidAddress(frame)) != NULL) {
memcpy(id->bssid, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
if ((addr = AirPDcapGetStaAddress(frame)) != NULL) {
memcpy(id->sta, addr, AIRPDCAP_MAC_LEN);
} else {
return AIRPDCAP_RET_UNSUCCESS;
}
}
#ifdef _DEBUG
g_snprintf(msgbuf, MSGBUF_LEN, "BSSID_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->bssid[0],id->bssid[1],id->bssid[2],id->bssid[3],id->bssid[4],id->bssid[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
g_snprintf(msgbuf, MSGBUF_LEN, "STA_MAC: %02X.%02X.%02X.%02X.%02X.%02X\t",
id->sta[0],id->sta[1],id->sta[2],id->sta[3],id->sta[4],id->sta[5]);
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapGetSaAddress", msgbuf, AIRPDCAP_DEBUG_LEVEL_3);
#endif
return AIRPDCAP_RET_SUCCESS;
}
/*
* AirPDcapGetBssidAddress() and AirPDcapGetBssidAddress() are used for
* key caching. In each case, it's more important to return a value than
* to return a _correct_ value, so we fudge addresses in some cases, e.g.
* the BSSID in bridged connections.
* FromDS ToDS Sta BSSID
* 0 0 addr1/2 addr3
* 0 1 addr2 addr1
* 1 0 addr1 addr2
* 1 1 addr2 addr1
*/
static const UCHAR *
AirPDcapGetStaAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
if (memcmp(frame->addr2, frame->addr3, AIRPDCAP_MAC_LEN) == 0)
return frame->addr1;
else
return frame->addr2;
case 1:
return frame->addr2;
case 2:
return frame->addr1;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) < 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
static const UCHAR *
AirPDcapGetBssidAddress(
const AIRPDCAP_MAC_FRAME_ADDR4 *frame)
{
switch(AIRPDCAP_DS_BITS(frame->fc[1])) { /* Bit 1 = FromDS, bit 0 = ToDS */
case 0:
return frame->addr3;
case 1:
return frame->addr1;
case 2:
return frame->addr2;
case 3:
if (memcmp(frame->addr1, frame->addr2, AIRPDCAP_MAC_LEN) > 0)
return frame->addr1;
else
return frame->addr2;
default:
return NULL;
}
}
/* Function used to derive the PTK. Refer to IEEE 802.11I-2004, pag. 74
* and IEEE 802.11i-2004, pag. 164 */
static void
AirPDcapRsnaPrfX(
AIRPDCAP_SEC_ASSOCIATION *sa,
const UCHAR pmk[32],
const UCHAR snonce[32],
const INT x, /* for TKIP 512, for CCMP 384 */
UCHAR *ptk)
{
UINT8 i;
UCHAR R[100];
INT offset=sizeof("Pairwise key expansion");
UCHAR output[80]; /* allow for sha1 overflow. */
memset(R, 0, 100);
memcpy(R, "Pairwise key expansion", offset);
/* Min(AA, SPA) || Max(AA, SPA) */
if (memcmp(sa->saId.sta, sa->saId.bssid, AIRPDCAP_MAC_LEN) < 0)
{
memcpy(R + offset, sa->saId.sta, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.bssid, AIRPDCAP_MAC_LEN);
}
else
{
memcpy(R + offset, sa->saId.bssid, AIRPDCAP_MAC_LEN);
memcpy(R + offset+AIRPDCAP_MAC_LEN, sa->saId.sta, AIRPDCAP_MAC_LEN);
}
offset+=AIRPDCAP_MAC_LEN*2;
/* Min(ANonce,SNonce) || Max(ANonce,SNonce) */
if( memcmp(snonce, sa->wpa.nonce, 32) < 0 )
{
memcpy(R + offset, snonce, 32);
memcpy(R + offset + 32, sa->wpa.nonce, 32);
}
else
{
memcpy(R + offset, sa->wpa.nonce, 32);
memcpy(R + offset + 32, snonce, 32);
}
offset+=32*2;
for(i = 0; i < (x+159)/160; i++)
{
R[offset] = i;
sha1_hmac(pmk, 32, R, 100, &output[20 * i]);
}
memcpy(ptk, output, x/8);
}
#define MAX_SSID_LENGTH 32 /* maximum SSID length */
static INT
AirPDcapRsnaPwd2PskStep(
const guint8 *ppBytes,
const guint ppLength,
const CHAR *ssid,
const size_t ssidLength,
const INT iterations,
const INT count,
UCHAR *output)
{
UCHAR digest[MAX_SSID_LENGTH+4]; /* SSID plus 4 bytes of count */
UCHAR digest1[SHA1_DIGEST_LEN];
INT i, j;
if (ssidLength > MAX_SSID_LENGTH) {
/* This "should not happen" */
return AIRPDCAP_RET_UNSUCCESS;
}
memset(digest, 0, sizeof digest);
memset(digest1, 0, sizeof digest1);
/* U1 = PRF(P, S || INT(i)) */
memcpy(digest, ssid, ssidLength);
digest[ssidLength] = (UCHAR)((count>>24) & 0xff);
digest[ssidLength+1] = (UCHAR)((count>>16) & 0xff);
digest[ssidLength+2] = (UCHAR)((count>>8) & 0xff);
digest[ssidLength+3] = (UCHAR)(count & 0xff);
sha1_hmac(ppBytes, ppLength, digest, (guint32) ssidLength+4, digest1);
/* output = U1 */
memcpy(output, digest1, SHA1_DIGEST_LEN);
for (i = 1; i < iterations; i++) {
/* Un = PRF(P, Un-1) */
sha1_hmac(ppBytes, ppLength, digest1, SHA1_DIGEST_LEN, digest);
memcpy(digest1, digest, SHA1_DIGEST_LEN);
/* output = output xor Un */
for (j = 0; j < SHA1_DIGEST_LEN; j++) {
output[j] ^= digest[j];
}
}
return AIRPDCAP_RET_SUCCESS;
}
static INT
AirPDcapRsnaPwd2Psk(
const CHAR *passphrase,
const CHAR *ssid,
const size_t ssidLength,
UCHAR *output)
{
UCHAR m_output[2*SHA1_DIGEST_LEN];
GByteArray *pp_ba = g_byte_array_new();
memset(m_output, 0, 2*SHA1_DIGEST_LEN);
if (!uri_str_to_bytes(passphrase, pp_ba)) {
g_byte_array_free(pp_ba, TRUE);
return 0;
}
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 1, m_output);
AirPDcapRsnaPwd2PskStep(pp_ba->data, pp_ba->len, ssid, ssidLength, 4096, 2, &m_output[SHA1_DIGEST_LEN]);
memcpy(output, m_output, AIRPDCAP_WPA_PSK_LEN);
g_byte_array_free(pp_ba, TRUE);
return 0;
}
/*
* Returns the decryption_key_t struct given a string describing the key.
* Returns NULL if the input_string cannot be parsed.
*/
decryption_key_t*
parse_key_string(gchar* input_string, guint8 key_type)
{
gchar *key, *tmp_str;
gchar *ssid;
GString *key_string = NULL;
GByteArray *ssid_ba = NULL, *key_ba;
gboolean res;
gchar **tokens;
guint n = 0;
decryption_key_t *dk;
if(input_string == NULL)
return NULL;
/*
* Parse the input_string. WEP and WPA will be just a string
* of hexadecimal characters (if key is wrong, null will be
* returned...).
* WPA-PWD should be in the form
* <key data>[:<ssid>]
*/
switch(key_type)
{
case AIRPDCAP_KEY_TYPE_WEP:
case AIRPDCAP_KEY_TYPE_WEP_40:
case AIRPDCAP_KEY_TYPE_WEP_104:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
if (res && key_ba->len > 0) {
/* Key is correct! It was probably an 'old style' WEP key */
/* Create the decryption_key_t structure, fill it and return it*/
dk = (decryption_key_t *)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WEP;
/* XXX - The current key handling code in the GUI requires
* no separators and lower case */
tmp_str = bytes_to_str(NULL, key_ba->data, key_ba->len);
dk->key = g_string_new(tmp_str);
g_string_ascii_down(dk->key);
dk->bits = key_ba->len * 8;
dk->ssid = NULL;
wmem_free(NULL, tmp_str);
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Key doesn't work */
g_byte_array_free(key_ba, TRUE);
return NULL;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
tokens = g_strsplit(input_string,":",0);
/* Tokens is a null termiated array of strings ... */
while(tokens[n] != NULL)
n++;
if(n < 1)
{
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
/*
* The first token is the key
*/
key = g_strdup(tokens[0]);
ssid = NULL;
/* Maybe there is a second token (an ssid, if everything else is ok) */
if(n >= 2)
{
ssid = g_strdup(tokens[1]);
}
/* Create a new string */
key_string = g_string_new(key);
ssid_ba = NULL;
/* Two (or more) tokens mean that the user entered a WPA-PWD key ... */
if( ((key_string->len) > WPA_KEY_MAX_CHAR_SIZE) || ((key_string->len) < WPA_KEY_MIN_CHAR_SIZE))
{
g_string_free(key_string, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid != NULL) /* more than two tokens found, means that the user specified the ssid */
{
ssid_ba = g_byte_array_new();
if (! uri_str_to_bytes(ssid, ssid_ba)) {
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
if(ssid_ba->len > WPA_SSID_MAX_CHAR_SIZE)
{
g_string_free(key_string, TRUE);
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return NULL;
}
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PWD;
dk->key = g_string_new(key);
dk->bits = 256; /* This is the length of the array pf bytes that will be generated using key+ssid ...*/
dk->ssid = byte_array_dup(ssid_ba); /* NULL if ssid_ba is NULL */
g_string_free(key_string, TRUE);
if (ssid_ba != NULL)
g_byte_array_free(ssid_ba, TRUE);
g_free(key);
if(ssid != NULL)
g_free(ssid);
/* Free the array of strings */
g_strfreev(tokens);
return dk;
case AIRPDCAP_KEY_TYPE_WPA_PSK:
key_ba = g_byte_array_new();
res = hex_str_to_bytes(input_string, key_ba, FALSE);
/* Two tokens means that the user should have entered a WPA-BIN key ... */
if(!res || ((key_ba->len) != WPA_PSK_KEY_SIZE))
{
g_byte_array_free(key_ba, TRUE);
/* No ssid has been created ... */
return NULL;
}
/* Key was correct!!! Create the new decryption_key_t ... */
dk = (decryption_key_t*)g_malloc(sizeof(decryption_key_t));
dk->type = AIRPDCAP_KEY_TYPE_WPA_PSK;
dk->key = g_string_new(input_string);
dk->bits = (guint) dk->key->len * 4;
dk->ssid = NULL;
g_byte_array_free(key_ba, TRUE);
return dk;
}
/* Type not supported */
return NULL;
}
void
free_key_string(decryption_key_t *dk)
{
if (dk->key)
g_string_free(dk->key, TRUE);
if (dk->ssid)
g_byte_array_free(dk->ssid, TRUE);
g_free(dk);
}
/*
* Returns a newly allocated string representing the given decryption_key_t
* struct, or NULL if something is wrong...
*/
gchar*
get_key_string(decryption_key_t* dk)
{
gchar* output_string = NULL;
if(dk == NULL || dk->key == NULL)
return NULL;
switch(dk->type) {
case AIRPDCAP_KEY_TYPE_WEP:
output_string = g_strdup(dk->key->str);
break;
case AIRPDCAP_KEY_TYPE_WPA_PWD:
if(dk->ssid == NULL)
output_string = g_strdup(dk->key->str);
else
output_string = g_strdup_printf("%s:%s",
dk->key->str, format_uri(dk->ssid, ":"));
break;
case AIRPDCAP_KEY_TYPE_WPA_PMK:
output_string = g_strdup(dk->key->str);
break;
default:
return NULL;
}
return output_string;
}
static INT
AirPDcapTDLSDeriveKey(
PAIRPDCAP_SEC_ASSOCIATION sa,
const guint8 *data,
guint offset_rsne,
guint offset_fte,
guint offset_timeout,
guint offset_link,
guint8 action)
{
sha256_hmac_context sha_ctx;
aes_cmac_ctx aes_ctx;
const guint8 *snonce, *anonce, *initiator, *responder, *bssid;
guint8 key_input[SHA256_DIGEST_LEN];
guint8 mic[16], iter[2], length[2], seq_num = action + 1;
/* Get key input */
anonce = &data[offset_fte + 20];
snonce = &data[offset_fte + 52];
sha256_starts(&(sha_ctx.ctx));
if (memcmp(anonce, snonce, AIRPDCAP_WPA_NONCE_LEN) < 0) {
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
} else {
sha256_update(&(sha_ctx.ctx), snonce, AIRPDCAP_WPA_NONCE_LEN);
sha256_update(&(sha_ctx.ctx), anonce, AIRPDCAP_WPA_NONCE_LEN);
}
sha256_finish(&(sha_ctx.ctx), key_input);
/* Derive key */
bssid = &data[offset_link + 2];
initiator = &data[offset_link + 8];
responder = &data[offset_link + 14];
sha256_hmac_starts(&sha_ctx, key_input, SHA256_DIGEST_LEN);
iter[0] = 1;
iter[1] = 0;
sha256_hmac_update(&sha_ctx, (const guint8 *)&iter, 2);
sha256_hmac_update(&sha_ctx, "TDLS PMK", 8);
if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) {
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
} else {
sha256_hmac_update(&sha_ctx, responder, AIRPDCAP_MAC_LEN);
sha256_hmac_update(&sha_ctx, initiator, AIRPDCAP_MAC_LEN);
}
sha256_hmac_update(&sha_ctx, bssid, AIRPDCAP_MAC_LEN);
length[0] = 256 & 0xff;
length[1] = (256 >> 8) & 0xff;
sha256_hmac_update(&sha_ctx, (const guint8 *)&length, 2);
sha256_hmac_finish(&sha_ctx, key_input);
/* Check MIC */
aes_cmac_encrypt_starts(&aes_ctx, key_input, 16);
aes_cmac_encrypt_update(&aes_ctx, initiator, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, responder, AIRPDCAP_MAC_LEN);
aes_cmac_encrypt_update(&aes_ctx, &seq_num, 1);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_link], data[offset_link + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_rsne], data[offset_rsne + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_timeout], data[offset_timeout + 1] + 2);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte], 4);
memset(mic, 0, 16);
aes_cmac_encrypt_update(&aes_ctx, mic, 16);
aes_cmac_encrypt_update(&aes_ctx, &data[offset_fte + 20], data[offset_fte + 1] + 2 - 20);
aes_cmac_encrypt_finish(&aes_ctx, mic);
if (memcmp(mic, &data[offset_fte + 4],16)) {
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verification failed", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_UNSUCCESS;
}
memcpy(AIRPDCAP_GET_TK(sa->wpa.ptk), &key_input[16], 16);
memcpy(sa->wpa.nonce, snonce, AIRPDCAP_WPA_NONCE_LEN);
sa->validKey = TRUE;
sa->wpa.key_ver = AIRPDCAP_WPA_KEY_VER_AES_CCMP;
AIRPDCAP_DEBUG_PRINT_LINE("AirPDcapTDLSDeriveKey", "MIC verified", AIRPDCAP_DEBUG_LEVEL_3);
return AIRPDCAP_RET_SUCCESS;
}
#ifdef __cplusplus
}
#endif
/****************************************************************************/
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5106_0 |
crossvul-cpp_data_bad_2675_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved (0x4)", /* 4 */
"Reserved (0x5)", /* 5 */
"Reserved (0x6)", /* 6 */
"Reserved (0x7)", /* 7 */
};
/*
* Frame Control subfields.
*/
#define FC_FRAME_TYPE(fc) ((fc) & 0x7)
#define FC_SECURITY_ENABLED 0x0008
#define FC_FRAME_PENDING 0x0010
#define FC_ACK_REQUEST 0x0020
#define FC_PAN_ID_COMPRESSION 0x0040
#define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3)
#define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3)
#define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3)
#define FC_ADDRESSING_MODE_NONE 0x00
#define FC_ADDRESSING_MODE_RESERVED 0x01
#define FC_ADDRESSING_MODE_SHORT 0x02
#define FC_ADDRESSING_MODE_LONG 0x03
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p + 2)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2675_0 |
crossvul-cpp_data_bad_1835_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M %
% T R R A A NN N SS F O O R R MM MM %
% T RRRR AAAAA N N N SSS FFF O O RRRR M M M %
% T R R A A N NN SS F O O R R M M %
% T R R A A N N SSSSS F OOO R R M M %
% %
% %
% MagickCore Image Transform Methods %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2015 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 "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/distort.h"
#include "MagickCore/draw.h"
#include "MagickCore/effect.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image.h"
#include "MagickCore/memory_.h"
#include "MagickCore/layer.h"
#include "MagickCore/list.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/resource_.h"
#include "MagickCore/resize.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/transform.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A u t o O r i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AutoOrientImage() adjusts an image so that its orientation is suitable for
% viewing (i.e. top-left orientation).
%
% The format of the AutoOrientImage method is:
%
% Image *AutoOrientImage(const Image *image,
% const OrientationType orientation,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: The image.
%
% o orientation: Current image orientation.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *AutoOrientImage(const Image *image,
const OrientationType orientation,ExceptionInfo *exception)
{
Image
*orient_image;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
orient_image=(Image *) NULL;
switch(orientation)
{
case UndefinedOrientation:
case TopLeftOrientation:
default:
{
orient_image=CloneImage(image,0,0,MagickTrue,exception);
break;
}
case TopRightOrientation:
{
orient_image=FlopImage(image,exception);
break;
}
case BottomRightOrientation:
{
orient_image=RotateImage(image,180.0,exception);
break;
}
case BottomLeftOrientation:
{
orient_image=FlipImage(image,exception);
break;
}
case LeftTopOrientation:
{
orient_image=TransposeImage(image,exception);
break;
}
case RightTopOrientation:
{
orient_image=RotateImage(image,90.0,exception);
break;
}
case RightBottomOrientation:
{
orient_image=TransverseImage(image,exception);
break;
}
case LeftBottomOrientation:
{
orient_image=RotateImage(image,270.0,exception);
break;
}
}
if (orient_image != (Image *) NULL)
orient_image->orientation=TopLeftOrientation;
return(orient_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C h o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ChopImage() removes a region of an image and collapses the image to occupy
% the removed portion.
%
% The format of the ChopImage method is:
%
% Image *ChopImage(const Image *image,const RectangleInfo *chop_info)
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o chop_info: Define the region of the image to chop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info,
ExceptionInfo *exception)
{
#define ChopImageTag "Chop/Image"
CacheView
*chop_view,
*image_view;
Image
*chop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
extent;
ssize_t
y;
/*
Check chop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
assert(chop_info != (RectangleInfo *) NULL);
if (((chop_info->x+(ssize_t) chop_info->width) < 0) ||
((chop_info->y+(ssize_t) chop_info->height) < 0) ||
(chop_info->x > (ssize_t) image->columns) ||
(chop_info->y > (ssize_t) image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
extent=(*chop_info);
if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns)
extent.width=(size_t) ((ssize_t) image->columns-extent.x);
if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows)
extent.height=(size_t) ((ssize_t) image->rows-extent.y);
if (extent.x < 0)
{
extent.width-=(size_t) (-extent.x);
extent.x=0;
}
if (extent.y < 0)
{
extent.height-=(size_t) (-extent.y);
extent.y=0;
}
chop_image=CloneImage(image,image->columns-extent.width,image->rows-
extent.height,MagickTrue,exception);
if (chop_image == (Image *) NULL)
return((Image *) NULL);
/*
Extract chop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
chop_view=AcquireAuthenticCacheView(chop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,chop_image,1,1)
#endif
for (y=0; y < (ssize_t) extent.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(chop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(chop_image,channel,p[i],q);
}
q+=GetPixelChannels(chop_image);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
/*
Extract chop image.
*/
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,chop_image,1,1)
#endif
for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns,
1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width)))
{
register ssize_t
i;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(chop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(chop_image,channel,p[i],q);
}
q+=GetPixelChannels(chop_image);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ChopImage)
#endif
proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
chop_view=DestroyCacheView(chop_view);
image_view=DestroyCacheView(image_view);
chop_image->type=image->type;
if (status == MagickFalse)
chop_image=DestroyImage(chop_image);
return(chop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n s o l i d a t e C M Y K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a
% single image.
%
% The format of the ConsolidateCMYKImage method is:
%
% Image *ConsolidateCMYKImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image sequence.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ConsolidateCMYKImages(const Image *images,
ExceptionInfo *exception)
{
CacheView
*cmyk_view,
*image_view;
Image
*cmyk_image,
*cmyk_images;
register ssize_t
j;
ssize_t
y;
/*
Consolidate separate C, M, Y, and K planes into a single image.
*/
assert(images != (Image *) NULL);
assert(images->signature == MagickCoreSignature);
if (images->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
cmyk_images=NewImageList();
for (j=0; j < (ssize_t) GetImageListLength(images); j+=4)
{
register ssize_t
i;
assert(images != (Image *) NULL);
cmyk_image=CloneImage(images,images->columns,images->rows,MagickTrue,
exception);
if (cmyk_image == (Image *) NULL)
break;
if (SetImageStorageClass(cmyk_image,DirectClass,exception) == MagickFalse)
break;
(void) SetImageColorspace(cmyk_image,CMYKColorspace,exception);
for (i=0; i < 4; i++)
{
image_view=AcquireVirtualCacheView(images,exception);
cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception);
for (y=0; y < (ssize_t) images->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception);
q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for (x=0; x < (ssize_t) images->columns; x++)
{
Quantum
pixel;
pixel=QuantumRange-GetPixelIntensity(images,p);
switch (i)
{
case 0: SetPixelCyan(cmyk_image,pixel,q); break;
case 1: SetPixelMagenta(cmyk_image,pixel,q); break;
case 2: SetPixelYellow(cmyk_image,pixel,q); break;
case 3: SetPixelBlack(cmyk_image,pixel,q); break;
default: break;
}
p+=GetPixelChannels(images);
q+=GetPixelChannels(cmyk_image);
}
if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse)
break;
}
cmyk_view=DestroyCacheView(cmyk_view);
image_view=DestroyCacheView(image_view);
images=GetNextImageInList(images);
if (images == (Image *) NULL)
break;
}
AppendImageToList(&cmyk_images,cmyk_image);
}
return(cmyk_images);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImage() extracts a region of the image starting at the offset defined
% by geometry. Region must be fully defined, and no special handling of
% geometry flags is performed.
%
% The format of the CropImage method is:
%
% Image *CropImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to crop with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry,
ExceptionInfo *exception)
{
#define CropImageTag "Crop/Image"
CacheView
*crop_view,
*image_view;
Image
*crop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
OffsetInfo
offset;
RectangleInfo
bounding_box,
page;
ssize_t
y;
/*
Check crop geometry.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
bounding_box=image->page;
if ((bounding_box.width == 0) || (bounding_box.height == 0))
{
bounding_box.width=image->columns;
bounding_box.height=image->rows;
}
page=(*geometry);
if (page.width == 0)
page.width=bounding_box.width;
if (page.height == 0)
page.height=bounding_box.height;
if (((bounding_box.x-page.x) >= (ssize_t) page.width) ||
((bounding_box.y-page.y) >= (ssize_t) page.height) ||
((page.x-bounding_box.x) > (ssize_t) image->columns) ||
((page.y-bounding_box.y) > (ssize_t) image->rows))
{
/*
Crop is not within virtual canvas, return 1 pixel transparent image.
*/
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.alpha=(Quantum) TransparentAlpha;
crop_image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(crop_image,exception);
crop_image->page=bounding_box;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
if (crop_image->dispose == BackgroundDispose)
crop_image->dispose=NoneDispose;
return(crop_image);
}
if ((page.x < 0) && (bounding_box.x >= 0))
{
page.width+=page.x-bounding_box.x;
page.x=0;
}
else
{
page.width-=bounding_box.x-page.x;
page.x-=bounding_box.x;
if (page.x < 0)
page.x=0;
}
if ((page.y < 0) && (bounding_box.y >= 0))
{
page.height+=page.y-bounding_box.y;
page.y=0;
}
else
{
page.height-=bounding_box.y-page.y;
page.y-=bounding_box.y;
if (page.y < 0)
page.y=0;
}
if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns)
page.width=image->columns-page.x;
if ((geometry->width != 0) && (page.width > geometry->width))
page.width=geometry->width;
if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows)
page.height=image->rows-page.y;
if ((geometry->height != 0) && (page.height > geometry->height))
page.height=geometry->height;
bounding_box.x+=page.x;
bounding_box.y+=page.y;
if ((page.width == 0) || (page.height == 0))
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionWarning,
"GeometryDoesNotContainImage","`%s'",image->filename);
return((Image *) NULL);
}
/*
Initialize crop image attributes.
*/
crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->page.width=image->page.width;
crop_image->page.height=image->page.height;
offset.x=(ssize_t) (bounding_box.x+bounding_box.width);
offset.y=(ssize_t) (bounding_box.y+bounding_box.height);
if ((offset.x > (ssize_t) image->page.width) ||
(offset.y > (ssize_t) image->page.height))
{
crop_image->page.width=bounding_box.width;
crop_image->page.height=bounding_box.height;
}
crop_image->page.x=bounding_box.x;
crop_image->page.y=bounding_box.y;
/*
Crop image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
crop_view=AcquireAuthenticCacheView(crop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,crop_image,1,1)
#endif
for (y=0; y < (ssize_t) crop_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,page.x,page.y+y,crop_image->columns,
1,exception);
q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) crop_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(crop_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(crop_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait crop_traits=GetPixelChannelTraits(crop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(crop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(crop_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(crop_image);
}
if (SyncCacheViewAuthenticPixels(crop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_CropImage)
#endif
proceed=SetImageProgress(image,CropImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
crop_view=DestroyCacheView(crop_view);
image_view=DestroyCacheView(image_view);
crop_image->type=image->type;
if (status == MagickFalse)
crop_image=DestroyImage(crop_image);
return(crop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C r o p I m a g e T o T i l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CropImageToTiles() crops a single image, into a possible list of tiles.
% This may include a single sub-region of the image. This basically applies
% all the normal geometry flags for Crop.
%
% Image *CropImageToTiles(const Image *image,
% const RectangleInfo *crop_geometry, ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double MagickRound(double x)
{
/*
Round the fraction to nearest integer.
*/
if ((x-floor(x)) < (ceil(x)-x))
return(floor(x));
return(ceil(x));
}
MagickExport Image *CropImageToTiles(const Image *image,
const char *crop_geometry,ExceptionInfo *exception)
{
Image
*next,
*crop_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
crop_image=NewImageList();
next=NewImageList();
flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception);
if ((flags & AreaValue) != 0)
{
PointInfo
delta,
offset;
RectangleInfo
crop;
size_t
height,
width;
/*
Crop into NxM tiles (@ flag).
*/
width=image->columns;
height=image->rows;
if (geometry.width == 0)
geometry.width=1;
if (geometry.height == 0)
geometry.height=1;
if ((flags & AspectValue) == 0)
{
width-=(geometry.x < 0 ? -1 : 1)*geometry.x;
height-=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
else
{
width+=(geometry.x < 0 ? -1 : 1)*geometry.x;
height+=(geometry.y < 0 ? -1 : 1)*geometry.y;
}
delta.x=(double) width/geometry.width;
delta.y=(double) height/geometry.height;
if (delta.x < 1.0)
delta.x=1.0;
if (delta.y < 1.0)
delta.y=1.0;
for (offset.y=0; offset.y < (double) height; )
{
if ((flags & AspectValue) == 0)
{
crop.y=(ssize_t) MagickRound((double) (offset.y-
(geometry.y > 0 ? 0 : geometry.y)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((double) (offset.y+
(geometry.y < 0 ? 0 : geometry.y)));
}
else
{
crop.y=(ssize_t) MagickRound((double) (offset.y-
(geometry.y > 0 ? geometry.y : 0)));
offset.y+=delta.y; /* increment now to find width */
crop.height=(size_t) MagickRound((double)
(offset.y+(geometry.y < -1 ? geometry.y : 0)));
}
crop.height-=crop.y;
crop.y+=image->page.y;
for (offset.x=0; offset.x < (double) width; )
{
if ((flags & AspectValue) == 0)
{
crop.x=(ssize_t) MagickRound((double) (offset.x-
(geometry.x > 0 ? 0 : geometry.x)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((double) (offset.x+
(geometry.x < 0 ? 0 : geometry.x)));
}
else
{
crop.x=(ssize_t) MagickRound((double) (offset.x-
(geometry.x > 0 ? geometry.x : 0)));
offset.x+=delta.x; /* increment now to find height */
crop.width=(size_t) MagickRound((double) (offset.x+
(geometry.x < 0 ? geometry.x : 0)));
}
crop.width-=crop.x;
crop.x+=image->page.x;
next=CropImage(image,&crop,exception);
if (next != (Image *) NULL)
AppendImageToList(&crop_image,next);
}
}
ClearMagickException(exception);
return(crop_image);
}
if (((geometry.width == 0) && (geometry.height == 0)) ||
((flags & XValue) != 0) || ((flags & YValue) != 0))
{
/*
Crop a single region at +X+Y.
*/
crop_image=CropImage(image,&geometry,exception);
if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0))
{
crop_image->page.width=geometry.width;
crop_image->page.height=geometry.height;
crop_image->page.x-=geometry.x;
crop_image->page.y-=geometry.y;
}
return(crop_image);
}
if ((image->columns > geometry.width) || (image->rows > geometry.height))
{
RectangleInfo
page;
size_t
height,
width;
ssize_t
x,
y;
/*
Crop into tiles of fixed size WxH.
*/
page=image->page;
if (page.width == 0)
page.width=image->columns;
if (page.height == 0)
page.height=image->rows;
width=geometry.width;
if (width == 0)
width=page.width;
height=geometry.height;
if (height == 0)
height=page.height;
next=NewImageList();
for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height)
{
for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width)
{
geometry.width=width;
geometry.height=height;
geometry.x=x;
geometry.y=y;
next=CropImage(image,&geometry,exception);
if (next == (Image *) NULL)
break;
AppendImageToList(&crop_image,next);
}
if (next == (Image *) NULL)
break;
}
return(crop_image);
}
return(CloneImage(image,0,0,MagickTrue,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x c e r p t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExcerptImage() returns a excerpt of the image as defined by the geometry.
%
% The format of the ExcerptImage method is:
%
% Image *ExcerptImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExcerptImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define ExcerptImageTag "Excerpt/Image"
CacheView
*excerpt_view,
*image_view;
Image
*excerpt_image;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Allocate excerpt image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (excerpt_image == (Image *) NULL)
return((Image *) NULL);
/*
Excerpt each row.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,excerpt_image,excerpt_image->rows,1)
#endif
for (y=0; y < (ssize_t) excerpt_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,geometry->x,geometry->y+y,
geometry->width,1,exception);
q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) excerpt_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(excerpt_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(excerpt_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait excerpt_traits=GetPixelChannelTraits(excerpt_image,channel);
if ((traits == UndefinedPixelTrait) ||
(excerpt_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(excerpt_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(excerpt_image);
}
if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_ExcerptImage)
#endif
proceed=SetImageProgress(image,ExcerptImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
excerpt_view=DestroyCacheView(excerpt_view);
image_view=DestroyCacheView(image_view);
excerpt_image->type=image->type;
if (status == MagickFalse)
excerpt_image=DestroyImage(excerpt_image);
return(excerpt_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x t e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExtentImage() extends the image as defined by the geometry, gravity, and
% image background color. Set the (x,y) offset of the geometry to move the
% original image relative to the extended image.
%
% The format of the ExtentImage method is:
%
% Image *ExtentImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to extend with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ExtentImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
Image
*extent_image;
/*
Allocate extent image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
if ((image->columns == geometry->width) &&
(image->rows == geometry->height) &&
(geometry->x == 0) && (geometry->y == 0))
return(CloneImage(image,0,0,MagickTrue,exception));
extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue,
exception);
if (extent_image == (Image *) NULL)
return((Image *) NULL);
(void) SetImageBackgroundColor(extent_image,exception);
(void) CompositeImage(extent_image,image,image->compose,MagickTrue,
-geometry->x,-geometry->y,exception);
return(extent_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l i p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlipImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis.
%
% The format of the FlipImage method is:
%
% Image *FlipImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FlipImage(const Image *image,ExceptionInfo *exception)
{
#define FlipImageTag "Flip/Image"
CacheView
*flip_view,
*image_view;
Image
*flip_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
flip_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (flip_image == (Image *) NULL)
return((Image *) NULL);
/*
Flip image.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flip_view=AcquireAuthenticCacheView(flip_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,flip_image,1,1)
#endif
for (y=0; y < (ssize_t) flip_image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y-
1),flip_image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) flip_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(flip_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(flip_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait flip_traits=GetPixelChannelTraits(flip_image,channel);
if ((traits == UndefinedPixelTrait) ||
(flip_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(flip_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(flip_image);
}
if (SyncCacheViewAuthenticPixels(flip_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FlipImage)
#endif
proceed=SetImageProgress(image,FlipImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flip_view=DestroyCacheView(flip_view);
image_view=DestroyCacheView(image_view);
flip_image->type=image->type;
if (page.height != 0)
page.y=(ssize_t) (page.height-flip_image->rows-page.y);
flip_image->page=page;
if (status == MagickFalse)
flip_image=DestroyImage(flip_image);
return(flip_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o p I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FlopImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis.
%
% The format of the FlopImage method is:
%
% Image *FlopImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *FlopImage(const Image *image,ExceptionInfo *exception)
{
#define FlopImageTag "Flop/Image"
CacheView
*flop_view,
*image_view;
Image
*flop_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
flop_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (flop_image == (Image *) NULL)
return((Image *) NULL);
/*
Flop each row.
*/
status=MagickTrue;
progress=0;
page=image->page;
image_view=AcquireVirtualCacheView(image,exception);
flop_view=AcquireAuthenticCacheView(flop_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(image,flop_image,1,1)
#endif
for (y=0; y < (ssize_t) flop_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
q+=GetPixelChannels(flop_image)*flop_image->columns;
for (x=0; x < (ssize_t) flop_image->columns; x++)
{
register ssize_t
i;
q-=GetPixelChannels(flop_image);
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait flop_traits=GetPixelChannelTraits(flop_image,channel);
if ((traits == UndefinedPixelTrait) ||
(flop_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(flop_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(flop_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FlopImage)
#endif
proceed=SetImageProgress(image,FlopImageTag,progress++,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
flop_view=DestroyCacheView(flop_view);
image_view=DestroyCacheView(image_view);
flop_image->type=image->type;
if (page.width != 0)
page.x=(ssize_t) (page.width-flop_image->columns-page.x);
flop_image->page=page;
if (status == MagickFalse)
flop_image=DestroyImage(flop_image);
return(flop_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R o l l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RollImage() offsets an image as defined by x_offset and y_offset.
%
% The format of the RollImage method is:
%
% Image *RollImage(const Image *image,const ssize_t x_offset,
% const ssize_t y_offset,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x_offset: the number of columns to roll in the horizontal direction.
%
% o y_offset: the number of rows to roll in the vertical direction.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy,
const ssize_t dx,const ssize_t dy,ExceptionInfo *exception)
{
CacheView
*source_view,
*destination_view;
MagickBooleanType
status;
ssize_t
y;
if (columns == 0)
return(MagickTrue);
status=MagickTrue;
source_view=AcquireVirtualCacheView(source,exception);
destination_view=AcquireAuthenticCacheView(destination,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(status) \
magick_threads(source,destination,rows,1)
#endif
for (y=0; y < (ssize_t) rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
/*
Transfer scanline.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception);
q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(source,p) == 0)
{
SetPixelBackgoundColor(destination,q);
p+=GetPixelChannels(source);
q+=GetPixelChannels(destination);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PixelChannel channel=GetPixelChannelChannel(source,i);
PixelTrait source_traits=GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((source_traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(destination,channel,p[i],q);
}
p+=GetPixelChannels(source);
q+=GetPixelChannels(destination);
}
sync=SyncCacheViewAuthenticPixels(destination_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
destination_view=DestroyCacheView(destination_view);
source_view=DestroyCacheView(source_view);
return(status);
}
MagickExport Image *RollImage(const Image *image,const ssize_t x_offset,
const ssize_t y_offset,ExceptionInfo *exception)
{
#define RollImageTag "Roll/Image"
Image
*roll_image;
MagickStatusType
status;
RectangleInfo
offset;
/*
Initialize roll image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
roll_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if (roll_image == (Image *) NULL)
return((Image *) NULL);
offset.x=x_offset;
offset.y=y_offset;
while (offset.x < 0)
offset.x+=(ssize_t) image->columns;
while (offset.x >= (ssize_t) image->columns)
offset.x-=(ssize_t) image->columns;
while (offset.y < 0)
offset.y+=(ssize_t) image->rows;
while (offset.y >= (ssize_t) image->rows)
offset.y-=(ssize_t) image->rows;
/*
Roll image.
*/
status=CopyImageRegion(roll_image,image,(size_t) offset.x,
(size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows-
offset.y,0,0,exception);
(void) SetImageProgress(image,RollImageTag,0,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,
(size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0,
exception);
(void) SetImageProgress(image,RollImageTag,1,3);
status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows-
offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,2,3);
status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows-
offset.y,0,0,offset.x,offset.y,exception);
(void) SetImageProgress(image,RollImageTag,3,3);
roll_image->type=image->type;
if (status == MagickFalse)
roll_image=DestroyImage(roll_image);
return(roll_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S h a v e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ShaveImage() shaves pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the ShaveImage method is:
%
% Image *ShaveImage(const Image *image,const RectangleInfo *shave_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o shave_image: Method ShaveImage returns a pointer to the shaved
% image. A null image is returned if there is a memory shortage or
% if the image width or height is zero.
%
% o image: the image.
%
% o shave_info: Specifies a pointer to a RectangleInfo which defines the
% region of the image to crop.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *ShaveImage(const Image *image,
const RectangleInfo *shave_info,ExceptionInfo *exception)
{
Image
*shave_image;
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (((2*shave_info->width) >= image->columns) ||
((2*shave_info->height) >= image->rows))
ThrowImageException(OptionWarning,"GeometryDoesNotContainImage");
SetGeometry(image,&geometry);
geometry.width-=2*shave_info->width;
geometry.height-=2*shave_info->height;
geometry.x=(ssize_t) shave_info->width+image->page.x;
geometry.y=(ssize_t) shave_info->height+image->page.y;
shave_image=CropImage(image,&geometry,exception);
if (shave_image == (Image *) NULL)
return((Image *) NULL);
shave_image->page.width-=2*shave_info->width;
shave_image->page.height-=2*shave_info->height;
shave_image->page.x-=(ssize_t) shave_info->width;
shave_image->page.y-=(ssize_t) shave_info->height;
return(shave_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S p l i c e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SpliceImage() splices a solid color into the image as defined by the
% geometry.
%
% The format of the SpliceImage method is:
%
% Image *SpliceImage(const Image *image,const RectangleInfo *geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o geometry: Define the region of the image to splice with members
% x, y, width, and height.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *SpliceImage(const Image *image,
const RectangleInfo *geometry,ExceptionInfo *exception)
{
#define SpliceImageTag "Splice/Image"
CacheView
*image_view,
*splice_view;
Image
*splice_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
splice_geometry;
ssize_t
y;
/*
Allocate splice image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(geometry != (const RectangleInfo *) NULL);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
splice_geometry=(*geometry);
splice_image=CloneImage(image,image->columns+splice_geometry.width,
image->rows+splice_geometry.height,MagickTrue,exception);
if (splice_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse)
{
splice_image=DestroyImage(splice_image);
return((Image *) NULL);
}
if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) &&
(IsGrayColorspace(splice_image->colorspace) != MagickFalse))
(void) SetImageColorspace(splice_image,sRGBColorspace,exception);
if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) &&
(splice_image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(splice_image,OpaqueAlpha,exception);
(void) SetImageBackgroundColor(splice_image,exception);
/*
Respect image geometry.
*/
switch (image->gravity)
{
default:
case UndefinedGravity:
case NorthWestGravity:
break;
case NorthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
break;
}
case NorthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
break;
}
case WestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.width/2;
break;
}
case CenterGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case EastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height/2;
break;
}
case SouthWestGravity:
{
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width/2;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
case SouthEastGravity:
{
splice_geometry.x+=(ssize_t) splice_geometry.width;
splice_geometry.y+=(ssize_t) splice_geometry.height;
break;
}
}
/*
Splice image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
splice_view=AcquireAuthenticCacheView(splice_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=0; y < (ssize_t) splice_geometry.y; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < splice_geometry.x; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,p) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,splice_image,1,1)
#endif
for (y=(ssize_t) (splice_geometry.y+splice_geometry.height);
y < (ssize_t) splice_image->rows; y++)
{
register const Quantum
*restrict p;
register ssize_t
x;
register Quantum
*restrict q;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height,
image->columns,1,exception);
if ((y < 0) || (y >= (ssize_t) splice_image->rows))
continue;
q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < splice_geometry.x; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++)
q+=GetPixelChannels(splice_image);
for ( ; x < (ssize_t) splice_image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(splice_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel);
if ((traits == UndefinedPixelTrait) ||
(splice_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(splice_image,channel,p[i],q);
}
SetPixelRed(splice_image,GetPixelRed(image,p),q);
SetPixelGreen(splice_image,GetPixelGreen(image,p),q);
SetPixelBlue(splice_image,GetPixelBlue(image,p),q);
SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(splice_image);
}
if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,SpliceImageTag,progress++,
splice_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
splice_view=DestroyCacheView(splice_view);
image_view=DestroyCacheView(image_view);
if (status == MagickFalse)
splice_image=DestroyImage(splice_image);
return(splice_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImage() is a convenience method that behaves like ResizeImage() or
% CropImage() but accepts scaling and/or cropping information as a region
% geometry specification. If the operation fails, the original image handle
% is left as is.
%
% This should only be used for single images.
%
% This function destroys what it assumes to be a single image list.
% If the input image is part of a larger list, all other images in that list
% will be simply 'lost', not destroyed.
%
% Also if the crop generates a list of images only the first image is resized.
% And finally if the crop succeeds and the resize failed, you will get a
% cropped image, as well as a 'false' or 'failed' report.
%
% This function and should probably be deprecated in favor of direct calls
% to CropImageToTiles() or ResizeImage(), as appropriate.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImage(Image **image,const char *crop_geometry,
% const char *image_geometry,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransformImage(Image **image,
const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception)
{
Image
*resize_image,
*transform_image;
MagickStatusType
flags;
RectangleInfo
geometry;
assert(image != (Image **) NULL);
assert((*image)->signature == MagickCoreSignature);
if ((*image)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename);
transform_image=(*image);
if (crop_geometry != (const char *) NULL)
{
Image
*crop_image;
/*
Crop image to a user specified size.
*/
crop_image=CropImageToTiles(*image,crop_geometry,exception);
if (crop_image == (Image *) NULL)
transform_image=CloneImage(*image,0,0,MagickTrue,exception);
else
{
transform_image=DestroyImage(transform_image);
transform_image=GetFirstImageInList(crop_image);
}
*image=transform_image;
}
if (image_geometry == (const char *) NULL)
return(MagickTrue);
/*
Scale image to a user specified size.
*/
flags=ParseRegionGeometry(transform_image,image_geometry,&geometry,exception);
(void) flags;
if ((transform_image->columns == geometry.width) &&
(transform_image->rows == geometry.height))
return(MagickTrue);
resize_image=ResizeImage(transform_image,geometry.width,geometry.height,
transform_image->filter,exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
transform_image=DestroyImage(transform_image);
transform_image=resize_image;
*image=transform_image;
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s f o r m I m a g e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransformImages() calls TransformImage() on each image of a sequence.
%
% The format of the TransformImage method is:
%
% MagickBooleanType TransformImages(Image **image,
% const char *crop_geometry,const char *image_geometry,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image The transformed image is returned as this parameter.
%
% o crop_geometry: A crop geometry string. This geometry defines a
% subregion of the image to crop.
%
% o image_geometry: An image geometry string. This geometry defines the
% final size of the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransformImages(Image **images,
const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception)
{
Image
*image,
**image_list,
*transform_images;
MagickStatusType
status;
register ssize_t
i;
assert(images != (Image **) NULL);
assert((*images)->signature == MagickCoreSignature);
if ((*images)->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
(*images)->filename);
image_list=ImageListToArray(*images,exception);
if (image_list == (Image **) NULL)
return(MagickFalse);
status=MagickTrue;
transform_images=NewImageList();
for (i=0; image_list[i] != (Image *) NULL; i++)
{
image=image_list[i];
status&=TransformImage(&image,crop_geometry,image_geometry,exception);
AppendImageToList(&transform_images,image);
}
*images=transform_images;
image_list=(Image **) RelinquishMagickMemory(image_list);
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p o s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransposeImage() creates a horizontal mirror image by reflecting the pixels
% around the central y-axis while rotating them by 90 degrees.
%
% The format of the TransposeImage method is:
%
% Image *TransposeImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransposeImage(const Image *image,ExceptionInfo *exception)
{
#define TransposeImageTag "Transpose/Image"
CacheView
*image_view,
*transpose_view;
Image
*transpose_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transpose_image == (Image *) NULL)
return((Image *) NULL);
/*
Transpose image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transpose_view=AcquireAuthenticCacheView(transpose_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,transpose_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,(ssize_t) image->rows-y-1,
image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1),
0,1,transpose_image->rows,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
if (GetPixelReadMask(image,q) == 0)
{
SetPixelBackgoundColor(transpose_image,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(transpose_image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait transpose_traits=GetPixelChannelTraits(transpose_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(transpose_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(transpose_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
q+=GetPixelChannels(transpose_image);
}
if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransposeImage)
#endif
proceed=SetImageProgress(image,TransposeImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transpose_view=DestroyCacheView(transpose_view);
image_view=DestroyCacheView(image_view);
transpose_image->type=image->type;
page=transpose_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
transpose_image->page=page;
if (status == MagickFalse)
transpose_image=DestroyImage(transpose_image);
return(transpose_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s v e r s e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransverseImage() creates a vertical mirror image by reflecting the pixels
% around the central x-axis while rotating them by 270 degrees.
%
% The format of the TransverseImage method is:
%
% Image *TransverseImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TransverseImage(const Image *image,ExceptionInfo *exception)
{
#define TransverseImageTag "Transverse/Image"
CacheView
*image_view,
*transverse_view;
Image
*transverse_image;
MagickBooleanType
status;
MagickOffsetType
progress;
RectangleInfo
page;
ssize_t
y;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue,
exception);
if (transverse_image == (Image *) NULL)
return((Image *) NULL);
/*
Transverse image.
*/
status=MagickTrue;
progress=0;
image_view=AcquireVirtualCacheView(image,exception);
transverse_view=AcquireAuthenticCacheView(transverse_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,transverse_image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
sync;
register const Quantum
*restrict p;
register Quantum
*restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
q=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-1),
0,1,transverse_image->rows,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
q+=GetPixelChannels(transverse_image)*image->columns;
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
q-=GetPixelChannels(transverse_image);
if (GetPixelReadMask(image,p) == 0)
{
p+=GetPixelChannels(image);
continue;
}
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel=GetPixelChannelChannel(image,i);
PixelTrait traits=GetPixelChannelTraits(image,channel);
PixelTrait transverse_traits=GetPixelChannelTraits(transverse_image,
channel);
if ((traits == UndefinedPixelTrait) ||
(transverse_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(transverse_image,channel,p[i],q);
}
p+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(transverse_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransverseImage)
#endif
proceed=SetImageProgress(image,TransverseImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
transverse_view=DestroyCacheView(transverse_view);
image_view=DestroyCacheView(image_view);
transverse_image->type=image->type;
page=transverse_image->page;
Swap(page.width,page.height);
Swap(page.x,page.y);
if (page.width != 0)
page.x=(ssize_t) (page.width-transverse_image->columns-page.x);
if (page.height != 0)
page.y=(ssize_t) (page.height-transverse_image->rows-page.y);
transverse_image->page=page;
if (status == MagickFalse)
transverse_image=DestroyImage(transverse_image);
return(transverse_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r i m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TrimImage() trims pixels from the image edges. It allocates the memory
% necessary for the new Image structure and returns a pointer to the new
% image.
%
% The format of the TrimImage method is:
%
% Image *TrimImage(const Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *TrimImage(const Image *image,ExceptionInfo *exception)
{
RectangleInfo
geometry;
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
geometry=GetImageBoundingBox(image,exception);
if ((geometry.width == 0) || (geometry.height == 0))
{
Image
*crop_image;
crop_image=CloneImage(image,1,1,MagickTrue,exception);
if (crop_image == (Image *) NULL)
return((Image *) NULL);
crop_image->background_color.alpha=(Quantum) TransparentAlpha;
crop_image->alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(crop_image,exception);
crop_image->page=image->page;
crop_image->page.x=(-1);
crop_image->page.y=(-1);
return(crop_image);
}
geometry.x+=image->page.x;
geometry.y+=image->page.y;
return(CropImage(image,&geometry,exception));
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1835_0 |
crossvul-cpp_data_bad_5869_0 | /*
* The two pass scaling function is based on:
* Filtered Image Rescaling
* Based on Gems III
* - Schumacher general filtered image rescaling
* (pp. 414-424)
* by Dale Schumacher
*
* Additional changes by Ray Gardener, Daylon Graphics Ltd.
* December 4, 1999
*
* Ported to libgd by Pierre Joye. Support for multiple channels
* added (argb for now).
*
* Initial sources code is avaibable in the Gems Source Code Packages:
* http://www.acm.org/pubs/tog/GraphicsGems/GGemsIII.tar.gz
*
*/
/*
Summary:
- Horizontal filter contributions are calculated on the fly,
as each column is mapped from src to dst image. This lets
us omit having to allocate a temporary full horizontal stretch
of the src image.
- If none of the src pixels within a sampling region differ,
then the output pixel is forced to equal (any of) the source pixel.
This ensures that filters do not corrupt areas of constant color.
- Filter weight contribution results, after summing, are
rounded to the nearest pixel color value instead of
being casted to ILubyte (usually an int or char). Otherwise,
artifacting occurs.
*/
/*
Additional functions are available for simple rotation or up/downscaling.
downscaling using the fixed point implementations are usually much faster
than the existing gdImageCopyResampled while having a similar or better
quality.
For image rotations, the optimized versions have a lazy antialiasing for
the edges of the images. For a much better antialiased result, the affine
function is recommended.
*/
/*
TODO:
- Optimize pixel accesses and loops once we have continuous buffer
- Add scale support for a portion only of an image (equivalent of copyresized/resampled)
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "gd.h"
#include "gdhelpers.h"
#ifdef _MSC_VER
# pragma optimize("t", on)
# include <emmintrin.h>
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c)))
#ifndef MAX
#define MAX(a,b) ((a)<(b)?(b):(a))
#endif
#define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c)))
#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
/* only used here, let do a generic fixed point integers later if required by other
part of GD */
typedef long gdFixed;
/* Integer to fixed point */
#define gd_itofx(x) ((x) << 8)
/* Float to fixed point */
#define gd_ftofx(x) (long)((x) * 256)
/* Double to fixed point */
#define gd_dtofx(x) (long)((x) * 256)
/* Fixed point to integer */
#define gd_fxtoi(x) ((x) >> 8)
/* Fixed point to float */
# define gd_fxtof(x) ((float)(x) / 256)
/* Fixed point to double */
#define gd_fxtod(x) ((double)(x) / 256)
/* Multiply a fixed by a fixed */
#define gd_mulfx(x,y) (((x) * (y)) >> 8)
/* Divide a fixed by a fixed */
#define gd_divfx(x,y) (((x) << 8) / (y))
typedef struct
{
double *Weights; /* Normalized weights of neighboring pixels */
int Left,Right; /* Bounds of source pixels window */
} ContributionType; /* Contirbution information for a single pixel */
typedef struct
{
ContributionType *ContribRow; /* Row (or column) of contribution weights */
unsigned int WindowSize, /* Filter window size (of affecting source pixels) */
LineLength; /* Length of line (no. or rows / cols) */
} LineContribType;
/* Each core filter has its own radius */
#define DEFAULT_FILTER_BICUBIC 3.0
#define DEFAULT_FILTER_BOX 0.5
#define DEFAULT_FILTER_GENERALIZED_CUBIC 0.5
#define DEFAULT_FILTER_RADIUS 1.0
#define DEFAULT_LANCZOS8_RADIUS 8.0
#define DEFAULT_LANCZOS3_RADIUS 3.0
#define DEFAULT_HERMITE_RADIUS 1.0
#define DEFAULT_BOX_RADIUS 0.5
#define DEFAULT_TRIANGLE_RADIUS 1.0
#define DEFAULT_BELL_RADIUS 1.5
#define DEFAULT_CUBICSPLINE_RADIUS 2.0
#define DEFAULT_MITCHELL_RADIUS 2.0
#define DEFAULT_COSINE_RADIUS 1.0
#define DEFAULT_CATMULLROM_RADIUS 2.0
#define DEFAULT_QUADRATIC_RADIUS 1.5
#define DEFAULT_QUADRATICBSPLINE_RADIUS 1.5
#define DEFAULT_CUBICCONVOLUTION_RADIUS 3.0
#define DEFAULT_GAUSSIAN_RADIUS 1.0
#define DEFAULT_HANNING_RADIUS 1.0
#define DEFAULT_HAMMING_RADIUS 1.0
#define DEFAULT_SINC_RADIUS 1.0
#define DEFAULT_WELSH_RADIUS 1.0
enum GD_RESIZE_FILTER_TYPE{
FILTER_DEFAULT = 0,
FILTER_BELL,
FILTER_BESSEL,
FILTER_BLACKMAN,
FILTER_BOX,
FILTER_BSPLINE,
FILTER_CATMULLROM,
FILTER_COSINE,
FILTER_CUBICCONVOLUTION,
FILTER_CUBICSPLINE,
FILTER_HERMITE,
FILTER_LANCZOS3,
FILTER_LANCZOS8,
FILTER_MITCHELL,
FILTER_QUADRATIC,
FILTER_QUADRATICBSPLINE,
FILTER_TRIANGLE,
FILTER_GAUSSIAN,
FILTER_HANNING,
FILTER_HAMMING,
FILTER_SINC,
FILTER_WELSH,
FILTER_CALLBACK = 999
};
typedef enum GD_RESIZE_FILTER_TYPE gdResizeFilterType;
static double KernelBessel_J1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p = Pone[8];
q = Qone[8];
for (i=7; i >= 0; i--)
{
p = p*x*x+Pone[i];
q = q*x*x+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_P1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Q1(const double x)
{
double p, q;
register long i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p = Pone[5];
q = Qone[5];
for (i=4; i >= 0; i--)
{
p = p*(8.0/x)*(8.0/x)+Pone[i];
q = q*(8.0/x)*(8.0/x)+Qone[i];
}
return (double)(p/q);
}
static double KernelBessel_Order1(double x)
{
double p, q;
if (x == 0.0)
return (0.0f);
p = x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return (p*KernelBessel_J1(x));
q = (double)sqrt(2.0f/(M_PI*x))*(double)(KernelBessel_P1(x)*(1.0f/sqrt(2.0f)*(sin(x)-cos(x)))-8.0f/x*KernelBessel_Q1(x)*
(-1.0f/sqrt(2.0f)*(sin(x)+cos(x))));
if (p < 0.0f)
q = (-q);
return (q);
}
static double filter_bessel(const double x)
{
if (x == 0.0f)
return (double)(M_PI/4.0f);
return (KernelBessel_Order1((double)M_PI*x)/(2.0f*x));
}
static double filter_blackman(const double x)
{
return (0.42f+0.5f*(double)cos(M_PI*x)+0.08f*(double)cos(2.0f*M_PI*x));
}
/**
* Bicubic interpolation kernel (a=-1):
\verbatim
/
| 1-2|t|**2+|t|**3 , if |t| < 1
h(t) = | 4-8|t|+5|t|**2-|t|**3 , if 1<=|t|<2
| 0 , otherwise
\
\endverbatim
* ***bd*** 2.2004
*/
static double filter_bicubic(const double t)
{
const double abs_t = (double)fabs(t);
const double abs_t_sq = abs_t * abs_t;
if (abs_t<1) return 1-2*abs_t_sq+abs_t_sq*abs_t;
if (abs_t<2) return 4 - 8*abs_t +5*abs_t_sq - abs_t_sq*abs_t;
return 0;
}
/**
* Generalized cubic kernel (for a=-1 it is the same as BicubicKernel):
\verbatim
/
| (a+2)|t|**3 - (a+3)|t|**2 + 1 , |t| <= 1
h(t) = | a|t|**3 - 5a|t|**2 + 8a|t| - 4a , 1 < |t| <= 2
| 0 , otherwise
\
\endverbatim
* Often used values for a are -1 and -1/2.
*/
static double filter_generalized_cubic(const double t)
{
const double a = -DEFAULT_FILTER_GENERALIZED_CUBIC;
double abs_t = (double)fabs(t);
double abs_t_sq = abs_t * abs_t;
if (abs_t < 1) return (a + 2) * abs_t_sq * abs_t - (a + 3) * abs_t_sq + 1;
if (abs_t < 2) return a * abs_t_sq * abs_t - 5 * a * abs_t_sq + 8 * a * abs_t - 4 * a;
return 0;
}
#ifdef FUNCTION_NOT_USED_YET
/* CubicSpline filter, default radius 2 */
static double filter_cubic_spline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0 ) {
const double x2 = x*x;
return (0.5 * x2 * x - x2 + 2.0 / 3.0);
}
if (x < 2.0) {
return (pow(2.0 - x, 3.0)/6.0);
}
return 0;
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* CubicConvolution filter, default radius 3 */
static double filter_cubic_convolution(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
const double x2 = x1 * x1;
const double x2_x = x2 * x;
if (x <= 1.0) return ((4.0 / 3.0)* x2_x - (7.0 / 3.0) * x2 + 1.0);
if (x <= 2.0) return (- (7.0 / 12.0) * x2_x + 3 * x2 - (59.0 / 12.0) * x + 2.5);
if (x <= 3.0) return ( (1.0/12.0) * x2_x - (2.0 / 3.0) * x2 + 1.75 * x - 1.5);
return 0;
}
#endif
static double filter_box(double x) {
if (x < - DEFAULT_FILTER_BOX)
return 0.0f;
if (x < DEFAULT_FILTER_BOX)
return 1.0f;
return 0.0f;
}
static double filter_catmullrom(const double x)
{
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(0.5f*(4.0f+x*(8.0f+x*(5.0f+x))));
if (x < 0.0)
return(0.5f*(2.0f+x*x*(-5.0f-3.0f*x)));
if (x < 1.0)
return(0.5f*(2.0f+x*x*(-5.0f+3.0f*x)));
if (x < 2.0)
return(0.5f*(4.0f+x*(-8.0f+x*(5.0f-x))));
return(0.0f);
}
#ifdef FUNCTION_NOT_USED_YET
static double filter_filter(double t)
{
/* f(t) = 2|t|^3 - 3|t|^2 + 1, -1 <= t <= 1 */
if(t < 0.0) t = -t;
if(t < 1.0) return((2.0 * t - 3.0) * t * t + 1.0);
return(0.0);
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* Lanczos8 filter, default radius 8 */
static double filter_lanczos8(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS8_RADIUS
if ( x == 0.0) return 1;
if ( x < R) {
return R * sin(x*M_PI) * sin(x * M_PI/ R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
#endif
#ifdef FUNCTION_NOT_USED_YET
/* Lanczos3 filter, default radius 3 */
static double filter_lanczos3(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
#define R DEFAULT_LANCZOS3_RADIUS
if ( x == 0.0) return 1;
if ( x < R)
{
return R * sin(x*M_PI) * sin(x * M_PI / R) / (x * M_PI * x * M_PI);
}
return 0.0;
#undef R
}
#endif
/* Hermite filter, default radius 1 */
static double filter_hermite(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return ((2.0 * x - 3) * x * x + 1.0 );
return 0.0;
}
/* Trangle filter, default radius 1 */
static double filter_triangle(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 1.0) return (1.0 - x);
return 0.0;
}
/* Bell filter, default radius 1.5 */
static double filter_bell(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x < 0.5) return (0.75 - x*x);
if (x < 1.5) return (0.5 * pow(x - 1.5, 2.0));
return 0.0;
}
/* Mitchell filter, default radius 2.0 */
static double filter_mitchell(const double x)
{
#define KM_B (1.0f/3.0f)
#define KM_C (1.0f/3.0f)
#define KM_P0 (( 6.0f - 2.0f * KM_B ) / 6.0f)
#define KM_P2 ((-18.0f + 12.0f * KM_B + 6.0f * KM_C) / 6.0f)
#define KM_P3 (( 12.0f - 9.0f * KM_B - 6.0f * KM_C) / 6.0f)
#define KM_Q0 (( 8.0f * KM_B + 24.0f * KM_C) / 6.0f)
#define KM_Q1 ((-12.0f * KM_B - 48.0f * KM_C) / 6.0f)
#define KM_Q2 (( 6.0f * KM_B + 30.0f * KM_C) / 6.0f)
#define KM_Q3 (( -1.0f * KM_B - 6.0f * KM_C) / 6.0f)
if (x < -2.0)
return(0.0f);
if (x < -1.0)
return(KM_Q0-x*(KM_Q1-x*(KM_Q2-x*KM_Q3)));
if (x < 0.0f)
return(KM_P0+x*x*(KM_P2-x*KM_P3));
if (x < 1.0f)
return(KM_P0+x*x*(KM_P2+x*KM_P3));
if (x < 2.0f)
return(KM_Q0+x*(KM_Q1+x*(KM_Q2+x*KM_Q3)));
return(0.0f);
}
#ifdef FUNCTION_NOT_USED_YET
/* Cosine filter, default radius 1 */
static double filter_cosine(const double x)
{
if ((x >= -1.0) && (x <= 1.0)) return ((cos(x * M_PI) + 1.0)/2.0);
return 0;
}
#endif
/* Quadratic filter, default radius 1.5 */
static double filter_quadratic(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- 2.0 * x * x + 1);
if (x <= 1.5) return (x * x - 2.5* x + 1.5);
return 0.0;
}
static double filter_bspline(const double x)
{
if (x>2.0f) {
return 0.0f;
} else {
double a, b, c, d;
/* Was calculated anyway cause the "if((x-1.0f) < 0)" */
const double xm1 = x - 1.0f;
const double xp1 = x + 1.0f;
const double xp2 = x + 2.0f;
if ((xp2) <= 0.0f) a = 0.0f; else a = xp2*xp2*xp2;
if ((xp1) <= 0.0f) b = 0.0f; else b = xp1*xp1*xp1;
if (x <= 0) c = 0.0f; else c = x*x*x;
if ((xm1) <= 0.0f) d = 0.0f; else d = xm1*xm1*xm1;
return (0.16666666666666666667f * (a - (4.0f * b) + (6.0f * c) - (4.0f * d)));
}
}
#ifdef FUNCTION_NOT_USED_YET
/* QuadraticBSpline filter, default radius 1.5 */
static double filter_quadratic_bspline(const double x1)
{
const double x = x1 < 0.0 ? -x1 : x1;
if (x <= 0.5) return (- x * x + 0.75);
if (x <= 1.5) return (0.5 * x * x - 1.5 * x + 1.125);
return 0.0;
}
#endif
static double filter_gaussian(const double x)
{
/* return(exp((double) (-2.0 * x * x)) * sqrt(2.0 / M_PI)); */
return (double)(exp(-2.0f * x * x) * 0.79788456080287f);
}
static double filter_hanning(const double x)
{
/* A Cosine windowing function */
return(0.5 + 0.5 * cos(M_PI * x));
}
static double filter_hamming(const double x)
{
/* should be
(0.54+0.46*cos(M_PI*(double) x));
but this approximation is sufficient */
if (x < -1.0f)
return 0.0f;
if (x < 0.0f)
return 0.92f*(-2.0f*x-3.0f)*x*x+1.0f;
if (x < 1.0f)
return 0.92f*(2.0f*x-3.0f)*x*x+1.0f;
return 0.0f;
}
static double filter_power(const double x)
{
const double a = 2.0f;
if (fabs(x)>1) return 0.0f;
return (1.0f - (double)fabs(pow(x,a)));
}
static double filter_sinc(const double x)
{
/* X-scaled Sinc(x) function. */
if (x == 0.0) return(1.0);
return (sin(M_PI * (double) x) / (M_PI * (double) x));
}
#ifdef FUNCTION_NOT_USED_YET
static double filter_welsh(const double x)
{
/* Welsh parabolic windowing filter */
if (x < 1.0)
return(1 - x*x);
return(0.0);
}
#endif
#if defined(_MSC_VER) && !defined(inline)
# define inline __inline
#endif
/* Copied from upstream's libgd */
static inline int _color_blend (const int dst, const int src)
{
const int src_alpha = gdTrueColorGetAlpha(src);
if( src_alpha == gdAlphaOpaque ) {
return src;
} else {
const int dst_alpha = gdTrueColorGetAlpha(dst);
if( src_alpha == gdAlphaTransparent ) return dst;
if( dst_alpha == gdAlphaTransparent ) {
return src;
} else {
register int alpha, red, green, blue;
const int src_weight = gdAlphaTransparent - src_alpha;
const int dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax;
const int tot_weight = src_weight + dst_weight;
alpha = src_alpha * dst_alpha / gdAlphaMax;
red = (gdTrueColorGetRed(src) * src_weight
+ gdTrueColorGetRed(dst) * dst_weight) / tot_weight;
green = (gdTrueColorGetGreen(src) * src_weight
+ gdTrueColorGetGreen(dst) * dst_weight) / tot_weight;
blue = (gdTrueColorGetBlue(src) * src_weight
+ gdTrueColorGetBlue(dst) * dst_weight) / tot_weight;
return ((alpha << 24) + (red << 16) + (green << 8) + blue);
}
}
}
static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor)
{
const gdFixed f_127 = gd_itofx(127);
register int c = src->tpixels[y][x];
c = c | (( (int) (gd_fxtof(gd_mulfx(coverage, f_127)) + 50.5f)) << 24);
return _color_blend(bgColor, c);
}
static inline int getPixelOverflowTC(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
#define colorIndex2RGBA(c) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(c)])
#define colorIndex2RGBcustomA(c, a) gdTrueColorAlpha(im->red[(c)], im->green[(c)], im->blue[(c)], im->alpha[(a)])
static inline int getPixelOverflowPalette(gdImagePtr im, const int x, const int y, const int bgColor)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->pixels[y][x];
if (c == im->transparent) {
return bgColor == -1 ? gdTrueColorAlpha(0, 0, 0, 127) : bgColor;
}
return colorIndex2RGBA(c);
} else {
register int border = 0;
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y < im->cy1) {
border = gdImageGetPixel(im, im->cx1, 0);
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = gdImageGetPixel(im, x, im->cy2);
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = gdImageGetPixel(im, im->cx1, y);
goto processborder;
}
if (x > im->cx2) {
border = gdImageGetPixel(im, im->cx2, y);
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return colorIndex2RGBcustomA(border, 127);
}
}
}
static int getPixelInterpolateWeight(gdImagePtr im, const double x, const double y, const int bgColor)
{
/* Closest pixel <= (xf,yf) */
int sx = (int)(x);
int sy = (int)(y);
const double xf = x - (double)sx;
const double yf = y - (double)sy;
const double nxf = (double) 1.0 - xf;
const double nyf = (double) 1.0 - yf;
const double m1 = xf * yf;
const double m2 = nxf * yf;
const double m3 = xf * nyf;
const double m4 = nxf * nyf;
/* get color values of neighbouring pixels */
const int c1 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy, bgColor) : getPixelOverflowPalette(im, sx, sy, bgColor);
const int c2 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy, bgColor) : getPixelOverflowPalette(im, sx - 1, sy, bgColor);
const int c3 = im->trueColor == 1 ? getPixelOverflowTC(im, sx, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
const int c4 = im->trueColor == 1 ? getPixelOverflowTC(im, sx - 1, sy - 1, bgColor) : getPixelOverflowPalette(im, sx, sy - 1, bgColor);
int r, g, b, a;
if (x < 0) sx--;
if (y < 0) sy--;
/* component-wise summing-up of color values */
if (im->trueColor) {
r = (int)(m1*gdTrueColorGetRed(c1) + m2*gdTrueColorGetRed(c2) + m3*gdTrueColorGetRed(c3) + m4*gdTrueColorGetRed(c4));
g = (int)(m1*gdTrueColorGetGreen(c1) + m2*gdTrueColorGetGreen(c2) + m3*gdTrueColorGetGreen(c3) + m4*gdTrueColorGetGreen(c4));
b = (int)(m1*gdTrueColorGetBlue(c1) + m2*gdTrueColorGetBlue(c2) + m3*gdTrueColorGetBlue(c3) + m4*gdTrueColorGetBlue(c4));
a = (int)(m1*gdTrueColorGetAlpha(c1) + m2*gdTrueColorGetAlpha(c2) + m3*gdTrueColorGetAlpha(c3) + m4*gdTrueColorGetAlpha(c4));
} else {
r = (int)(m1*im->red[(c1)] + m2*im->red[(c2)] + m3*im->red[(c3)] + m4*im->red[(c4)]);
g = (int)(m1*im->green[(c1)] + m2*im->green[(c2)] + m3*im->green[(c3)] + m4*im->green[(c4)]);
b = (int)(m1*im->blue[(c1)] + m2*im->blue[(c2)] + m3*im->blue[(c3)] + m4*im->blue[(c4)]);
a = (int)(m1*im->alpha[(c1)] + m2*im->alpha[(c2)] + m3*im->alpha[(c3)] + m4*im->alpha[(c4)]);
}
r = CLAMP(r, 0, 255);
g = CLAMP(g, 0, 255);
b = CLAMP(b, 0, 255);
a = CLAMP(a, 0, gdAlphaMax);
return gdTrueColorAlpha(r, g, b, a);
}
/**
* Function: getPixelInterpolated
* Returns the interpolated color value using the default interpolation
* method. The returned color is always in the ARGB format (truecolor).
*
* Parameters:
* im - Image to set the default interpolation method
* y - X value of the ideal position
* y - Y value of the ideal position
* method - Interpolation method <gdInterpolationMethod>
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*
* See also:
* <gdSetInterpolationMethod>
*/
int getPixelInterpolated(gdImagePtr im, const double x, const double y, const int bgColor)
{
const int xi=(int)((x) < 0 ? x - 1: x);
const int yi=(int)((y) < 0 ? y - 1: y);
int yii;
int i;
double kernel, kernel_cache_y;
double kernel_x[12], kernel_y[4];
double new_r = 0.0f, new_g = 0.0f, new_b = 0.0f, new_a = 0.0f;
/* These methods use special implementations */
if (im->interpolation_id == GD_BILINEAR_FIXED || im->interpolation_id == GD_BICUBIC_FIXED || im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
return -1;
}
if (im->interpolation_id == GD_WEIGHTED4) {
return getPixelInterpolateWeight(im, x, y, bgColor);
}
if (im->interpolation_id == GD_NEAREST_NEIGHBOUR) {
if (im->trueColor == 1) {
return getPixelOverflowTC(im, xi, yi, bgColor);
} else {
return getPixelOverflowPalette(im, xi, yi, bgColor);
}
}
if (im->interpolation) {
for (i=0; i<4; i++) {
kernel_x[i] = (double) im->interpolation((double)(xi+i-1-x));
kernel_y[i] = (double) im->interpolation((double)(yi+i-1-y));
}
} else {
return -1;
}
/*
* TODO: use the known fast rgba multiplication implementation once
* the new formats are in place
*/
for (yii = yi-1; yii < yi+3; yii++) {
int xii;
kernel_cache_y = kernel_y[yii-(yi-1)];
if (im->trueColor) {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowTC(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
} else {
for (xii=xi-1; xii<xi+3; xii++) {
const int rgbs = getPixelOverflowPalette(im, xii, yii, bgColor);
kernel = kernel_cache_y * kernel_x[xii-(xi-1)];
new_r += kernel * gdTrueColorGetRed(rgbs);
new_g += kernel * gdTrueColorGetGreen(rgbs);
new_b += kernel * gdTrueColorGetBlue(rgbs);
new_a += kernel * gdTrueColorGetAlpha(rgbs);
}
}
}
new_r = CLAMP(new_r, 0, 255);
new_g = CLAMP(new_g, 0, 255);
new_b = CLAMP(new_b, 0, 255);
new_a = CLAMP(new_a, 0, gdAlphaMax);
return gdTrueColorAlpha(((int)new_r), ((int)new_g), ((int)new_b), ((int)new_a));
}
static inline LineContribType * _gdContributionsAlloc(unsigned int line_length, unsigned int windows_size)
{
unsigned int u = 0;
LineContribType *res;
res = (LineContribType *) gdMalloc(sizeof(LineContribType));
if (!res) {
return NULL;
}
res->WindowSize = windows_size;
res->LineLength = line_length;
res->ContribRow = (ContributionType *) gdMalloc(line_length * sizeof(ContributionType));
for (u = 0 ; u < line_length ; u++) {
res->ContribRow[u].Weights = (double *) gdMalloc(windows_size * sizeof(double));
}
return res;
}
static inline void _gdContributionsFree(LineContribType * p)
{
unsigned int u;
for (u = 0; u < p->LineLength; u++) {
gdFree(p->ContribRow[u].Weights);
}
gdFree(p->ContribRow);
gdFree(p);
}
static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsigned int src_size, double scale_d, const interpolation_method pFilter)
{
double width_d;
double scale_f_d = 1.0;
const double filter_width_d = DEFAULT_BOX_RADIUS;
int windows_size;
unsigned int u;
LineContribType *res;
if (scale_d < 1.0) {
width_d = filter_width_d / scale_d;
scale_f_d = scale_d;
} else {
width_d= filter_width_d;
}
windows_size = 2 * (int)ceil(width_d) + 1;
res = _gdContributionsAlloc(line_size, windows_size);
for (u = 0; u < line_size; u++) {
const double dCenter = (double)u / scale_d;
/* get the significant edge points affecting the pixel */
register int iLeft = MAX(0, (int)floor (dCenter - width_d));
int iRight = MIN((int)ceil(dCenter + width_d), (int)src_size - 1);
double dTotalWeight = 0.0;
int iSrc;
res->ContribRow[u].Left = iLeft;
res->ContribRow[u].Right = iRight;
/* Cut edge points to fit in filter window in case of spill-off */
if (iRight - iLeft + 1 > windows_size) {
if (iLeft < ((int)src_size - 1 / 2)) {
iLeft++;
} else {
iRight--;
}
}
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc)));
}
if (dTotalWeight < 0.0) {
_gdContributionsFree(res);
return NULL;
}
if (dTotalWeight > 0.0) {
for (iSrc = iLeft; iSrc <= iRight; iSrc++) {
res->ContribRow[u].Weights[iSrc-iLeft] /= dTotalWeight;
}
}
}
return res;
}
static inline void _gdScaleRow(gdImagePtr pSrc, unsigned int src_width, gdImagePtr dst, unsigned int dst_width, unsigned int row, LineContribType *contrib)
{
int *p_src_row = pSrc->tpixels[row];
int *p_dst_row = dst->tpixels[row];
unsigned int x;
for (x = 0; x < dst_width - 1; x++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int left = contrib->ContribRow[x].Left;
const int right = contrib->ContribRow[x].Right;
int i;
/* Accumulate each channel */
for (i = left; i <= right; i++) {
const int left_channel = i - left;
r += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetRed(p_src_row[i])));
g += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetGreen(p_src_row[i])));
b += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetBlue(p_src_row[i])));
a += (unsigned char)(contrib->ContribRow[x].Weights[left_channel] * (double)(gdTrueColorGetAlpha(p_src_row[i])));
}
p_dst_row[x] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleHoriz(gdImagePtr pSrc, unsigned int src_width, unsigned int src_height, gdImagePtr pDst, unsigned int dst_width, unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same width, just copy it */
if (dst_width == src_width) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_width, src_width, (double)dst_width / (double)src_width, pSrc->interpolation);
if (contrib == NULL) {
return;
}
/* Scale each row */
for (u = 0; u < dst_height - 1; u++) {
_gdScaleRow(pSrc, src_width, pDst, dst_width, u, contrib);
}
_gdContributionsFree (contrib);
}
static inline void _gdScaleCol (gdImagePtr pSrc, unsigned int src_width, gdImagePtr pRes, unsigned int dst_width, unsigned int dst_height, unsigned int uCol, LineContribType *contrib)
{
unsigned int y;
for (y = 0; y < dst_height - 1; y++) {
register unsigned char r = 0, g = 0, b = 0, a = 0;
const int iLeft = contrib->ContribRow[y].Left;
const int iRight = contrib->ContribRow[y].Right;
int i;
/* Accumulate each channel */
for (i = iLeft; i <= iRight; i++) {
const int pCurSrc = pSrc->tpixels[i][uCol];
const int i_iLeft = i - iLeft;
r += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetRed(pCurSrc)));
g += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetGreen(pCurSrc)));
b += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetBlue(pCurSrc)));
a += (unsigned char)(contrib->ContribRow[y].Weights[i_iLeft] * (double)(gdTrueColorGetAlpha(pCurSrc)));
}
pRes->tpixels[y][uCol] = gdTrueColorAlpha(r, g, b, a);
}
}
static inline void _gdScaleVert (const gdImagePtr pSrc, const unsigned int src_width, const unsigned int src_height, const gdImagePtr pDst, const unsigned int dst_width, const unsigned int dst_height)
{
unsigned int u;
LineContribType * contrib;
/* same height, copy it */
if (src_height == dst_height) {
unsigned int y;
for (y = 0; y < src_height - 1; ++y) {
memcpy(pDst->tpixels[y], pSrc->tpixels[y], src_width);
}
}
contrib = _gdContributionsCalc(dst_height, src_height, (double)(dst_height) / (double)(src_height), pSrc->interpolation);
/* scale each column */
for (u = 0; u < dst_width - 1; u++) {
_gdScaleCol(pSrc, src_width, pDst, dst_width, dst_height, u, contrib);
}
_gdContributionsFree(contrib);
}
gdImagePtr gdImageScaleTwoPass(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
gdImagePtr dst;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
gdImageSetInterpolationMethod(tmp_im, src->interpolation_id);
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
gdFree(tmp_im);
return NULL;
}
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
gdImagePtr Scale(const gdImagePtr src, const unsigned int src_width, const unsigned int src_height, const gdImagePtr dst, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr tmp_im;
tmp_im = gdImageCreateTrueColor(new_width, src_height);
if (tmp_im == NULL) {
return NULL;
}
_gdScaleHoriz(src, src_width, src_height, tmp_im, new_width, src_height);
_gdScaleVert(tmp_im, new_width, src_height, dst, new_width, new_height);
gdFree(tmp_im);
return dst;
}
/*
BilinearFixed, BicubicFixed and nearest implementations are rewamped versions of the implementation in CBitmapEx
http://www.codeproject.com/Articles/29121/CBitmapEx-Free-C-Bitmap-Manipulation-Class
Integer only implementation, good to have for common usages like pre scale very large
images before using another interpolation methods for the last step.
*/
gdImagePtr gdImageScaleNearestNeighbour(gdImagePtr im, const unsigned int width, const unsigned int height)
{
const unsigned long new_width = MAX(1, width);
const unsigned long new_height = MAX(1, height);
const float dx = (float)im->sx / (float)new_width;
const float dy = (float)im->sy / (float)new_height;
const gdFixed f_dx = gd_ftofx(dx);
const gdFixed f_dy = gd_ftofx(dy);
gdImagePtr dst_img;
unsigned long dst_offset_x;
unsigned long dst_offset_y = 0;
unsigned int i;
dst_img = gdImageCreateTrueColor(new_width, new_height);
if (dst_img == NULL) {
return NULL;
}
for (i=0; i<new_height; i++) {
unsigned int j;
dst_offset_x = 0;
if (im->trueColor) {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = im->tpixels[m][n];
}
} else {
for (j=0; j<new_width; j++) {
const gdFixed f_i = gd_itofx(i);
const gdFixed f_j = gd_itofx(j);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
const gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
dst_img->tpixels[dst_offset_y][dst_offset_x++] = colorIndex2RGBA(im->pixels[m][n]);
}
}
dst_offset_y++;
}
return dst_img;
}
static inline int getPixelOverflowColorTC(gdImagePtr im, const int x, const int y, const int color)
{
if (gdImageBoundsSafe(im, x, y)) {
const int c = im->tpixels[y][x];
if (c == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
}
return c;
} else {
register int border = 0;
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y < im->cy1) {
border = im->tpixels[0][im->cx1];
goto processborder;
}
if (y > im->cy2) {
if (x >= im->cx1 && x <= im->cx1) {
border = im->tpixels[im->cy2][x];
goto processborder;
} else {
return gdTrueColorAlpha(0, 0, 0, 127);
}
}
/* y is bound safe at this point */
if (x < im->cx1) {
border = im->tpixels[y][im->cx1];
goto processborder;
}
if (x > im->cx2) {
border = im->tpixels[y][im->cx2];
}
processborder:
if (border == im->transparent) {
return gdTrueColorAlpha(0, 0, 0, 127);
} else{
return gdTrueColorAlpha(gdTrueColorGetRed(border), gdTrueColorGetGreen(border), gdTrueColorGetBlue(border), 127);
}
}
}
static gdImagePtr gdImageScaleBilinearPalette(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long _width = MAX(1, new_width);
long _height = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)_width;
float dy = (float)gdImageSY(im) / (float)_height;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
const int transparent = im->transparent;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (new_img == NULL) {
return NULL;
}
new_img->transparent = gdTrueColorAlpha(im->red[transparent], im->green[transparent], im->blue[transparent], im->alpha[transparent]);
for (i=0; i < _height; i++) {
long j;
const gdFixed f_i = gd_itofx(i);
const gdFixed f_a = gd_mulfx(f_i, f_dy);
register long m = gd_fxtoi(f_a);
dst_offset_h = 0;
for (j=0; j < _width; j++) {
/* Update bitmap */
gdFixed f_j = gd_itofx(j);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* zero for the background color, nothig gets outside anyway */
pixel1 = getPixelOverflowPalette(im, n, m, 0);
pixel2 = getPixelOverflowPalette(im, n + 1, m, 0);
pixel3 = getPixelOverflowPalette(im, n, m + 1, 0);
pixel4 = getPixelOverflowPalette(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
static gdImagePtr gdImageScaleBilinearTC(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
long dst_w = MAX(1, new_width);
long dst_h = MAX(1, new_height);
float dx = (float)gdImageSX(im) / (float)dst_w;
float dy = (float)gdImageSY(im) / (float)dst_h;
gdFixed f_dx = gd_ftofx(dx);
gdFixed f_dy = gd_ftofx(dy);
gdFixed f_1 = gd_itofx(1);
int dst_offset_h;
int dst_offset_v = 0;
long i;
gdImagePtr new_img;
new_img = gdImageCreateTrueColor(new_width, new_height);
if (!new_img){
return NULL;
}
for (i=0; i < dst_h; i++) {
long j;
dst_offset_h = 0;
for (j=0; j < dst_w; j++) {
/* Update bitmap */
gdFixed f_i = gd_itofx(i);
gdFixed f_j = gd_itofx(j);
gdFixed f_a = gd_mulfx(f_i, f_dy);
gdFixed f_b = gd_mulfx(f_j, f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
gdFixed f_f = f_a - gd_itofx(m);
gdFixed f_g = f_b - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
unsigned int pixel1;
unsigned int pixel2;
unsigned int pixel3;
unsigned int pixel4;
register gdFixed f_r1, f_r2, f_r3, f_r4,
f_g1, f_g2, f_g3, f_g4,
f_b1, f_b2, f_b3, f_b4,
f_a1, f_a2, f_a3, f_a4;
/* 0 for bgColor, nothing gets outside anyway */
pixel1 = getPixelOverflowTC(im, n, m, 0);
pixel2 = getPixelOverflowTC(im, n + 1, m, 0);
pixel3 = getPixelOverflowTC(im, n, m + 1, 0);
pixel4 = getPixelOverflowTC(im, n + 1, m + 1, 0);
f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
{
const char red = (char) gd_fxtoi(gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4));
const char green = (char) gd_fxtoi(gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4));
const char blue = (char) gd_fxtoi(gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4));
const char alpha = (char) gd_fxtoi(gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4));
new_img->tpixels[dst_offset_v][dst_offset_h] = gdTrueColorAlpha(red, green, blue, alpha);
}
dst_offset_h++;
}
dst_offset_v++;
}
return new_img;
}
gdImagePtr gdImageScaleBilinear(gdImagePtr im, const unsigned int new_width, const unsigned int new_height)
{
if (im->trueColor) {
return gdImageScaleBilinearTC(im, new_width, new_height);
} else {
return gdImageScaleBilinearPalette(im, new_width, new_height);
}
}
gdImagePtr gdImageScaleBicubicFixed(gdImagePtr src, const unsigned int width, const unsigned int height)
{
const long new_width = MAX(1, width);
const long new_height = MAX(1, height);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const gdFixed f_dx = gd_ftofx((float)src_w / (float)new_width);
const gdFixed f_dy = gd_ftofx((float)src_h / (float)new_height);
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gamma = gd_ftofx(1.04f);
gdImagePtr dst;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
long i;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
long j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_a = gd_mulfx(gd_itofx(i), f_dy);
const gdFixed f_b = gd_mulfx(gd_itofx(j), f_dx);
const long m = gd_fxtoi(f_a);
const long n = gd_fxtoi(f_b);
const gdFixed f_f = f_a - gd_itofx(m);
const gdFixed f_g = f_b - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
long k;
register gdFixed f_red = 0, f_green = 0, f_blue = 0, f_alpha = 0;
unsigned char red, green, blue, alpha = 0;
int *dst_row = dst->tpixels[dst_offset_y];
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m;
}
if ((m < 1) || (n >= src_w - 1)) {
src_offset_x[2] = n;
src_offset_y[2] = m;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m;
}
if ((m < 1) || (n >= src_w - 2)) {
src_offset_x[3] = n;
src_offset_y[3] = m;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m;
}
if (n < 1) {
src_offset_x[4] = n;
src_offset_y[4] = m;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = n;
src_offset_y[6] = m;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w - 2) {
src_offset_x[7] = n;
src_offset_y[7] = m;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h - 1) || (n < 1)) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h - 1) {
src_offset_x[8] = n;
src_offset_y[8] = m;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = n;
src_offset_y[10] = m;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h - 1) || (n >= src_w - 2)) {
src_offset_x[11] = n;
src_offset_y[11] = m;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h - 2) || (n < 1)) {
src_offset_x[12] = n;
src_offset_y[12] = m;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h - 2) {
src_offset_x[13] = n;
src_offset_y[13] = m;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 1)) {
src_offset_x[14] = n;
src_offset_y[14] = m;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h - 2) || (n >= src_w - 2)) {
src_offset_x[15] = n;
src_offset_y[15] = m;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k = -1; k < 3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_d = 0, f_c = 0;
register gdFixed f_RY;
int l;
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2, gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1, gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f, gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1, gd_mulfx(f_fm1,f_fm1));
f_RY = gd_divfx((f_a - gd_mulfx(f_4,f_b) + gd_mulfx(f_6,f_c) - gd_mulfx(f_4,f_d)),f_6);
for (l = -1; l < 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
register gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
register gdFixed f_RX, f_R, f_rs, f_gs, f_bs, f_ba;
register int c;
const int _k = ((k+1)*4) + (l+1);
if (f_fp2 > 0) f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
if (f_fp1 > 0) f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
if (f > 0) f_c = gd_mulfx(f,gd_mulfx(f,f));
if (f_fm1 > 0) f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
f_RX = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
f_R = gd_mulfx(f_RY,f_RX);
c = src->tpixels[*(src_offset_y + _k)][*(src_offset_x + _k)];
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_ba = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs,f_R);
f_green += gd_mulfx(f_gs,f_R);
f_blue += gd_mulfx(f_bs,f_R);
f_alpha += gd_mulfx(f_ba,f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gamma)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gamma)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gamma)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gamma)), 0, 127);
*(dst_row + dst_offset_x) = gdTrueColorAlpha(red, green, blue, alpha);
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
BGD_DECLARE(gdImagePtr) gdImageScale(const gdImagePtr src, const unsigned int new_width, const unsigned int new_height)
{
gdImagePtr im_scaled = NULL;
if (src == NULL || src->interpolation_id < 0 || src->interpolation_id > GD_METHOD_COUNT) {
return 0;
}
switch (src->interpolation_id) {
/*Special cases, optimized implementations */
case GD_NEAREST_NEIGHBOUR:
im_scaled = gdImageScaleNearestNeighbour(src, new_width, new_height);
break;
case GD_BILINEAR_FIXED:
im_scaled = gdImageScaleBilinear(src, new_width, new_height);
break;
case GD_BICUBIC_FIXED:
im_scaled = gdImageScaleBicubicFixed(src, new_width, new_height);
break;
/* generic */
default:
if (src->interpolation == NULL) {
return NULL;
}
im_scaled = gdImageScaleTwoPass(src, src->sx, src->sy, new_width, new_height);
break;
}
return im_scaled;
}
gdImagePtr gdImageRotateNearestNeighbour(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h-1) && (n > 0) && (n < src_w-1)) {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = src->tpixels[m][n];
}
} else {
if (dst_offset_y < new_height) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateGeneric(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = ((float) (-degrees / 180.0f) * (float)M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = (unsigned int)(abs((int)(src_w * cos(_angle))) + abs((int)(src_h * sin(_angle))) + 0.5f);
const unsigned int new_height = (unsigned int)(abs((int)(src_w * sin(_angle))) + abs((int)(src_h * cos(_angle))) + 0.5f);
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
const gdFixed f_slop_y = f_sin;
const gdFixed f_slop_x = f_cos;
const gdFixed f_slop = f_slop_x > 0 && f_slop_x > 0 ?
f_slop_x > f_slop_y ? gd_divfx(f_slop_y, f_slop_x) : gd_divfx(f_slop_x, f_slop_y)
: 0;
if (bgColor < 0) {
return NULL;
}
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (!dst) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j = 0; j < new_width; j++) {
gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
long m = gd_fxtoi(f_m);
long n = gd_fxtoi(f_n);
if ((n <= 0) || (m <= 0) || (m >= src_h) || (n >= src_w)) {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
} else if ((n <= 1) || (m <= 1) || (m >= src_h - 1) || (n >= src_w - 1)) {
register int c = getPixelInterpolated(src, n, m, bgColor);
c = c | (( gdTrueColorGetAlpha(c) + ((int)(127* gd_fxtof(f_slop)))) << 24);
dst->tpixels[dst_offset_y][dst_offset_x++] = _color_blend(bgColor, c);
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = getPixelInterpolated(src, n, m, bgColor);
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor)
{
float _angle = (float)((- degrees / 180.0f) * M_PI);
const unsigned int src_w = gdImageSX(src);
const unsigned int src_h = gdImageSY(src);
unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
unsigned int i;
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int src_offset_x, src_offset_y;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i = 0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const unsigned int m = gd_fxtoi(f_m);
const unsigned int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g);
const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g);
const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g);
const gdFixed f_w4 = gd_mulfx(f_f, f_g);
if (n < src_w - 1) {
src_offset_x = n + 1;
src_offset_y = m;
}
if (m < src_h - 1) {
src_offset_x = n;
src_offset_y = m + 1;
}
if (!((n >= src_w - 1) || (m >= src_h - 1))) {
src_offset_x = n + 1;
src_offset_y = m + 1;
}
{
const int pixel1 = src->tpixels[src_offset_y][src_offset_x];
register int pixel2, pixel3, pixel4;
if (src_offset_y + 1 >= src_h) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else if (src_offset_x + 1 >= src_w) {
pixel2 = bgColor;
pixel3 = bgColor;
pixel4 = bgColor;
} else {
pixel2 = src->tpixels[src_offset_y][src_offset_x + 1];
pixel3 = src->tpixels[src_offset_y + 1][src_offset_x];
pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1];
}
{
const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1));
const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2));
const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3));
const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4));
const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1));
const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2));
const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3));
const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4));
const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1));
const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2));
const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3));
const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4));
const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1));
const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2));
const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3));
const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4));
const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4);
const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4);
const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4);
const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4);
const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255);
const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255);
const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255);
const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha);
}
}
} else {
dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor;
}
}
dst_offset_y++;
}
return dst;
}
gdImagePtr gdImageRotateBicubicFixed(gdImagePtr src, const float degrees, const int bgColor)
{
const float _angle = (float)((- degrees / 180.0f) * M_PI);
const int src_w = gdImageSX(src);
const int src_h = gdImageSY(src);
const unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f));
const unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f));
const gdFixed f_0_5 = gd_ftofx(0.5f);
const gdFixed f_H = gd_itofx(src_h/2);
const gdFixed f_W = gd_itofx(src_w/2);
const gdFixed f_cos = gd_ftofx(cos(-_angle));
const gdFixed f_sin = gd_ftofx(sin(-_angle));
const gdFixed f_1 = gd_itofx(1);
const gdFixed f_2 = gd_itofx(2);
const gdFixed f_4 = gd_itofx(4);
const gdFixed f_6 = gd_itofx(6);
const gdFixed f_gama = gd_ftofx(1.04f);
unsigned int dst_offset_x;
unsigned int dst_offset_y = 0;
unsigned int i;
gdImagePtr dst;
/* impact perf a bit, but not that much. Implementation for palette
images can be done at a later point.
*/
if (src->trueColor == 0) {
gdImagePaletteToTrueColor(src);
}
dst = gdImageCreateTrueColor(new_width, new_height);
if (dst == NULL) {
return NULL;
}
dst->saveAlphaFlag = 1;
for (i=0; i < new_height; i++) {
unsigned int j;
dst_offset_x = 0;
for (j=0; j < new_width; j++) {
const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2);
const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2);
const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H;
const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W;
const int m = gd_fxtoi(f_m);
const int n = gd_fxtoi(f_n);
if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w-1)) {
const gdFixed f_f = f_m - gd_itofx(m);
const gdFixed f_g = f_n - gd_itofx(n);
unsigned int src_offset_x[16], src_offset_y[16];
unsigned char red, green, blue, alpha;
gdFixed f_red=0, f_green=0, f_blue=0, f_alpha=0;
int k;
if ((m < 1) || (n < 1)) {
src_offset_x[0] = n;
src_offset_y[0] = m;
} else {
src_offset_x[0] = n - 1;
src_offset_y[0] = m;
}
if (m < 1) {
src_offset_x[1] = n;
src_offset_y[1] = m;
} else {
src_offset_x[1] = n;
src_offset_y[1] = m ;
}
if ((m < 1) || (n >= src_w-1)) {
src_offset_x[2] = - 1;
src_offset_y[2] = - 1;
} else {
src_offset_x[2] = n + 1;
src_offset_y[2] = m ;
}
if ((m < 1) || (n >= src_w-2)) {
src_offset_x[3] = - 1;
src_offset_y[3] = - 1;
} else {
src_offset_x[3] = n + 1 + 1;
src_offset_y[3] = m ;
}
if (n < 1) {
src_offset_x[4] = - 1;
src_offset_y[4] = - 1;
} else {
src_offset_x[4] = n - 1;
src_offset_y[4] = m;
}
src_offset_x[5] = n;
src_offset_y[5] = m;
if (n >= src_w-1) {
src_offset_x[6] = - 1;
src_offset_y[6] = - 1;
} else {
src_offset_x[6] = n + 1;
src_offset_y[6] = m;
}
if (n >= src_w-2) {
src_offset_x[7] = - 1;
src_offset_y[7] = - 1;
} else {
src_offset_x[7] = n + 1 + 1;
src_offset_y[7] = m;
}
if ((m >= src_h-1) || (n < 1)) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[8] = n - 1;
src_offset_y[8] = m;
}
if (m >= src_h-1) {
src_offset_x[8] = - 1;
src_offset_y[8] = - 1;
} else {
src_offset_x[9] = n;
src_offset_y[9] = m;
}
if ((m >= src_h-1) || (n >= src_w-1)) {
src_offset_x[10] = - 1;
src_offset_y[10] = - 1;
} else {
src_offset_x[10] = n + 1;
src_offset_y[10] = m;
}
if ((m >= src_h-1) || (n >= src_w-2)) {
src_offset_x[11] = - 1;
src_offset_y[11] = - 1;
} else {
src_offset_x[11] = n + 1 + 1;
src_offset_y[11] = m;
}
if ((m >= src_h-2) || (n < 1)) {
src_offset_x[12] = - 1;
src_offset_y[12] = - 1;
} else {
src_offset_x[12] = n - 1;
src_offset_y[12] = m;
}
if (m >= src_h-2) {
src_offset_x[13] = - 1;
src_offset_y[13] = - 1;
} else {
src_offset_x[13] = n;
src_offset_y[13] = m;
}
if ((m >= src_h-2) || (n >= src_w - 1)) {
src_offset_x[14] = - 1;
src_offset_y[14] = - 1;
} else {
src_offset_x[14] = n + 1;
src_offset_y[14] = m;
}
if ((m >= src_h-2) || (n >= src_w-2)) {
src_offset_x[15] = - 1;
src_offset_y[15] = - 1;
} else {
src_offset_x[15] = n + 1 + 1;
src_offset_y[15] = m;
}
for (k=-1; k<3; k++) {
const gdFixed f = gd_itofx(k)-f_f;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0,f_c = 0, f_d = 0;
gdFixed f_RY;
int l;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RY = gd_divfx((f_a-gd_mulfx(f_4,f_b)+gd_mulfx(f_6,f_c)-gd_mulfx(f_4,f_d)),f_6);
for (l=-1; l< 3; l++) {
const gdFixed f = gd_itofx(l) - f_g;
const gdFixed f_fm1 = f - f_1;
const gdFixed f_fp1 = f + f_1;
const gdFixed f_fp2 = f + f_2;
gdFixed f_a = 0, f_b = 0, f_c = 0, f_d = 0;
gdFixed f_RX, f_R;
const int _k = ((k + 1) * 4) + (l + 1);
register gdFixed f_rs, f_gs, f_bs, f_as;
register int c;
if (f_fp2 > 0) {
f_a = gd_mulfx(f_fp2,gd_mulfx(f_fp2,f_fp2));
}
if (f_fp1 > 0) {
f_b = gd_mulfx(f_fp1,gd_mulfx(f_fp1,f_fp1));
}
if (f > 0) {
f_c = gd_mulfx(f,gd_mulfx(f,f));
}
if (f_fm1 > 0) {
f_d = gd_mulfx(f_fm1,gd_mulfx(f_fm1,f_fm1));
}
f_RX = gd_divfx((f_a - gd_mulfx(f_4, f_b) + gd_mulfx(f_6, f_c) - gd_mulfx(f_4, f_d)), f_6);
f_R = gd_mulfx(f_RY, f_RX);
if ((src_offset_x[_k] <= 0) || (src_offset_y[_k] <= 0) || (src_offset_y[_k] >= src_h) || (src_offset_x[_k] >= src_w)) {
c = bgColor;
} else if ((src_offset_x[_k] <= 1) || (src_offset_y[_k] <= 1) || (src_offset_y[_k] >= (int)src_h - 1) || (src_offset_x[_k] >= (int)src_w - 1)) {
gdFixed f_127 = gd_itofx(127);
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
c = c | (( (int) (gd_fxtof(gd_mulfx(f_R, f_127)) + 50.5f)) << 24);
c = _color_blend(bgColor, c);
} else {
c = src->tpixels[src_offset_y[_k]][src_offset_x[_k]];
}
f_rs = gd_itofx(gdTrueColorGetRed(c));
f_gs = gd_itofx(gdTrueColorGetGreen(c));
f_bs = gd_itofx(gdTrueColorGetBlue(c));
f_as = gd_itofx(gdTrueColorGetAlpha(c));
f_red += gd_mulfx(f_rs, f_R);
f_green += gd_mulfx(f_gs, f_R);
f_blue += gd_mulfx(f_bs, f_R);
f_alpha += gd_mulfx(f_as, f_R);
}
}
red = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_red, f_gama)), 0, 255);
green = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_green, f_gama)), 0, 255);
blue = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_blue, f_gama)), 0, 255);
alpha = (unsigned char) CLAMP(gd_fxtoi(gd_mulfx(f_alpha, f_gama)), 0, 127);
dst->tpixels[dst_offset_y][dst_offset_x] = gdTrueColorAlpha(red, green, blue, alpha);
} else {
dst->tpixels[dst_offset_y][dst_offset_x] = bgColor;
}
dst_offset_x++;
}
dst_offset_y++;
}
return dst;
}
BGD_DECLARE(gdImagePtr) gdImageRotateInterpolated(const gdImagePtr src, const float angle, int bgcolor)
{
/* round to two decimals and keep the 100x multiplication to use it in the common square angles
case later. Keep the two decimal precisions so smaller rotation steps can be done, useful for
slow animations, f.e. */
const int angle_rounded = fmod((int) floorf(angle * 100), 360 * 100);
if (bgcolor < 0) {
return NULL;
}
/* 0 && 90 degrees multiple rotation, 0 rotation simply clones the return image and convert it
to truecolor, as we must return truecolor image. */
switch (angle_rounded) {
case 0: {
gdImagePtr dst = gdImageClone(src);
if (dst == NULL) {
return NULL;
}
if (dst->trueColor == 0) {
gdImagePaletteToTrueColor(dst);
}
return dst;
}
case -2700:
case 9000:
return gdImageRotate90(src, 0);
case -18000:
case 18000:
return gdImageRotate180(src, 0);
case -9000:
case 27000:
return gdImageRotate270(src, 0);
}
if (src == NULL || src->interpolation_id < 1 || src->interpolation_id > GD_METHOD_COUNT) {
return NULL;
}
switch (src->interpolation_id) {
case GD_NEAREST_NEIGHBOUR:
return gdImageRotateNearestNeighbour(src, angle, bgcolor);
break;
case GD_BILINEAR_FIXED:
return gdImageRotateBilinear(src, angle, bgcolor);
break;
case GD_BICUBIC_FIXED:
return gdImageRotateBicubicFixed(src, angle, bgcolor);
break;
default:
return gdImageRotateGeneric(src, angle, bgcolor);
}
return NULL;
}
/**
* Title: Affine transformation
**/
/**
* Group: Transform
**/
static void gdImageClipRectangle(gdImagePtr im, gdRectPtr r)
{
int c1x, c1y, c2x, c2y;
int x1,y1;
gdImageGetClip(im, &c1x, &c1y, &c2x, &c2y);
x1 = r->x + r->width - 1;
y1 = r->y + r->height - 1;
r->x = CLAMP(r->x, c1x, c2x);
r->y = CLAMP(r->y, c1y, c2y);
r->width = CLAMP(x1, c1x, c2x) - r->x + 1;
r->height = CLAMP(y1, c1y, c2y) - r->y + 1;
}
void gdDumpRect(const char *msg, gdRectPtr r)
{
printf("%s (%i, %i) (%i, %i)\n", msg, r->x, r->y, r->width, r->height);
}
/**
* Function: gdTransformAffineGetImage
* Applies an affine transformation to a region and return an image
* containing the complete transformation.
*
* Parameters:
* dst - Pointer to a gdImagePtr to store the created image, NULL when
* the creation or the transformation failed
* src - Source image
* src_area - rectangle defining the source region to transform
* dstY - Y position in the destination image
* affine - The desired affine transformation
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineGetImage(gdImagePtr *dst,
const gdImagePtr src,
gdRectPtr src_area,
const double affine[6])
{
int res;
double m[6];
gdRect bbox;
gdRect area_full;
if (src_area == NULL) {
area_full.x = 0;
area_full.y = 0;
area_full.width = gdImageSX(src);
area_full.height = gdImageSY(src);
src_area = &area_full;
}
gdTransformAffineBoundingBox(src_area, affine, &bbox);
*dst = gdImageCreateTrueColor(bbox.width, bbox.height);
if (*dst == NULL) {
return GD_FALSE;
}
(*dst)->saveAlphaFlag = 1;
if (!src->trueColor) {
gdImagePaletteToTrueColor(src);
}
/* Translate to dst origin (0,0) */
gdAffineTranslate(m, -bbox.x, -bbox.y);
gdAffineConcat(m, affine, m);
gdImageAlphaBlending(*dst, 0);
res = gdTransformAffineCopy(*dst,
0,0,
src,
src_area,
m);
if (res != GD_TRUE) {
gdImageDestroy(*dst);
dst = NULL;
return GD_FALSE;
} else {
return GD_TRUE;
}
}
/**
* Function: gdTransformAffineCopy
* Applies an affine transformation to a region and copy the result
* in a destination to the given position.
*
* Parameters:
* dst - Image to draw the transformed image
* src - Source image
* dstX - X position in the destination image
* dstY - Y position in the destination image
* src_area - Rectangular region to rotate in the src image
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineCopy(gdImagePtr dst,
int dst_x, int dst_y,
const gdImagePtr src,
gdRectPtr src_region,
const double affine[6])
{
int c1x,c1y,c2x,c2y;
int backclip = 0;
int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2;
register int x, y, src_offset_x, src_offset_y;
double inv[6];
int *dst_p;
gdPointF pt, src_pt;
gdRect bbox;
int end_x, end_y;
gdInterpolationMethod interpolation_id_bak = GD_DEFAULT;
/* These methods use special implementations */
if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) {
interpolation_id_bak = src->interpolation_id;
gdImageSetInterpolationMethod(src, GD_BICUBIC);
}
gdImageClipRectangle(src, src_region);
if (src_region->x > 0 || src_region->y > 0
|| src_region->width < gdImageSX(src)
|| src_region->height < gdImageSY(src)) {
backclip = 1;
gdImageGetClip(src, &backup_clipx1, &backup_clipy1,
&backup_clipx2, &backup_clipy2);
gdImageSetClip(src, src_region->x, src_region->y,
src_region->x + src_region->width - 1,
src_region->y + src_region->height - 1);
}
if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) {
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_FALSE;
}
gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y);
end_x = bbox.width + (int) fabs(bbox.x);
end_y = bbox.height + (int) fabs(bbox.y);
/* Get inverse affine to let us work with destination -> source */
gdAffineInvert(inv, affine);
src_offset_x = src_region->x;
src_offset_y = src_region->y;
if (dst->alphaBlendingFlag) {
for (y = bbox.y; y <= end_y; y++) {
pt.y = y + 0.5;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5;
gdAffineApplyToPointF(&src_pt, &pt, inv);
gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0));
}
}
} else {
for (y = 0; y <= end_y; y++) {
pt.y = y + 0.5 + bbox.y;
if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) {
continue;
}
dst_p = dst->tpixels[dst_y + y] + dst_x;
for (x = 0; x <= end_x; x++) {
pt.x = x + 0.5 + bbox.x;
gdAffineApplyToPointF(&src_pt, &pt, inv);
if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) {
break;
}
*(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1);
}
}
}
/* Restore clip if required */
if (backclip) {
gdImageSetClip(src, backup_clipx1, backup_clipy1,
backup_clipx2, backup_clipy2);
}
gdImageSetInterpolationMethod(src, interpolation_id_bak);
return GD_TRUE;
}
/**
* Function: gdTransformAffineBoundingBox
* Returns the bounding box of an affine transformation applied to a
* rectangular area <gdRect>
*
* Parameters:
* src - Rectangular source area for the affine transformation
* affine - the affine transformation
* bbox - the resulting bounding box
*
* Returns:
* GD_TRUE if the affine is rectilinear or GD_FALSE
*/
BGD_DECLARE(int) gdTransformAffineBoundingBox(gdRectPtr src, const double affine[6], gdRectPtr bbox)
{
gdPointF extent[4], min, max, point;
int i;
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) src->width;
extent[1].y=0.0;
extent[2].x=(double) src->width;
extent[2].y=(double) src->height;
extent[3].x=0.0;
extent[3].y=(double) src->height;
for (i=0; i < 4; i++) {
point=extent[i];
if (gdAffineApplyToPointF(&extent[i], &point, affine) != GD_TRUE) {
return GD_FALSE;
}
}
min=extent[0];
max=extent[0];
for (i=1; i < 4; i++) {
if (min.x > extent[i].x)
min.x=extent[i].x;
if (min.y > extent[i].y)
min.y=extent[i].y;
if (max.x < extent[i].x)
max.x=extent[i].x;
if (max.y < extent[i].y)
max.y=extent[i].y;
}
bbox->x = (int) min.x;
bbox->y = (int) min.y;
bbox->width = (int) floor(max.x - min.x) - 1;
bbox->height = (int) floor(max.y - min.y);
return GD_TRUE;
}
BGD_DECLARE(int) gdImageSetInterpolationMethod(gdImagePtr im, gdInterpolationMethod id)
{
if (im == NULL || id < 0 || id > GD_METHOD_COUNT) {
return 0;
}
switch (id) {
case GD_DEFAULT:
im->interpolation_id = GD_BILINEAR_FIXED;
im->interpolation = NULL;
break;
/* Optimized versions */
case GD_BILINEAR_FIXED:
case GD_BICUBIC_FIXED:
case GD_NEAREST_NEIGHBOUR:
case GD_WEIGHTED4:
im->interpolation = NULL;
break;
/* generic versions*/
case GD_BELL:
im->interpolation = filter_bell;
break;
case GD_BESSEL:
im->interpolation = filter_bessel;
break;
case GD_BICUBIC:
im->interpolation = filter_bicubic;
break;
case GD_BLACKMAN:
im->interpolation = filter_blackman;
break;
case GD_BOX:
im->interpolation = filter_box;
break;
case GD_BSPLINE:
im->interpolation = filter_bspline;
break;
case GD_CATMULLROM:
im->interpolation = filter_catmullrom;
break;
case GD_GAUSSIAN:
im->interpolation = filter_gaussian;
break;
case GD_GENERALIZED_CUBIC:
im->interpolation = filter_generalized_cubic;
break;
case GD_HERMITE:
im->interpolation = filter_hermite;
break;
case GD_HAMMING:
im->interpolation = filter_hamming;
break;
case GD_HANNING:
im->interpolation = filter_hanning;
break;
case GD_MITCHELL:
im->interpolation = filter_mitchell;
break;
case GD_POWER:
im->interpolation = filter_power;
break;
case GD_QUADRATIC:
im->interpolation = filter_quadratic;
break;
case GD_SINC:
im->interpolation = filter_sinc;
break;
case GD_TRIANGLE:
im->interpolation = filter_triangle;
break;
default:
return 0;
break;
}
im->interpolation_id = id;
return 1;
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5869_0 |
crossvul-cpp_data_bad_3905_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Windowing Alternate Secondary Orders
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
* Copyright 2011 Roman Barabanov <romanbarabanov@gmail.com>
*
* 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 <winpr/crt.h>
#include <freerdp/log.h>
#include "window.h"
#define TAG FREERDP_TAG("core.window")
static void update_free_window_icon_info(ICON_INFO* iconInfo);
BOOL rail_read_unicode_string(wStream* s, RAIL_UNICODE_STRING* unicode_string)
{
UINT16 new_len;
BYTE* new_str;
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, new_len); /* cbString (2 bytes) */
if (Stream_GetRemainingLength(s) < new_len)
return FALSE;
if (!new_len)
{
free(unicode_string->string);
unicode_string->string = NULL;
unicode_string->length = 0;
return TRUE;
}
new_str = (BYTE*)realloc(unicode_string->string, new_len);
if (!new_str)
{
free(unicode_string->string);
unicode_string->string = NULL;
return FALSE;
}
unicode_string->string = new_str;
unicode_string->length = new_len;
Stream_Read(s, unicode_string->string, unicode_string->length);
return TRUE;
}
BOOL utf8_string_to_rail_string(const char* string, RAIL_UNICODE_STRING* unicode_string)
{
WCHAR* buffer = NULL;
int length = 0;
free(unicode_string->string);
unicode_string->string = NULL;
unicode_string->length = 0;
if (!string || strlen(string) < 1)
return TRUE;
length = ConvertToUnicode(CP_UTF8, 0, string, -1, &buffer, 0);
if ((length < 0) || ((size_t)length * sizeof(WCHAR) > UINT16_MAX))
{
free(buffer);
return FALSE;
}
unicode_string->string = (BYTE*)buffer;
unicode_string->length = (UINT16)length * sizeof(WCHAR);
return TRUE;
}
/* See [MS-RDPERP] 2.2.1.2.3 Icon Info (TS_ICON_INFO) */
static BOOL update_read_icon_info(wStream* s, ICON_INFO* iconInfo)
{
BYTE* newBitMask;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, iconInfo->cacheId); /* cacheId (1 byte) */
Stream_Read_UINT8(s, iconInfo->bpp); /* bpp (1 byte) */
if ((iconInfo->bpp < 1) || (iconInfo->bpp > 32))
{
WLog_ERR(TAG, "invalid bpp value %" PRIu32 "", iconInfo->bpp);
return FALSE;
}
Stream_Read_UINT16(s, iconInfo->width); /* width (2 bytes) */
Stream_Read_UINT16(s, iconInfo->height); /* height (2 bytes) */
/* cbColorTable is only present when bpp is 1, 4 or 8 */
switch (iconInfo->bpp)
{
case 1:
case 4:
case 8:
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbColorTable); /* cbColorTable (2 bytes) */
break;
default:
iconInfo->cbColorTable = 0;
break;
}
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT16(s, iconInfo->cbBitsMask); /* cbBitsMask (2 bytes) */
Stream_Read_UINT16(s, iconInfo->cbBitsColor); /* cbBitsColor (2 bytes) */
if (Stream_GetRemainingLength(s) < iconInfo->cbBitsMask + iconInfo->cbBitsColor)
return FALSE;
/* bitsMask */
newBitMask = (BYTE*)realloc(iconInfo->bitsMask, iconInfo->cbBitsMask);
if (!newBitMask)
{
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
return FALSE;
}
iconInfo->bitsMask = newBitMask;
Stream_Read(s, iconInfo->bitsMask, iconInfo->cbBitsMask);
/* colorTable */
if (iconInfo->colorTable == NULL)
{
if (iconInfo->cbColorTable)
{
iconInfo->colorTable = (BYTE*)malloc(iconInfo->cbColorTable);
if (!iconInfo->colorTable)
return FALSE;
}
}
else if (iconInfo->cbColorTable)
{
BYTE* new_tab;
new_tab = (BYTE*)realloc(iconInfo->colorTable, iconInfo->cbColorTable);
if (!new_tab)
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
return FALSE;
}
iconInfo->colorTable = new_tab;
}
else
{
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
if (iconInfo->colorTable)
Stream_Read(s, iconInfo->colorTable, iconInfo->cbColorTable);
/* bitsColor */
newBitMask = (BYTE*)realloc(iconInfo->bitsColor, iconInfo->cbBitsColor);
if (!newBitMask)
{
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
return FALSE;
}
iconInfo->bitsColor = newBitMask;
Stream_Read(s, iconInfo->bitsColor, iconInfo->cbBitsColor);
return TRUE;
}
static BOOL update_read_cached_icon_info(wStream* s, CACHED_ICON_INFO* cachedIconInfo)
{
if (Stream_GetRemainingLength(s) < 3)
return FALSE;
Stream_Read_UINT16(s, cachedIconInfo->cacheEntry); /* cacheEntry (2 bytes) */
Stream_Read_UINT8(s, cachedIconInfo->cacheId); /* cacheId (1 byte) */
return TRUE;
}
static BOOL update_read_notify_icon_infotip(wStream* s, NOTIFY_ICON_INFOTIP* notifyIconInfoTip)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, notifyIconInfoTip->timeout); /* timeout (4 bytes) */
Stream_Read_UINT32(s, notifyIconInfoTip->flags); /* infoFlags (4 bytes) */
return rail_read_unicode_string(s, ¬ifyIconInfoTip->text) && /* infoTipText */
rail_read_unicode_string(s, ¬ifyIconInfoTip->title); /* title */
}
static BOOL update_read_window_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_STATE_ORDER* windowState)
{
UINT32 i;
size_t size;
RECTANGLE_16* newRect;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OWNER)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, windowState->ownerWindowId); /* ownerWindowId (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_STYLE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->style); /* style (4 bytes) */
Stream_Read_UINT32(s, windowState->extendedStyle); /* extendedStyle (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_SHOW)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->showState); /* showState (1 byte) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TITLE)
{
if (!rail_read_unicode_string(s, &windowState->titleInfo)) /* titleInfo */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->clientOffsetX); /* clientOffsetX (4 bytes) */
Stream_Read_INT32(s, windowState->clientOffsetY); /* clientOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->clientAreaWidth); /* clientAreaWidth (4 bytes) */
Stream_Read_UINT32(s, windowState->clientAreaHeight); /* clientAreaHeight (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->resizeMarginLeft);
Stream_Read_UINT32(s, windowState->resizeMarginRight);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->resizeMarginTop);
Stream_Read_UINT32(s, windowState->resizeMarginBottom);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->RPContent); /* RPContent (1 byte) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, windowState->rootParentHandle); /* rootParentHandle (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->windowOffsetX); /* windowOffsetX (4 bytes) */
Stream_Read_INT32(s, windowState->windowOffsetY); /* windowOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_INT32(s, windowState->windowClientDeltaX); /* windowClientDeltaX (4 bytes) */
Stream_Read_INT32(s, windowState->windowClientDeltaY); /* windowClientDeltaY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->windowWidth); /* windowWidth (4 bytes) */
Stream_Read_UINT32(s, windowState->windowHeight); /* windowHeight (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, windowState->numWindowRects); /* numWindowRects (2 bytes) */
if (windowState->numWindowRects == 0)
{
return TRUE;
}
size = sizeof(RECTANGLE_16) * windowState->numWindowRects;
newRect = (RECTANGLE_16*)realloc(windowState->windowRects, size);
if (!newRect)
{
free(windowState->windowRects);
windowState->windowRects = NULL;
return FALSE;
}
windowState->windowRects = newRect;
if (Stream_GetRemainingLength(s) < 8 * windowState->numWindowRects)
return FALSE;
/* windowRects */
for (i = 0; i < windowState->numWindowRects; i++)
{
Stream_Read_UINT16(s, windowState->windowRects[i].left); /* left (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].top); /* top (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].right); /* right (2 bytes) */
Stream_Read_UINT16(s, windowState->windowRects[i].bottom); /* bottom (2 bytes) */
}
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
{
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, windowState->visibleOffsetX); /* visibleOffsetX (4 bytes) */
Stream_Read_UINT32(s, windowState->visibleOffsetY); /* visibleOffsetY (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
{
if (Stream_GetRemainingLength(s) < 2)
return FALSE;
Stream_Read_UINT16(s, windowState->numVisibilityRects); /* numVisibilityRects (2 bytes) */
if (windowState->numVisibilityRects != 0)
{
size = sizeof(RECTANGLE_16) * windowState->numVisibilityRects;
newRect = (RECTANGLE_16*)realloc(windowState->visibilityRects, size);
if (!newRect)
{
free(windowState->visibilityRects);
windowState->visibilityRects = NULL;
return FALSE;
}
windowState->visibilityRects = newRect;
if (Stream_GetRemainingLength(s) < windowState->numVisibilityRects * 8)
return FALSE;
/* visibilityRects */
for (i = 0; i < windowState->numVisibilityRects; i++)
{
Stream_Read_UINT16(s, windowState->visibilityRects[i].left); /* left (2 bytes) */
Stream_Read_UINT16(s, windowState->visibilityRects[i].top); /* top (2 bytes) */
Stream_Read_UINT16(s, windowState->visibilityRects[i].right); /* right (2 bytes) */
Stream_Read_UINT16(s,
windowState->visibilityRects[i].bottom); /* bottom (2 bytes) */
}
}
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION)
{
if (!rail_read_unicode_string(s, &windowState->OverlayDescription))
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ICON_OVERLAY_NULL)
{
/* no data to be read here */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->TaskbarButton);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->EnforceServerZOrder);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->AppBarState);
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE)
{
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, windowState->AppBarEdge);
}
return TRUE;
}
static BOOL update_read_window_icon_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_ICON_ORDER* window_icon)
{
WINPR_UNUSED(orderInfo);
window_icon->iconInfo = (ICON_INFO*)calloc(1, sizeof(ICON_INFO));
if (!window_icon->iconInfo)
return FALSE;
return update_read_icon_info(s, window_icon->iconInfo); /* iconInfo (ICON_INFO) */
}
static BOOL update_read_window_cached_icon_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
WINDOW_CACHED_ICON_ORDER* window_cached_icon)
{
WINPR_UNUSED(orderInfo);
return update_read_cached_icon_info(
s, &window_cached_icon->cachedIcon); /* cachedIcon (CACHED_ICON_INFO) */
}
static void update_read_window_delete_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* window deletion event */
}
static BOOL window_order_supported(const rdpSettings* settings, UINT32 fieldFlags)
{
const UINT32 mask = (WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE | WINDOW_ORDER_FIELD_RP_CONTENT |
WINDOW_ORDER_FIELD_ROOT_PARENT);
BOOL dresult;
if (!settings)
return FALSE;
/* See [MS-RDPERP] 2.2.1.1.2 Window List Capability Set */
dresult = settings->AllowUnanouncedOrdersFromServer;
switch (settings->RemoteWndSupportLevel)
{
case WINDOW_LEVEL_SUPPORTED_EX:
return TRUE;
case WINDOW_LEVEL_SUPPORTED:
return ((fieldFlags & mask) == 0) || dresult;
case WINDOW_LEVEL_NOT_SUPPORTED:
return dresult;
default:
return dresult;
}
}
#define DUMP_APPEND(buffer, size, ...) \
do \
{ \
char* b = (buffer); \
size_t s = (size); \
size_t pos = strnlen(b, s); \
_snprintf(&b[pos], s - pos, __VA_ARGS__); \
} while (0)
static void dump_window_state_order(wLog* log, const char* msg, const WINDOW_ORDER_INFO* order,
const WINDOW_STATE_ORDER* state)
{
char buffer[3000] = { 0 };
const size_t bufferSize = sizeof(buffer) - 1;
_snprintf(buffer, bufferSize, "%s windowId=0x%" PRIu32 "", msg, order->windowId);
if (order->fieldFlags & WINDOW_ORDER_FIELD_OWNER)
DUMP_APPEND(buffer, bufferSize, " owner=0x%" PRIx32 "", state->ownerWindowId);
if (order->fieldFlags & WINDOW_ORDER_FIELD_STYLE)
{
DUMP_APPEND(buffer, bufferSize, " [ex]style=<0x%" PRIx32 ", 0x%" PRIx32 "", state->style,
state->extendedStyle);
if (state->style & WS_POPUP)
DUMP_APPEND(buffer, bufferSize, " popup");
if (state->style & WS_VISIBLE)
DUMP_APPEND(buffer, bufferSize, " visible");
if (state->style & WS_THICKFRAME)
DUMP_APPEND(buffer, bufferSize, " thickframe");
if (state->style & WS_BORDER)
DUMP_APPEND(buffer, bufferSize, " border");
if (state->style & WS_CAPTION)
DUMP_APPEND(buffer, bufferSize, " caption");
if (state->extendedStyle & WS_EX_NOACTIVATE)
DUMP_APPEND(buffer, bufferSize, " noactivate");
if (state->extendedStyle & WS_EX_TOOLWINDOW)
DUMP_APPEND(buffer, bufferSize, " toolWindow");
if (state->extendedStyle & WS_EX_TOPMOST)
DUMP_APPEND(buffer, bufferSize, " topMost");
DUMP_APPEND(buffer, bufferSize, ">");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_SHOW)
{
const char* showStr;
switch (state->showState)
{
case 0:
showStr = "hidden";
break;
case 2:
showStr = "minimized";
break;
case 3:
showStr = "maximized";
break;
case 5:
showStr = "current";
break;
default:
showStr = "<unknown>";
break;
}
DUMP_APPEND(buffer, bufferSize, " show=%s", showStr);
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_TITLE)
DUMP_APPEND(buffer, bufferSize, " title");
if (order->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET)
DUMP_APPEND(buffer, bufferSize, " clientOffset=(%" PRId32 ",%" PRId32 ")",
state->clientOffsetX, state->clientOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE)
DUMP_APPEND(buffer, bufferSize, " clientAreaWidth=%" PRIu32 " clientAreaHeight=%" PRIu32 "",
state->clientAreaWidth, state->clientAreaHeight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
DUMP_APPEND(buffer, bufferSize,
" resizeMarginLeft=%" PRIu32 " resizeMarginRight=%" PRIu32 "",
state->resizeMarginLeft, state->resizeMarginRight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
DUMP_APPEND(buffer, bufferSize,
" resizeMarginTop=%" PRIu32 " resizeMarginBottom=%" PRIu32 "",
state->resizeMarginTop, state->resizeMarginBottom);
if (order->fieldFlags & WINDOW_ORDER_FIELD_RP_CONTENT)
DUMP_APPEND(buffer, bufferSize, " rpContent=0x%" PRIx32 "", state->RPContent);
if (order->fieldFlags & WINDOW_ORDER_FIELD_ROOT_PARENT)
DUMP_APPEND(buffer, bufferSize, " rootParent=0x%" PRIx32 "", state->rootParentHandle);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
DUMP_APPEND(buffer, bufferSize, " windowOffset=(%" PRId32 ",%" PRId32 ")",
state->windowOffsetX, state->windowOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA)
DUMP_APPEND(buffer, bufferSize, " windowClientDelta=(%" PRId32 ",%" PRId32 ")",
state->windowClientDeltaX, state->windowClientDeltaY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
DUMP_APPEND(buffer, bufferSize, " windowWidth=%" PRIu32 " windowHeight=%" PRIu32 "",
state->windowWidth, state->windowHeight);
if (order->fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " windowRects=(");
for (i = 0; i < state->numWindowRects; i++)
{
DUMP_APPEND(buffer, bufferSize, "(%" PRIu16 ",%" PRIu16 ",%" PRIu16 ",%" PRIu16 ")",
state->windowRects[i].left, state->windowRects[i].top,
state->windowRects[i].right, state->windowRects[i].bottom);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
DUMP_APPEND(buffer, bufferSize, " visibleOffset=(%" PRId32 ",%" PRId32 ")",
state->visibleOffsetX, state->visibleOffsetY);
if (order->fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " visibilityRects=(");
for (i = 0; i < state->numVisibilityRects; i++)
{
DUMP_APPEND(buffer, bufferSize, "(%" PRIu16 ",%" PRIu16 ",%" PRIu16 ",%" PRIu16 ")",
state->visibilityRects[i].left, state->visibilityRects[i].top,
state->visibilityRects[i].right, state->visibilityRects[i].bottom);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
if (order->fieldFlags & WINDOW_ORDER_FIELD_OVERLAY_DESCRIPTION)
DUMP_APPEND(buffer, bufferSize, " overlayDescr");
if (order->fieldFlags & WINDOW_ORDER_FIELD_ICON_OVERLAY_NULL)
DUMP_APPEND(buffer, bufferSize, " iconOverlayNull");
if (order->fieldFlags & WINDOW_ORDER_FIELD_TASKBAR_BUTTON)
DUMP_APPEND(buffer, bufferSize, " taskBarButton=0x%" PRIx8 "", state->TaskbarButton);
if (order->fieldFlags & WINDOW_ORDER_FIELD_ENFORCE_SERVER_ZORDER)
DUMP_APPEND(buffer, bufferSize, " enforceServerZOrder=0x%" PRIx8 "",
state->EnforceServerZOrder);
if (order->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_STATE)
DUMP_APPEND(buffer, bufferSize, " appBarState=0x%" PRIx8 "", state->AppBarState);
if (order->fieldFlags & WINDOW_ORDER_FIELD_APPBAR_EDGE)
{
const char* appBarEdgeStr;
switch (state->AppBarEdge)
{
case 0:
appBarEdgeStr = "left";
break;
case 1:
appBarEdgeStr = "top";
break;
case 2:
appBarEdgeStr = "right";
break;
case 3:
appBarEdgeStr = "bottom";
break;
default:
appBarEdgeStr = "<unknown>";
break;
}
DUMP_APPEND(buffer, bufferSize, " appBarEdge=%s", appBarEdgeStr);
}
WLog_Print(log, WLOG_DEBUG, buffer);
}
static BOOL update_recv_window_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, orderInfo->windowId); /* windowId (4 bytes) */
if (orderInfo->fieldFlags & WINDOW_ORDER_ICON)
{
WINDOW_ICON_ORDER window_icon = { 0 };
result = update_read_window_icon_order(s, orderInfo, &window_icon);
if (result)
{
WLog_Print(update->log, WLOG_DEBUG, "WindowIcon windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowIcon, result, context, orderInfo, &window_icon);
}
update_free_window_icon_info(window_icon.iconInfo);
free(window_icon.iconInfo);
}
else if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON)
{
WINDOW_CACHED_ICON_ORDER window_cached_icon = { 0 };
result = update_read_window_cached_icon_order(s, orderInfo, &window_cached_icon);
if (result)
{
WLog_Print(update->log, WLOG_DEBUG, "WindowCachedIcon windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowCachedIcon, result, context, orderInfo, &window_cached_icon);
}
}
else if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_DELETED)
{
update_read_window_delete_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "WindowDelete windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->WindowDelete, result, context, orderInfo);
}
else
{
WINDOW_STATE_ORDER windowState = { 0 };
result = update_read_window_state_order(s, orderInfo, &windowState);
if (result)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW)
{
dump_window_state_order(update->log, "WindowCreate", orderInfo, &windowState);
IFCALLRET(window->WindowCreate, result, context, orderInfo, &windowState);
}
else
{
dump_window_state_order(update->log, "WindowUpdate", orderInfo, &windowState);
IFCALLRET(window->WindowUpdate, result, context, orderInfo, &windowState);
}
update_free_window_state(&windowState);
}
}
return result;
}
static void update_notify_icon_state_order_free(NOTIFY_ICON_STATE_ORDER* notify)
{
free(notify->toolTip.string);
free(notify->infoTip.text.string);
free(notify->infoTip.title.string);
update_free_window_icon_info(¬ify->icon);
memset(notify, 0, sizeof(NOTIFY_ICON_STATE_ORDER));
}
static BOOL update_read_notification_icon_state_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
NOTIFY_ICON_STATE_ORDER* notify_icon_state)
{
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_VERSION)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, notify_icon_state->version); /* version (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_TIP)
{
if (!rail_read_unicode_string(s,
¬ify_icon_state->toolTip)) /* toolTip (UNICODE_STRING) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_INFO_TIP)
{
if (!update_read_notify_icon_infotip(
s, ¬ify_icon_state->infoTip)) /* infoTip (NOTIFY_ICON_INFOTIP) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_NOTIFY_STATE)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, notify_icon_state->state); /* state (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_ICON)
{
if (!update_read_icon_info(s, ¬ify_icon_state->icon)) /* icon (ICON_INFO) */
return FALSE;
}
if (orderInfo->fieldFlags & WINDOW_ORDER_CACHED_ICON)
{
if (!update_read_cached_icon_info(
s, ¬ify_icon_state->cachedIcon)) /* cachedIcon (CACHED_ICON_INFO) */
return FALSE;
}
return TRUE;
}
static void update_read_notification_icon_delete_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* notification icon deletion event */
}
static BOOL update_recv_notification_icon_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (Stream_GetRemainingLength(s) < 8)
return FALSE;
Stream_Read_UINT32(s, orderInfo->windowId); /* windowId (4 bytes) */
Stream_Read_UINT32(s, orderInfo->notifyIconId); /* notifyIconId (4 bytes) */
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_DELETED)
{
update_read_notification_icon_delete_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconDelete");
IFCALLRET(window->NotifyIconDelete, result, context, orderInfo);
}
else
{
NOTIFY_ICON_STATE_ORDER notify_icon_state = { 0 };
result = update_read_notification_icon_state_order(s, orderInfo, ¬ify_icon_state);
if (!result)
goto fail;
if (orderInfo->fieldFlags & WINDOW_ORDER_STATE_NEW)
{
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconCreate");
IFCALLRET(window->NotifyIconCreate, result, context, orderInfo, ¬ify_icon_state);
}
else
{
WLog_Print(update->log, WLOG_DEBUG, "NotifyIconUpdate");
IFCALLRET(window->NotifyIconUpdate, result, context, orderInfo, ¬ify_icon_state);
}
fail:
update_notify_icon_state_order_free(¬ify_icon_state);
}
return result;
}
static BOOL update_read_desktop_actively_monitored_order(wStream* s, WINDOW_ORDER_INFO* orderInfo,
MONITORED_DESKTOP_ORDER* monitored_desktop)
{
int i;
int size;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
{
if (Stream_GetRemainingLength(s) < 4)
return FALSE;
Stream_Read_UINT32(s, monitored_desktop->activeWindowId); /* activeWindowId (4 bytes) */
}
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
UINT32* newid;
if (Stream_GetRemainingLength(s) < 1)
return FALSE;
Stream_Read_UINT8(s, monitored_desktop->numWindowIds); /* numWindowIds (1 byte) */
if (Stream_GetRemainingLength(s) < 4 * monitored_desktop->numWindowIds)
return FALSE;
if (monitored_desktop->numWindowIds > 0)
{
size = sizeof(UINT32) * monitored_desktop->numWindowIds;
newid = (UINT32*)realloc(monitored_desktop->windowIds, size);
if (!newid)
{
free(monitored_desktop->windowIds);
monitored_desktop->windowIds = NULL;
return FALSE;
}
monitored_desktop->windowIds = newid;
/* windowIds */
for (i = 0; i < (int)monitored_desktop->numWindowIds; i++)
{
Stream_Read_UINT32(s, monitored_desktop->windowIds[i]);
}
}
}
return TRUE;
}
static void update_read_desktop_non_monitored_order(wStream* s, WINDOW_ORDER_INFO* orderInfo)
{
/* non-monitored desktop notification event */
}
static void dump_monitored_desktop(wLog* log, const char* msg, const WINDOW_ORDER_INFO* orderInfo,
const MONITORED_DESKTOP_ORDER* monitored)
{
char buffer[1000] = { 0 };
const size_t bufferSize = sizeof(buffer) - 1;
DUMP_APPEND(buffer, bufferSize, "%s", msg);
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
DUMP_APPEND(buffer, bufferSize, " activeWindowId=0x%" PRIx32 "", monitored->activeWindowId);
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
{
UINT32 i;
DUMP_APPEND(buffer, bufferSize, " windows=(");
for (i = 0; i < monitored->numWindowIds; i++)
{
DUMP_APPEND(buffer, bufferSize, "0x%" PRIx32 ",", monitored->windowIds[i]);
}
DUMP_APPEND(buffer, bufferSize, ")");
}
WLog_Print(log, WLOG_DEBUG, buffer);
}
static BOOL update_recv_desktop_info_order(rdpUpdate* update, wStream* s,
WINDOW_ORDER_INFO* orderInfo)
{
rdpContext* context = update->context;
rdpWindowUpdate* window = update->window;
BOOL result = TRUE;
if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_NONE)
{
update_read_desktop_non_monitored_order(s, orderInfo);
WLog_Print(update->log, WLOG_DEBUG, "NonMonitoredDesktop, windowId=0x%" PRIx32 "",
orderInfo->windowId);
IFCALLRET(window->NonMonitoredDesktop, result, context, orderInfo);
}
else
{
MONITORED_DESKTOP_ORDER monitored_desktop = { 0 };
result = update_read_desktop_actively_monitored_order(s, orderInfo, &monitored_desktop);
if (result)
{
dump_monitored_desktop(update->log, "ActivelyMonitoredDesktop", orderInfo,
&monitored_desktop);
IFCALLRET(window->MonitoredDesktop, result, context, orderInfo, &monitored_desktop);
}
free(monitored_desktop.windowIds);
}
return result;
}
void update_free_window_icon_info(ICON_INFO* iconInfo)
{
if (!iconInfo)
return;
free(iconInfo->bitsColor);
iconInfo->bitsColor = NULL;
free(iconInfo->bitsMask);
iconInfo->bitsMask = NULL;
free(iconInfo->colorTable);
iconInfo->colorTable = NULL;
}
BOOL update_recv_altsec_window_order(rdpUpdate* update, wStream* s)
{
BOOL rc = TRUE;
size_t remaining;
UINT16 orderSize;
WINDOW_ORDER_INFO orderInfo = { 0 };
remaining = Stream_GetRemainingLength(s);
if (remaining < 6)
{
WLog_Print(update->log, WLOG_ERROR, "Stream short");
return FALSE;
}
Stream_Read_UINT16(s, orderSize); /* orderSize (2 bytes) */
Stream_Read_UINT32(s, orderInfo.fieldFlags); /* FieldsPresentFlags (4 bytes) */
if (remaining + 1 < orderSize)
{
WLog_Print(update->log, WLOG_ERROR, "Stream short orderSize");
return FALSE;
}
if (!window_order_supported(update->context->settings, orderInfo.fieldFlags))
{
WLog_INFO(TAG, "Window order %08" PRIx32 " not supported!", orderInfo.fieldFlags);
return FALSE;
}
if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_WINDOW)
rc = update_recv_window_info_order(update, s, &orderInfo);
else if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_NOTIFY)
rc = update_recv_notification_icon_info_order(update, s, &orderInfo);
else if (orderInfo.fieldFlags & WINDOW_ORDER_TYPE_DESKTOP)
rc = update_recv_desktop_info_order(update, s, &orderInfo);
if (!rc)
WLog_Print(update->log, WLOG_ERROR, "windoworder flags %08" PRIx32 " failed",
orderInfo.fieldFlags);
return rc;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3905_0 |
crossvul-cpp_data_good_330_0 | /*
* Copyright (C) Arnaldo Carvalho de Melo 2004
* Copyright (C) Ian McDonald 2005
* Copyright (C) Yoshifumi Nishida 2005
*
* This software may be distributed either under the terms of the
* BSD-style license that accompanies tcpdump or the GNU GPL version 2
*/
/* \summary: Datagram Congestion Control Protocol (DCCP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip.h"
#include "ip6.h"
#include "ipproto.h"
/* RFC4340: Datagram Congestion Control Protocol (DCCP) */
/**
* struct dccp_hdr - generic part of DCCP packet header, with a 24-bit
* sequence number
*
* @dccph_sport - Relevant port on the endpoint that sent this packet
* @dccph_dport - Relevant port on the other endpoint
* @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words
* @dccph_ccval - Used by the HC-Sender CCID
* @dccph_cscov - Parts of the packet that are covered by the Checksum field
* @dccph_checksum - Internet checksum, depends on dccph_cscov
* @dccph_x - 0 = 24 bit sequence number, 1 = 48
* @dccph_type - packet type, see DCCP_PKT_ prefixed macros
* @dccph_seq - 24-bit sequence number
*/
struct dccp_hdr {
uint16_t dccph_sport,
dccph_dport;
uint8_t dccph_doff;
uint8_t dccph_ccval_cscov;
uint16_t dccph_checksum;
uint8_t dccph_xtr;
uint8_t dccph_seq[3];
} UNALIGNED;
/**
* struct dccp_hdr_ext - generic part of DCCP packet header, with a 48-bit
* sequence number
*
* @dccph_sport - Relevant port on the endpoint that sent this packet
* @dccph_dport - Relevant port on the other endpoint
* @dccph_doff - Data Offset from the start of the DCCP header, in 32-bit words
* @dccph_ccval - Used by the HC-Sender CCID
* @dccph_cscov - Parts of the packet that are covered by the Checksum field
* @dccph_checksum - Internet checksum, depends on dccph_cscov
* @dccph_x - 0 = 24 bit sequence number, 1 = 48
* @dccph_type - packet type, see DCCP_PKT_ prefixed macros
* @dccph_seq - 48-bit sequence number
*/
struct dccp_hdr_ext {
uint16_t dccph_sport,
dccph_dport;
uint8_t dccph_doff;
uint8_t dccph_ccval_cscov;
uint16_t dccph_checksum;
uint8_t dccph_xtr;
uint8_t reserved;
uint8_t dccph_seq[6];
} UNALIGNED;
#define DCCPH_CCVAL(dh) (((dh)->dccph_ccval_cscov >> 4) & 0xF)
#define DCCPH_CSCOV(dh) (((dh)->dccph_ccval_cscov) & 0xF)
#define DCCPH_X(dh) ((dh)->dccph_xtr & 1)
#define DCCPH_TYPE(dh) (((dh)->dccph_xtr >> 1) & 0xF)
/**
* struct dccp_hdr_request - Conection initiation request header
*
* @dccph_req_service - Service to which the client app wants to connect
*/
struct dccp_hdr_request {
uint32_t dccph_req_service;
} UNALIGNED;
/**
* struct dccp_hdr_response - Conection initiation response header
*
* @dccph_resp_ack - 48 bit ack number, contains GSR
* @dccph_resp_service - Echoes the Service Code on a received DCCP-Request
*/
struct dccp_hdr_response {
uint8_t dccph_resp_ack[8]; /* always 8 bytes */
uint32_t dccph_resp_service;
} UNALIGNED;
/**
* struct dccp_hdr_reset - Unconditionally shut down a connection
*
* @dccph_resp_ack - 48 bit ack number
* @dccph_reset_service - Echoes the Service Code on a received DCCP-Request
*/
struct dccp_hdr_reset {
uint8_t dccph_reset_ack[8]; /* always 8 bytes */
uint8_t dccph_reset_code,
dccph_reset_data[3];
} UNALIGNED;
enum dccp_pkt_type {
DCCP_PKT_REQUEST = 0,
DCCP_PKT_RESPONSE,
DCCP_PKT_DATA,
DCCP_PKT_ACK,
DCCP_PKT_DATAACK,
DCCP_PKT_CLOSEREQ,
DCCP_PKT_CLOSE,
DCCP_PKT_RESET,
DCCP_PKT_SYNC,
DCCP_PKT_SYNCACK
};
static const struct tok dccp_pkt_type_str[] = {
{ DCCP_PKT_REQUEST, "DCCP-Request" },
{ DCCP_PKT_RESPONSE, "DCCP-Response" },
{ DCCP_PKT_DATA, "DCCP-Data" },
{ DCCP_PKT_ACK, "DCCP-Ack" },
{ DCCP_PKT_DATAACK, "DCCP-DataAck" },
{ DCCP_PKT_CLOSEREQ, "DCCP-CloseReq" },
{ DCCP_PKT_CLOSE, "DCCP-Close" },
{ DCCP_PKT_RESET, "DCCP-Reset" },
{ DCCP_PKT_SYNC, "DCCP-Sync" },
{ DCCP_PKT_SYNCACK, "DCCP-SyncAck" },
{ 0, NULL}
};
enum dccp_reset_codes {
DCCP_RESET_CODE_UNSPECIFIED = 0,
DCCP_RESET_CODE_CLOSED,
DCCP_RESET_CODE_ABORTED,
DCCP_RESET_CODE_NO_CONNECTION,
DCCP_RESET_CODE_PACKET_ERROR,
DCCP_RESET_CODE_OPTION_ERROR,
DCCP_RESET_CODE_MANDATORY_ERROR,
DCCP_RESET_CODE_CONNECTION_REFUSED,
DCCP_RESET_CODE_BAD_SERVICE_CODE,
DCCP_RESET_CODE_TOO_BUSY,
DCCP_RESET_CODE_BAD_INIT_COOKIE,
DCCP_RESET_CODE_AGGRESSION_PENALTY,
__DCCP_RESET_CODE_LAST
};
static const char tstr[] = "[|dccp]";
static const char *dccp_reset_codes[] = {
"unspecified",
"closed",
"aborted",
"no_connection",
"packet_error",
"option_error",
"mandatory_error",
"connection_refused",
"bad_service_code",
"too_busy",
"bad_init_cookie",
"aggression_penalty",
};
static const char *dccp_feature_nums[] = {
"reserved",
"ccid",
"allow_short_seqno",
"sequence_window",
"ecn_incapable",
"ack_ratio",
"send_ack_vector",
"send_ndp_count",
"minimum checksum coverage",
"check data checksum",
};
static inline u_int dccp_csum_coverage(const struct dccp_hdr* dh, u_int len)
{
u_int cov;
if (DCCPH_CSCOV(dh) == 0)
return len;
cov = (dh->dccph_doff + DCCPH_CSCOV(dh) - 1) * sizeof(uint32_t);
return (cov > len)? len : cov;
}
static int dccp_cksum(netdissect_options *ndo, const struct ip *ip,
const struct dccp_hdr *dh, u_int len)
{
return nextproto4_cksum(ndo, ip, (const uint8_t *)(const void *)dh, len,
dccp_csum_coverage(dh, len), IPPROTO_DCCP);
}
static int dccp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6,
const struct dccp_hdr *dh, u_int len)
{
return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)dh, len,
dccp_csum_coverage(dh, len), IPPROTO_DCCP);
}
static const char *dccp_reset_code(uint8_t code)
{
if (code >= __DCCP_RESET_CODE_LAST)
return "invalid";
return dccp_reset_codes[code];
}
static uint64_t dccp_seqno(const u_char *bp)
{
const struct dccp_hdr *dh = (const struct dccp_hdr *)bp;
uint64_t seqno;
if (DCCPH_X(dh) != 0) {
const struct dccp_hdr_ext *dhx = (const struct dccp_hdr_ext *)bp;
seqno = EXTRACT_48BITS(dhx->dccph_seq);
} else {
seqno = EXTRACT_24BITS(dh->dccph_seq);
}
return seqno;
}
static inline unsigned int dccp_basic_hdr_len(const struct dccp_hdr *dh)
{
return DCCPH_X(dh) ? sizeof(struct dccp_hdr_ext) : sizeof(struct dccp_hdr);
}
static void dccp_print_ack_no(netdissect_options *ndo, const u_char *bp)
{
const struct dccp_hdr *dh = (const struct dccp_hdr *)bp;
const u_char *ackp = bp + dccp_basic_hdr_len(dh);
uint64_t ackno;
if (DCCPH_X(dh) != 0) {
ND_TCHECK2(*ackp, 8);
ackno = EXTRACT_48BITS(ackp + 2);
} else {
ND_TCHECK2(*ackp, 4);
ackno = EXTRACT_24BITS(ackp + 1);
}
ND_PRINT((ndo, "(ack=%" PRIu64 ") ", ackno));
trunc:
return;
}
static int dccp_print_option(netdissect_options *, const u_char *, u_int);
/**
* dccp_print - show dccp packet
* @bp - beginning of dccp packet
* @data2 - beginning of enclosing
* @len - lenght of ip packet
*/
void dccp_print(netdissect_options *ndo, const u_char *bp, const u_char *data2,
u_int len)
{
const struct dccp_hdr *dh;
const struct ip *ip;
const struct ip6_hdr *ip6;
const u_char *cp;
u_short sport, dport;
u_int hlen;
u_int fixed_hdrlen;
uint8_t dccph_type;
dh = (const struct dccp_hdr *)bp;
ip = (const struct ip *)data2;
if (IP_V(ip) == 6)
ip6 = (const struct ip6_hdr *)data2;
else
ip6 = NULL;
/* make sure we have enough data to look at the X bit */
cp = (const u_char *)(dh + 1);
if (cp > ndo->ndo_snapend) {
ND_PRINT((ndo, "[Invalid packet|dccp]"));
return;
}
if (len < sizeof(struct dccp_hdr)) {
ND_PRINT((ndo, "truncated-dccp - %u bytes missing!",
len - (u_int)sizeof(struct dccp_hdr)));
return;
}
/* get the length of the generic header */
fixed_hdrlen = dccp_basic_hdr_len(dh);
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-dccp - %u bytes missing!",
len - fixed_hdrlen));
return;
}
ND_TCHECK2(*dh, fixed_hdrlen);
sport = EXTRACT_16BITS(&dh->dccph_sport);
dport = EXTRACT_16BITS(&dh->dccph_dport);
hlen = dh->dccph_doff * 4;
if (ip6) {
ND_PRINT((ndo, "%s.%d > %s.%d: ",
ip6addr_string(ndo, &ip6->ip6_src), sport,
ip6addr_string(ndo, &ip6->ip6_dst), dport));
} else {
ND_PRINT((ndo, "%s.%d > %s.%d: ",
ipaddr_string(ndo, &ip->ip_src), sport,
ipaddr_string(ndo, &ip->ip_dst), dport));
}
ND_PRINT((ndo, "DCCP"));
if (ndo->ndo_qflag) {
ND_PRINT((ndo, " %d", len - hlen));
if (hlen > len) {
ND_PRINT((ndo, " [bad hdr length %u - too long, > %u]",
hlen, len));
}
return;
}
/* other variables in generic header */
if (ndo->ndo_vflag) {
ND_PRINT((ndo, " (CCVal %d, CsCov %d, ", DCCPH_CCVAL(dh), DCCPH_CSCOV(dh)));
}
/* checksum calculation */
if (ndo->ndo_vflag && ND_TTEST2(bp[0], len)) {
uint16_t sum = 0, dccp_sum;
dccp_sum = EXTRACT_16BITS(&dh->dccph_checksum);
ND_PRINT((ndo, "cksum 0x%04x ", dccp_sum));
if (IP_V(ip) == 4)
sum = dccp_cksum(ndo, ip, dh, len);
else if (IP_V(ip) == 6)
sum = dccp6_cksum(ndo, ip6, dh, len);
if (sum != 0)
ND_PRINT((ndo, "(incorrect -> 0x%04x)",in_cksum_shouldbe(dccp_sum, sum)));
else
ND_PRINT((ndo, "(correct)"));
}
if (ndo->ndo_vflag)
ND_PRINT((ndo, ")"));
ND_PRINT((ndo, " "));
dccph_type = DCCPH_TYPE(dh);
switch (dccph_type) {
case DCCP_PKT_REQUEST: {
const struct dccp_hdr_request *dhr =
(const struct dccp_hdr_request *)(bp + fixed_hdrlen);
fixed_hdrlen += 4;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_TCHECK(*dhr);
ND_PRINT((ndo, "%s (service=%d) ",
tok2str(dccp_pkt_type_str, "", dccph_type),
EXTRACT_32BITS(&dhr->dccph_req_service)));
break;
}
case DCCP_PKT_RESPONSE: {
const struct dccp_hdr_response *dhr =
(const struct dccp_hdr_response *)(bp + fixed_hdrlen);
fixed_hdrlen += 12;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_TCHECK(*dhr);
ND_PRINT((ndo, "%s (service=%d) ",
tok2str(dccp_pkt_type_str, "", dccph_type),
EXTRACT_32BITS(&dhr->dccph_resp_service)));
break;
}
case DCCP_PKT_DATA:
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
case DCCP_PKT_ACK: {
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
}
case DCCP_PKT_DATAACK: {
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
}
case DCCP_PKT_CLOSEREQ:
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
case DCCP_PKT_CLOSE:
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
case DCCP_PKT_RESET: {
const struct dccp_hdr_reset *dhr =
(const struct dccp_hdr_reset *)(bp + fixed_hdrlen);
fixed_hdrlen += 12;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_TCHECK(*dhr);
ND_PRINT((ndo, "%s (code=%s) ",
tok2str(dccp_pkt_type_str, "", dccph_type),
dccp_reset_code(dhr->dccph_reset_code)));
break;
}
case DCCP_PKT_SYNC:
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
case DCCP_PKT_SYNCACK:
fixed_hdrlen += 8;
if (len < fixed_hdrlen) {
ND_PRINT((ndo, "truncated-%s - %u bytes missing!",
tok2str(dccp_pkt_type_str, "", dccph_type),
len - fixed_hdrlen));
return;
}
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "", dccph_type)));
break;
default:
ND_PRINT((ndo, "%s ", tok2str(dccp_pkt_type_str, "unknown-type-%u", dccph_type)));
break;
}
if ((DCCPH_TYPE(dh) != DCCP_PKT_DATA) &&
(DCCPH_TYPE(dh) != DCCP_PKT_REQUEST))
dccp_print_ack_no(ndo, bp);
if (ndo->ndo_vflag < 2)
return;
ND_PRINT((ndo, "seq %" PRIu64, dccp_seqno(bp)));
/* process options */
if (hlen > fixed_hdrlen){
u_int optlen;
cp = bp + fixed_hdrlen;
ND_PRINT((ndo, " <"));
hlen -= fixed_hdrlen;
while(1){
optlen = dccp_print_option(ndo, cp, hlen);
if (!optlen)
break;
if (hlen <= optlen)
break;
hlen -= optlen;
cp += optlen;
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, ">"));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
return;
}
static const struct tok dccp_option_values[] = {
{ 0, "nop" },
{ 1, "mandatory" },
{ 2, "slowreceiver" },
{ 32, "change_l" },
{ 33, "confirm_l" },
{ 34, "change_r" },
{ 35, "confirm_r" },
{ 36, "initcookie" },
{ 37, "ndp_count" },
{ 38, "ack_vector0" },
{ 39, "ack_vector1" },
{ 40, "data_dropped" },
{ 41, "timestamp" },
{ 42, "timestamp_echo" },
{ 43, "elapsed_time" },
{ 44, "data_checksum" },
{ 0, NULL }
};
static int
dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen)
{
uint8_t optlen, i;
ND_TCHECK(*option);
if (*option >= 32) {
ND_TCHECK(*(option+1));
optlen = *(option +1);
if (optlen < 2) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen too short", *option));
else
ND_PRINT((ndo, "%s optlen too short",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
} else
optlen = 1;
if (hlen < optlen) {
if (*option >= 128)
ND_PRINT((ndo, "CCID option %u optlen goes past header length",
*option));
else
ND_PRINT((ndo, "%s optlen goes past header length",
tok2str(dccp_option_values, "Option %u", *option)));
return 0;
}
ND_TCHECK2(*option, optlen);
if (*option >= 128) {
ND_PRINT((ndo, "CCID option %d", *option));
switch (optlen) {
case 4:
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
break;
case 6:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
break;
default:
break;
}
} else {
ND_PRINT((ndo, "%s", tok2str(dccp_option_values, "Option %u", *option)));
switch (*option) {
case 32:
case 33:
case 34:
case 35:
if (optlen < 3) {
ND_PRINT((ndo, " optlen too short"));
return optlen;
}
if (*(option + 2) < 10){
ND_PRINT((ndo, " %s", dccp_feature_nums[*(option + 2)]));
for (i = 0; i < optlen - 3; i++)
ND_PRINT((ndo, " %d", *(option + 3 + i)));
}
break;
case 36:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 37:
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, " %d", *(option + 2 + i)));
break;
case 38:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 39:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 40:
if (optlen > 2) {
ND_PRINT((ndo, " 0x"));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
case 41:
/*
* 13.1. Timestamp Option
*
* +--------+--------+--------+--------+--------+--------+
* |00101001|00000110| Timestamp Value |
* +--------+--------+--------+--------+--------+--------+
* Type=41 Length=6
*/
if (optlen == 6)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else
ND_PRINT((ndo, " [optlen != 6]"));
break;
case 42:
/*
* 13.3. Timestamp Echo Option
*
* +--------+--------+--------+--------+--------+--------+
* |00101010|00000110| Timestamp Echo |
* +--------+--------+--------+--------+--------+--------+
* Type=42 Len=6
*
* +--------+--------+------- ... -------+--------+--------+
* |00101010|00001000| Timestamp Echo | Elapsed Time |
* +--------+--------+------- ... -------+--------+--------+
* Type=42 Len=8 (4 bytes)
*
* +--------+--------+------- ... -------+------- ... -------+
* |00101010|00001010| Timestamp Echo | Elapsed Time |
* +--------+--------+------- ... -------+------- ... -------+
* Type=42 Len=10 (4 bytes) (4 bytes)
*/
switch (optlen) {
case 6:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
break;
case 8:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
ND_PRINT((ndo, " (elapsed time %u)", EXTRACT_16BITS(option + 6)));
break;
case 10:
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
ND_PRINT((ndo, " (elapsed time %u)", EXTRACT_32BITS(option + 6)));
break;
default:
ND_PRINT((ndo, " [optlen != 6 or 8 or 10]"));
break;
}
break;
case 43:
if (optlen == 6)
ND_PRINT((ndo, " %u", EXTRACT_32BITS(option + 2)));
else if (optlen == 4)
ND_PRINT((ndo, " %u", EXTRACT_16BITS(option + 2)));
else
ND_PRINT((ndo, " [optlen != 4 or 6]"));
break;
case 44:
if (optlen > 2) {
ND_PRINT((ndo, " "));
for (i = 0; i < optlen - 2; i++)
ND_PRINT((ndo, "%02x", *(option + 2 + i)));
}
break;
}
}
return optlen;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_330_0 |
crossvul-cpp_data_good_142_0 | /* radare - LGPL - Copyright 2011-2018 - pancake, Roc Valles, condret, killabyte */
#if 0
http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf
https://en.wikipedia.org/wiki/Atmel_AVR_instruction_set
#endif
#include <string.h>
#include <r_types.h>
#include <r_util.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
static RDESContext desctx;
typedef struct _cpu_const_tag {
const char *const key;
ut8 type;
ut32 value;
ut8 size;
} CPU_CONST;
#define CPU_CONST_NONE 0
#define CPU_CONST_PARAM 1
#define CPU_CONST_REG 2
typedef struct _cpu_model_tag {
const char *const model;
int pc;
char *inherit;
struct _cpu_model_tag *inherit_cpu_p;
CPU_CONST *consts[10];
} CPU_MODEL;
typedef void (*inst_handler_t) (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu);
typedef struct _opcodes_tag_ {
const char *const name;
int mask;
int selector;
inst_handler_t handler;
int cycles;
int size;
ut64 type;
} OPCODE_DESC;
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu);
#define CPU_MODEL_DECL(model, pc, consts) \
{ \
model, \
pc, \
consts \
}
#define MASK(bits) ((bits) == 32 ? 0xffffffff : (~((~((ut32) 0)) << (bits))))
#define CPU_PC_MASK(cpu) MASK((cpu)->pc)
#define CPU_PC_SIZE(cpu) ((((cpu)->pc) >> 3) + ((((cpu)->pc) & 0x07) ? 1 : 0))
#define INST_HANDLER(OPCODE_NAME) static void _inst__ ## OPCODE_NAME (RAnal *anal, RAnalOp *op, const ut8 *buf, int len, int *fail, CPU_MODEL *cpu)
#define INST_DECL(OP, M, SL, C, SZ, T) { #OP, (M), (SL), _inst__ ## OP, (C), (SZ), R_ANAL_OP_TYPE_ ## T }
#define INST_LAST { "unknown", 0, 0, (void *) 0, 2, 1, R_ANAL_OP_TYPE_UNK }
#define INST_CALL(OPCODE_NAME) _inst__ ## OPCODE_NAME (anal, op, buf, len, fail, cpu)
#define INST_INVALID { *fail = 1; return; }
#define INST_ASSERT(x) { if (!(x)) { INST_INVALID; } }
#define ESIL_A(e, ...) r_strbuf_appendf (&op->esil, e, ##__VA_ARGS__)
#define STR_BEGINS(in, s) strncasecmp (in, s, strlen (s))
// Following IO definitions are valid for:
// ATmega8
// ATmega88
CPU_CONST cpu_reg_common[] = {
{ "spl", CPU_CONST_REG, 0x3d, sizeof (ut8) },
{ "sph", CPU_CONST_REG, 0x3e, sizeof (ut8) },
{ "sreg", CPU_CONST_REG, 0x3f, sizeof (ut8) },
{ "spmcsr", CPU_CONST_REG, 0x37, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_common[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x40, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x60, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 1024, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_m640_m1280m_m1281_m2560_m2561[] = {
{ "eeprom_size", CPU_CONST_PARAM, 512, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1ff, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x200, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_memsize_xmega128a4u[] = {
{ "eeprom_size", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "io_size", CPU_CONST_PARAM, 0x1000, sizeof (ut32) },
{ "sram_start", CPU_CONST_PARAM, 0x800, sizeof (ut32) },
{ "sram_size", CPU_CONST_PARAM, 0x2000, sizeof (ut32) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_5_bits[] = {
{ "page_size", CPU_CONST_PARAM, 5, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_CONST cpu_pagesize_7_bits[] = {
{ "page_size", CPU_CONST_PARAM, 7, sizeof (ut8) },
{ NULL, 0, 0, 0 },
};
CPU_MODEL cpu_models[] = {
{ .model = "ATmega640", .pc = 15,
.consts = {
cpu_reg_common,
cpu_memsize_m640_m1280m_m1281_m2560_m2561,
cpu_pagesize_7_bits,
NULL
},
},
{
.model = "ATxmega128a4u", .pc = 17,
.consts = {
cpu_reg_common,
cpu_memsize_xmega128a4u,
cpu_pagesize_7_bits,
NULL
}
},
{ .model = "ATmega1280", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega1281", .pc = 16, .inherit = "ATmega640" },
{ .model = "ATmega2560", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega2561", .pc = 17, .inherit = "ATmega640" },
{ .model = "ATmega88", .pc = 8, .inherit = "ATmega8" },
// CPU_MODEL_DECL ("ATmega168", 13, 512, 512),
// last model is the default AVR - ATmega8 forever!
{
.model = "ATmega8", .pc = 13,
.consts = {
cpu_reg_common,
cpu_memsize_common,
cpu_pagesize_5_bits,
NULL
}
},
};
static CPU_MODEL *get_cpu_model(char *model);
static CPU_MODEL *__get_cpu_model_recursive(char *model) {
CPU_MODEL *cpu = NULL;
for (cpu = cpu_models; cpu < cpu_models + ((sizeof (cpu_models) / sizeof (CPU_MODEL))) - 1; cpu++) {
if (!strcasecmp (model, cpu->model)) {
break;
}
}
// fix inheritance tree
if (cpu->inherit && !cpu->inherit_cpu_p) {
cpu->inherit_cpu_p = get_cpu_model (cpu->inherit);
if (!cpu->inherit_cpu_p) {
eprintf ("ERROR: Cannot inherit from unknown CPU model '%s'.\n", cpu->inherit);
}
}
return cpu;
}
static CPU_MODEL *get_cpu_model(char *model) {
static CPU_MODEL *cpu = NULL;
// cached value?
if (cpu && !strcasecmp (model, cpu->model))
return cpu;
// do the real search
cpu = __get_cpu_model_recursive (model);
return cpu;
}
static ut32 const_get_value(CPU_CONST *c) {
return c ? MASK (c->size * 8) & c->value : 0;
}
static CPU_CONST *const_by_name(CPU_MODEL *cpu, int type, char *c) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem->key; citem++) {
if (!strcmp (c, citem->key)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_name (cpu->inherit_cpu_p, type, c);
eprintf ("ERROR: CONSTANT key[%s] NOT FOUND.\n", c);
return NULL;
}
static int __esil_pop_argument(RAnalEsil *esil, ut64 *v) {
char *t = r_anal_esil_pop (esil);
if (!t || !r_anal_esil_get_parm (esil, t, v)) {
free (t);
return false;
}
free (t);
return true;
}
static CPU_CONST *const_by_value(CPU_MODEL *cpu, int type, ut32 v) {
CPU_CONST **clist, *citem;
for (clist = cpu->consts; *clist; clist++) {
for (citem = *clist; citem && citem->key; citem++) {
if (citem->value == (MASK (citem->size * 8) & v)
&& (type == CPU_CONST_NONE || type == citem->type)) {
return citem;
}
}
}
if (cpu->inherit_cpu_p)
return const_by_value (cpu->inherit_cpu_p, type, v);
return NULL;
}
static RStrBuf *__generic_io_dest(ut8 port, int write, CPU_MODEL *cpu) {
RStrBuf *r = r_strbuf_new ("");
CPU_CONST *c = const_by_value (cpu, CPU_CONST_REG, port);
if (c != NULL) {
r_strbuf_set (r, c->key);
if (write) {
r_strbuf_append (r, ",=");
}
} else {
r_strbuf_setf (r, "_io,%d,+,%s[1]", port, write ? "=" : "");
}
return r;
}
static void __generic_bitop_flags(RAnalOp *op) {
ESIL_A ("0,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
}
static void __generic_ld_st(RAnalOp *op, char *mem, char ireg, int use_ramp, int prepostdec, int offset, int st) {
if (ireg) {
// preincrement index register
if (prepostdec < 0) {
ESIL_A ("1,%c,-,%c,=,", ireg, ireg);
}
// set register index address
ESIL_A ("%c,", ireg);
// add offset
if (offset != 0) {
ESIL_A ("%d,+,", offset);
}
} else {
ESIL_A ("%d,", offset);
}
if (use_ramp) {
ESIL_A ("16,ramp%c,<<,+,", ireg ? ireg : 'd');
}
// set SRAM base address
ESIL_A ("_%s,+,", mem);
// read/write from SRAM
ESIL_A ("%s[1],", st ? "=" : "");
// postincrement index register
if (ireg && prepostdec > 0) {
ESIL_A ("1,%c,+,%c,=,", ireg, ireg);
}
}
static void __generic_pop(RAnalOp *op, int sz) {
if (sz > 1) {
ESIL_A ("1,sp,+,_ram,+,"); // calc SRAM(sp+1)
ESIL_A ("[%d],", sz); // read value
ESIL_A ("%d,sp,+=,", sz); // sp += item_size
} else {
ESIL_A ("1,sp,+=," // increment stack pointer
"sp,_ram,+,[1],"); // load SRAM[sp]
}
}
static void __generic_push(RAnalOp *op, int sz) {
ESIL_A ("sp,_ram,+,"); // calc pointer SRAM(sp)
if (sz > 1) {
ESIL_A ("-%d,+,", sz - 1); // dec SP by 'sz'
}
ESIL_A ("=[%d],", sz); // store value in stack
ESIL_A ("-%d,sp,+=,", sz); // decrement stack pointer
}
static void __generic_add_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_add_update_flags_rr(RAnalOp *op, int d, int r) {
__generic_add_update_flags(op, 'r', d, 'r', r);
}
static void __generic_sub_update_flags(RAnalOp *op, char t_d, ut64 v_d, char t_rk, ut64 v_rk, int carry) {
RStrBuf *d_strbuf, *rk_strbuf;
char *d, *rk;
d_strbuf = r_strbuf_new (NULL);
rk_strbuf = r_strbuf_new (NULL);
r_strbuf_setf (d_strbuf, t_d == 'r' ? "r%d" : "%" PFMT64d, v_d);
r_strbuf_setf (rk_strbuf, t_rk == 'r' ? "r%d" : "%" PFMT64d, v_rk);
d = r_strbuf_get(d_strbuf);
rk = r_strbuf_get(rk_strbuf);
ESIL_A ("%s,0x08,&,!," "%s,0x08,&,!,!," "&," // H
"%s,0x08,&,!,!," "0,RPICK,0x08,&,!,!," "&,"
"%s,0x08,&,!," "0,RPICK,0x08,&,!,!," "&,"
"|,|,hf,=,",
d, rk, rk, d);
ESIL_A ("%s,0x80,&,!,!," "%s,0x80,&,!," "&," // V
"" "0,RPICK,0x80,&,!," "&,"
"%s,0x80,&,!," "%s,0x80,&,!,!," "&,"
"" "0,RPICK,0x80,&,!,!," "&,"
"|,vf,=,",
d, rk, d, rk);
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
if (carry)
ESIL_A ("0,RPICK,!,zf,&,zf,=,"); // Z
else
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("%s,0x80,&,!," "%s,0x80,&,!,!," "&," // C
"%s,0x80,&,!,!," "0,RPICK,0x80,&,!,!," "&,"
"%s,0x80,&,!," "0,RPICK,0x80,&,!,!," "&,"
"|,|,cf,=,",
d, rk, rk, d);
ESIL_A ("vf,nf,^,sf,=,"); // S
r_strbuf_free (d_strbuf);
r_strbuf_free (rk_strbuf);
}
static void __generic_sub_update_flags_rr(RAnalOp *op, int d, int r, int carry) {
__generic_sub_update_flags(op, 'r', d, 'r', r, carry);
}
static void __generic_sub_update_flags_rk(RAnalOp *op, int d, int k, int carry) {
__generic_sub_update_flags(op, 'r', d, 'k', k, carry);
}
INST_HANDLER (adc) { // ADC Rd, Rr
// ROL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,cf,+,r%d,+,", r, d); // Rd + Rr + C
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (add) { // ADD Rd, Rr
// LSL Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,+,", r, d); // Rd + Rr
__generic_add_update_flags_rr(op, d, r); // FLAGS
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (adiw) { // ADIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("r%d:r%d,%d,+,", d + 1, d, k); // Rd+1:Rd + Rr
// FLAGS:
ESIL_A ("r%d,0x80,&,!," // V
"0,RPICK,0x8000,&,!,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!,!," // C
"0,RPICK,0x8000,&,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (and) { // AND Rd, Rr
// TST Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,&,", r, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (andi) { // ANDI Rd, K
// CBR Rd, K (= ANDI Rd, 1-K)
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0x0f) << 4) | (buf[0] & 0x0f);
op->val = k;
ESIL_A ("%d,r%d,&,", k, d); // 0: Rd & Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (asr) { // ASR Rd
if (len < 2) {
return;
}
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,r%d,0x80,&,|,", d, d); // 0: R=(Rd >> 1) | Rd7
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (bclr) { // BCLR s
// CLC
// CLH
// CLI
// CLN
// CLR
// CLS
// CLT
// CLV
// CLZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("0xff,%d,1,<<,^,sreg,&=,", s);
}
INST_HANDLER (bld) { // BLD Rd, b
if (len < 2) {
return;
}
int d = ((buf[1] & 0x01) << 4) | ((buf[0] >> 4) & 0xf);
int b = buf[0] & 0x7;
ESIL_A ("r%d,%d,1,<<,0xff,^,&,", d, b); // Rd/b = 0
ESIL_A ("%d,tf,<<,|,r%d,=,", b, d); // Rd/b |= T<<b
}
INST_HANDLER (brbx) { // BRBC s, k
// BRBS s, k
// BRBC/S 0: BRCC BRCS
// BRSH BRLO
// BRBC/S 1: BREQ BRNE
// BRBC/S 2: BRPL BRMI
// BRBC/S 3: BRVC BRVS
// BRBC/S 4: BRGE BRLT
// BRBC/S 5: BRHC BRHS
// BRBC/S 6: BRTC BRTS
// BRBC/S 7: BRID BRIE
int s = buf[0] & 0x7;
op->jump = op->addr
+ ((((buf[1] & 0x03) << 6) | ((buf[0] & 0xf8) >> 2))
| (buf[1] & 0x2 ? ~((int) 0x7f) : 0))
+ 2;
op->fail = op->addr + op->size;
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,sreg,&,", s); // SREG(s)
ESIL_A (buf[1] & 0x4
? "!," // BRBC => branch if cleared
: "!,!,"); // BRBS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (break) { // BREAK
ESIL_A ("BREAK");
}
INST_HANDLER (bset) { // BSET s
// SEC
// SEH
// SEI
// SEN
// SER
// SES
// SET
// SEV
// SEZ
int s = (buf[0] >> 4) & 0x7;
ESIL_A ("%d,1,<<,sreg,|=,", s);
}
INST_HANDLER (bst) { // BST Rd, b
if (len < 2) {
return;
}
ESIL_A ("r%d,%d,1,<<,&,!,!,tf,=,", // tf = Rd/b
((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf), // r
buf[0] & 0x7); // b
}
INST_HANDLER (call) { // CALL k
if (len < 4) {
return;
}
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->fail = op->addr + op->size;
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // AT*mega optimizes one cycle
}
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (cbi) { // CBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->family = R_ANAL_OP_FAMILY_IO;
op->type2 = 1;
op->val = a;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,^,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (com) { // COM Rd
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0xff,-,0xff,&,r%d,=,", r, r); // Rd = 0xFF-Rd
// FLAGS:
ESIL_A ("0,cf,=,"); // C
__generic_bitop_flags (op); // ...rest...
}
INST_HANDLER (cp) { // CP Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("r%d,r%d,-,", r, d); // do Rd - Rr
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
}
INST_HANDLER (cpc) { // CPC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] << 3) & 0x10);
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // Rd - Rr - C
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
}
INST_HANDLER (cpi) { // CPI Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
ESIL_A ("%d,r%d,-,", k, d); // Rd - k
__generic_sub_update_flags_rk (op, d, k, 0); // FLAGS (carry)
}
INST_HANDLER (cpse) { // CPSE Rd, Rr
int r = (buf[0] & 0xf) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
RAnalOp next_op;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to true, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("r%d,r%d,^,!,", r, d); // Rr == Rd
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (dec) { // DEC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("-1,r%d,+,", d); // --Rd
// FLAGS:
ESIL_A ("0,RPICK,0x7f,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (des) { // DES k
if (desctx.round < 16) { //DES
op->type = R_ANAL_OP_TYPE_CRYPTO;
op->cycles = 1; //redo this
r_strbuf_setf (&op->esil, "%d,des", desctx.round);
}
}
INST_HANDLER (eijmp) { // EIJMP
ut64 z, eind;
// read z and eind for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
r_anal_esil_reg_read (anal->esil, "eind", &eind, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = ((eind << 16) + z) << 1;
// jump
ESIL_A ("1,z,16,eind,<<,+,<<,pc,=,");
// cycles
op->cycles = 2;
}
INST_HANDLER (eicall) { // EICALL
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard EIJMP
INST_CALL (eijmp);
// fix cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega") ? 3 : 4;
}
INST_HANDLER (elpm) { // ELPM
// ELPM Rd
// ELPM Rd, Z+
int d = ((buf[1] & 0xfe) == 0x90)
? ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf) // Rd
: 0; // R0
ESIL_A ("16,rampz,<<,z,+,_prog,+,[1],"); // read RAMPZ:Z
ESIL_A ("r%d,=,", d); // Rd = [1]
if ((buf[1] & 0xfe) == 0x90 && (buf[0] & 0xf) == 0x7) {
ESIL_A ("16,1,z,+,DUP,z,=,>>,1,&,rampz,+=,"); // ++(rampz:z)
}
}
INST_HANDLER (eor) { // EOR Rd, Rr
// CLR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,^,", r, d); // 0: Rd ^ Rr
__generic_bitop_flags (op); // up flags
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (fmul) { // FMUL Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,r%d,r%d,*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmuls) { // FMULS Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("*,<<,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (fmulsu) { // FMULSU Rd, Rr
int d = ((buf[0] >> 4) & 0x7) + 16;
int r = (buf[0] & 0x7) + 16;
ESIL_A ("1,");
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("r%d", r); // unsigned Rr
ESIL_A ("*,<<,"); // 0: (Rd*Rr)<<1
ESIL_A ("0xffff,&,"); // prevent overflow
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/16
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (ijmp) { // IJMP k
ut64 z;
// read z for calculating jump address on runtime
r_anal_esil_reg_read (anal->esil, "z", &z, NULL);
// real target address may change during execution, so this value will
// be changing all the time
op->jump = z << 1;
op->cycles = 2;
ESIL_A ("1,z,<<,pc,=,"); // jump!
}
INST_HANDLER (icall) { // ICALL k
// push pc in stack
ESIL_A ("pc,"); // esil is already pointing to
// next instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret in stack
// do a standard IJMP
INST_CALL (ijmp);
// fix cycles
if (!STR_BEGINS (cpu->model, "ATxmega")) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (in) { // IN Rd, A
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_src = __generic_io_dest (a, 0, cpu);
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("%s,r%d,=,", r_strbuf_get (io_src), r);
r_strbuf_free (io_src);
}
INST_HANDLER (inc) { // INC Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("1,r%d,+,", d); // ++Rd
// FLAGS:
ESIL_A ("0,RPICK,0x80,==,vf,=,"); // V
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (jmp) { // JMP k
op->jump = (buf[2] << 1)
| (buf[3] << 9)
| (buf[1] & 0x01) << 23
| (buf[0] & 0x01) << 17
| (buf[0] & 0xf0) << 14;
op->cycles = 3;
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
}
INST_HANDLER (lac) { // LAC Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,0xff,^,&,", d); // 0: (Z) & ~Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (las) { // LAS Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,|,", d); // 0: (Z) | Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (lat) { // LAT Z, Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
// read memory from RAMPZ:Z
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 0); // 0: Read (RAMPZ:Z)
ESIL_A ("r%d,^,", d); // 0: (Z) ^ Rd
ESIL_A ("DUP,r%d,=,", d); // Rd = [0]
__generic_ld_st (op, "ram", 'z', 1, 0, 0, 1); // Store in RAM
}
INST_HANDLER (ld) { // LD Rd, X
// LD Rd, X+
// LD Rd, -X
// read memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post incremented
: 0, // no increment
0, // offset always 0
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles = (buf[0] & 0x3) == 0
? 2 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldd) { // LD Rd, Y LD Rd, Z
// LD Rd, Y+ LD Rd, Z+
// LD Rd, -Y LD Rd, -Z
// LD Rd, Y+q LD Rd, Z+q
// calculate offset (this value only has sense in some opcodes,
// but we are optimistic and we calculate it always)
int offset = (buf[1] & 0x20)
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7);
// read memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10) ? offset : 0, // offset or not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// cycles
op->cycles =
(buf[1] & 0x10) == 0
? (!offset ? 1 : 3) // LDD
: (buf[0] & 0x3) == 0
? 1 // LD Rd, X
: (buf[0] & 0x3) == 1
? 2 // LD Rd, X+
: 3; // LD Rd, -X
if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// AT*mega optimizes 1 cycle!
op->cycles--;
}
}
INST_HANDLER (ldi) { // LDI Rd, K
int k = (buf[0] & 0xf) + ((buf[1] & 0xf) << 4);
int d = ((buf[0] >> 4) & 0xf) + 16;
op->val = k;
ESIL_A ("0x%x,r%d,=,", k, d);
}
INST_HANDLER (lds) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
// load value from RAMPD:k
__generic_ld_st (op, "ram", 0, 1, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
INST_HANDLER (sts) { // STS k, Rr
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
int k = (buf[3] << 8) | buf[2];
op->ptr = k;
ESIL_A ("r%d,", r);
__generic_ld_st (op, "ram", 0, 1, 0, k, 1);
op->cycles = 2;
}
#if 0
INST_HANDLER (lds16) { // LDS Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0x0f)
| ((buf[1] << 3) & 0x30)
| ((buf[1] << 4) & 0x40)
| (~(buf[1] << 4) & 0x80);
op->ptr = k;
// load value from @k
__generic_ld_st (op, "ram", 0, 0, 0, k, 0);
ESIL_A ("r%d,=,", d);
}
#endif
INST_HANDLER (lpm) { // LPM
// LPM Rd, Z
// LPM Rd, Z+
ut16 ins = (((ut16) buf[1]) << 8) | ((ut16) buf[0]);
// read program memory
__generic_ld_st (
op, "prog",
'z', // index register Y/Z
1, // use RAMP* registers
(ins & 0xfe0f) == 0x9005
? 1 // post incremented
: 0, // no increment
0, // not offset
0); // load operation (!st)
// load register
ESIL_A ("r%d,=,",
(ins == 0x95c8)
? 0 // LPM (r0)
: ((buf[0] >> 4) & 0xf) // LPM Rd
| ((buf[1] & 0x1) << 4));
}
INST_HANDLER (lsr) { // LSR Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("1,r%d,>>,", d); // 0: R=(Rd >> 1)
ESIL_A ("r%d,0x1,&,!,!,cf,=,", d); // C = Rd0
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("nf,vf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = R
}
INST_HANDLER (mov) { // MOV Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,=,", r, d);
}
INST_HANDLER (movw) { // MOVW Rd+1:Rd, Rr+1:Rr
int d = (buf[0] & 0xf0) >> 3;
int r = (buf[0] & 0x0f) << 1;
ESIL_A ("r%d,r%d,=,r%d,r%d,=,", r, d, r + 1, d + 1);
}
INST_HANDLER (mul) { // MUL Rd, Rr
int d = ((buf[1] << 4) & 0x10) | ((buf[0] >> 4) & 0x0f);
int r = ((buf[1] << 3) & 0x10) | (buf[0] & 0x0f);
ESIL_A ("r%d,r%d,*,", r, d); // 0: (Rd*Rr)<<1
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (muls) { // MULS Rd, Rr
int d = (buf[0] >> 4 & 0x0f) + 16;
int r = (buf[0] & 0x0f) + 16;
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", r); // sign extension Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (mulsu) { // MULSU Rd, Rr
int d = (buf[0] >> 4 & 0x07) + 16;
int r = (buf[0] & 0x07) + 16;
ESIL_A ("r%d,", r); // unsigned Rr
ESIL_A ("r%d,DUP,0x80,&,?{,0xffff00,|,},", d); // sign extension Rd
ESIL_A ("*,"); // 0: (Rd*Rr)
ESIL_A ("DUP,0xff,&,r0,=,"); // r0 = LO(0)
ESIL_A ("8,0,RPICK,>>,0xff,&,r1,=,"); // r1 = HI(0)
ESIL_A ("DUP,0x8000,&,!,!,cf,=,"); // C = R/15
ESIL_A ("DUP,!,zf,=,"); // Z = !R
}
INST_HANDLER (neg) { // NEG Rd
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
ESIL_A ("r%d,0x00,-,0xff,&,", d); // 0: (0-Rd)
ESIL_A ("DUP,r%d,0xff,^,|,0x08,&,!,!,hf,=,", d); // H
ESIL_A ("DUP,0x80,-,!,vf,=,", d); // V
ESIL_A ("DUP,0x80,&,!,!,nf,=,"); // N
ESIL_A ("DUP,!,zf,=,"); // Z
ESIL_A ("DUP,!,!,cf,=,"); // C
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (nop) { // NOP
ESIL_A (",,");
}
INST_HANDLER (or) { // OR Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,|,", r, d); // 0: (Rd | Rr)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (ori) { // ORI Rd, K
// SBR Rd, K
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = (buf[0] & 0xf) | ((buf[1] & 0xf) << 4);
op->val = k;
ESIL_A ("r%d,%d,|,", d, k); // 0: (Rd | k)
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("0,vf,=,"); // V
ESIL_A ("nf,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (out) { // OUT A, Rr
int r = ((buf[0] >> 4) & 0x0f) | ((buf[1] & 0x01) << 4);
int a = (buf[0] & 0x0f) | ((buf[1] & 0x6) << 3);
RStrBuf *io_dst = __generic_io_dest (a, 1, cpu);
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
ESIL_A ("r%d,%s,", r, r_strbuf_get (io_dst));
r_strbuf_free (io_dst);
}
INST_HANDLER (pop) { // POP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
__generic_pop (op, 1);
ESIL_A ("r%d,=,", d); // store in Rd
}
INST_HANDLER (push) { // PUSH Rr
int r = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("r%d,", r); // load Rr
__generic_push (op, 1); // push it into stack
// cycles
op->cycles = !STR_BEGINS (cpu->model, "ATxmega")
? 1 // AT*mega optimizes one cycle
: 2;
}
INST_HANDLER (rcall) { // RCALL k
// target address
op->jump = (op->addr
+ (((((buf[1] & 0xf) << 8) | buf[0]) << 1)
| (((buf[1] & 0x8) ? ~((int) 0x1fff) : 0)))
+ 2) & CPU_PC_MASK (cpu);
op->fail = op->addr + op->size;
// esil
ESIL_A ("pc,"); // esil already points to next
// instruction (@ret)
__generic_push (op, CPU_PC_SIZE (cpu)); // push @ret addr
ESIL_A ("%"PFMT64d",pc,=,", op->jump); // jump!
// cycles
if (!strncasecmp (cpu->model, "ATtiny", 6)) {
op->cycles = 4; // ATtiny is always slow
} else {
// PC size decides required runtime!
op->cycles = cpu->pc <= 16 ? 3 : 4;
if (!STR_BEGINS (cpu->model, "ATxmega")) {
op->cycles--; // ATxmega optimizes one cycle
}
}
}
INST_HANDLER (ret) { // RET
op->eob = true;
// esil
__generic_pop (op, CPU_PC_SIZE (cpu));
ESIL_A ("pc,=,"); // jump!
// cycles
if (CPU_PC_SIZE (cpu) > 2) { // if we have a bus bigger than 16 bit
op->cycles++; // (i.e. a 22-bit bus), add one extra cycle
}
}
INST_HANDLER (reti) { // RETI
//XXX: There are not privileged instructions in ATMEL/AVR
op->family = R_ANAL_OP_FAMILY_PRIV;
// first perform a standard 'ret'
INST_CALL (ret);
// RETI: The I-bit is cleared by hardware after an interrupt
// has occurred, and is set by the RETI instruction to enable
// subsequent interrupts
ESIL_A ("1,if,=,");
}
INST_HANDLER (rjmp) { // RJMP k
op->jump = (op->addr
#ifdef _MSC_VER
#pragma message ("anal_avr.c: WARNING: Probably broken on windows")
+ ((((( buf[1] & 0xf) << 9) | (buf[0] << 1)))
| (buf[1] & 0x8 ? ~(0x1fff) : 0))
#else
+ ((((( (typeof (op->jump)) buf[1] & 0xf) << 9) | ((typeof (op->jump)) buf[0] << 1)))
| (buf[1] & 0x8 ? ~((typeof (op->jump)) 0x1fff) : 0))
#endif
+ 2) & CPU_PC_MASK (cpu);
ESIL_A ("%"PFMT64d",pc,=,", op->jump);
}
INST_HANDLER (ror) { // ROR Rd
int d = ((buf[0] >> 4) & 0x0f) | ((buf[1] << 4) & 0x10);
ESIL_A ("1,r%d,>>,7,cf,<<,|,", d); // 0: (Rd>>1) | (cf<<7)
ESIL_A ("r%d,1,&,cf,=,", d); // C
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("0,RPICK,0x80,&,!,!,nf,=,"); // N
ESIL_A ("nf,cf,^,vf,=,"); // V
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d,=,", d); // Rd = result
}
INST_HANDLER (sbc) { // SBC Rd, Rr
int r = (buf[0] & 0x0f) | ((buf[1] & 0x2) << 3);
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x1) << 4);
ESIL_A ("cf,r%d,+,r%d,-,", r, d); // 0: (Rd-Rr-C)
__generic_sub_update_flags_rr (op, d, r, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbci) { // SBCI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("cf,%d,+,r%d,-,", k, d); // 0: (Rd-k-C)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sub) { // SUB Rd, Rr
int d = ((buf[0] >> 4) & 0xf) | ((buf[1] & 1) << 4);
int r = (buf[0] & 0xf) | ((buf[1] & 2) << 3);
ESIL_A ("r%d,r%d,-,", r, d); // 0: (Rd-k)
__generic_sub_update_flags_rr (op, d, r, 0); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (subi) { // SUBI Rd, k
int d = ((buf[0] >> 4) & 0xf) + 16;
int k = ((buf[1] & 0xf) << 4) | (buf[0] & 0xf);
op->val = k;
ESIL_A ("%d,r%d,-,", k, d); // 0: (Rd-k)
__generic_sub_update_flags_rk (op, d, k, 1); // FLAGS (no carry)
ESIL_A ("r%d,=,", d); // Rd = Result
}
INST_HANDLER (sbi) { // SBI A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RStrBuf *io_port;
op->type2 = 1;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("0xff,%d,1,<<,|,%s,&,", b, io_port);
r_strbuf_free (io_port);
// write result to port a
io_port = __generic_io_dest (a, 1, cpu);
ESIL_A ("%s,", r_strbuf_get (io_port));
r_strbuf_free (io_port);
}
INST_HANDLER (sbix) { // SBIC A, b
// SBIS A, b
int a = (buf[0] >> 3) & 0x1f;
int b = buf[0] & 0x07;
RAnalOp next_op;
RStrBuf *io_port;
op->type2 = 0;
op->val = a;
op->family = R_ANAL_OP_FAMILY_IO;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size,
len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
// read port a and clear bit b
io_port = __generic_io_dest (a, 0, cpu);
ESIL_A ("%d,1,<<,%s,&,", b, io_port); // IO(A,b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBIC => branch if 0
: "!,!,"); // SBIS => branch if 1
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
r_strbuf_free (io_port);
}
INST_HANDLER (sbiw) { // SBIW Rd+1:Rd, K
int d = ((buf[0] & 0x30) >> 3) + 24;
int k = (buf[0] & 0xf) | ((buf[0] >> 2) & 0x30);
op->val = k;
ESIL_A ("%d,r%d:r%d,-,", k, d + 1, d); // 0(Rd+1:Rd - Rr)
ESIL_A ("r%d,0x80,&,!,!," // V
"0,RPICK,0x8000,&,!,"
"&,vf,=,", d + 1);
ESIL_A ("0,RPICK,0x8000,&,!,!,nf,=,"); // N
ESIL_A ("0,RPICK,!,zf,=,"); // Z
ESIL_A ("r%d,0x80,&,!," // C
"0,RPICK,0x8000,&,!,!,"
"&,cf,=,", d + 1);
ESIL_A ("vf,nf,^,sf,=,"); // S
ESIL_A ("r%d:r%d,=,", d + 1, d); // Rd = result
}
INST_HANDLER (sbrx) { // SBRC Rr, b
// SBRS Rr, b
int b = buf[0] & 0x7;
int r = ((buf[0] >> 4) & 0xf) | ((buf[1] & 0x01) << 4);
RAnalOp next_op;
// calculate next instruction size (call recursively avr_op_analyze)
// and free next_op's esil string (we dont need it now)
avr_op_analyze (anal,
&next_op,
op->addr + op->size, buf + op->size, len - op->size,
cpu);
r_strbuf_fini (&next_op.esil);
op->jump = op->addr + next_op.size + 2;
// cycles
op->cycles = 1; // XXX: This is a bug, because depends on eval state,
// so it cannot be really be known until this
// instruction is executed by the ESIL interpreter!!!
// In case of evaluating to false, this instruction
// needs 2/3 cycles, elsewhere it needs only 1 cycle.
ESIL_A ("%d,1,<<,r%d,&,", b, r); // Rr(b)
ESIL_A ((buf[1] & 0xe) == 0xc
? "!," // SBRC => branch if cleared
: "!,!,"); // SBRS => branch if set
ESIL_A ("?{,%"PFMT64d",pc,=,},", op->jump); // ?true => jmp
}
INST_HANDLER (sleep) { // SLEEP
ESIL_A ("BREAK");
}
INST_HANDLER (spm) { // SPM Z+
ut64 spmcsr;
// read SPM Control Register (SPMCR)
r_anal_esil_reg_read (anal->esil, "spmcsr", &spmcsr, NULL);
// clear SPMCSR
ESIL_A ("0x7c,spmcsr,&=,");
// decide action depending on the old value of SPMCSR
switch (spmcsr & 0x7f) {
case 0x03: // PAGE ERASE
// invoke SPM_CLEAR_PAGE (erases target page writing
// the 0xff value
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_ERASE,"); // do magic
break;
case 0x01: // FILL TEMPORARY BUFFER
ESIL_A ("r1,r0,"); // push data
ESIL_A ("z,"); // push target address
ESIL_A ("SPM_PAGE_FILL,"); // do magic
break;
case 0x05: // WRITE PAGE
ESIL_A ("16,rampz,<<,z,+,"); // push target address
ESIL_A ("SPM_PAGE_WRITE,"); // do magic
break;
default:
eprintf ("SPM: I dont know what to do with SPMCSR %02x.\n",
(unsigned int) spmcsr);
}
op->cycles = 1; // This is truly false. Datasheets do not publish how
// many cycles this instruction uses in all its
// operation modes and I am pretty sure that this value
// can vary substantially from one MCU type to another.
// So... one cycle is fine.
}
INST_HANDLER (st) { // ST X, Rr
// ST X+, Rr
// ST -X, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
'x', // use index register X
0, // no use RAMP* registers
(buf[0] & 0xf) == 0xe
? -1 // pre decremented
: (buf[0] & 0xf) == 0xd
? 1 // post increment
: 0, // no increment
0, // offset always 0
1); // store operation (st)
// // cycles
// op->cycles = buf[0] & 0x3 == 0
// ? 2 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (std) { // ST Y, Rr ST Z, Rr
// ST Y+, Rr ST Z+, Rr
// ST -Y, Rr ST -Z, Rr
// ST Y+q, Rr ST Z+q, Rr
// load register
ESIL_A ("r%d,", ((buf[1] & 1) << 4) | ((buf[0] >> 4) & 0xf));
// write in memory
__generic_ld_st (
op, "ram",
buf[0] & 0x8 ? 'y' : 'z', // index register Y/Z
0, // no use RAMP* registers
!(buf[1] & 0x10)
? 0 // no increment
: buf[0] & 0x1
? 1 // post incremented
: -1, // pre decremented
!(buf[1] & 0x10)
? (buf[1] & 0x20) // offset
| ((buf[1] & 0xc) << 1)
| (buf[0] & 0x7)
: 0, // no offset
1); // load operation (!st)
// // cycles
// op->cycles =
// buf[1] & 0x1 == 0
// ? !(offset ? 1 : 3) // LDD
// : buf[0] & 0x3 == 0
// ? 1 // LD Rd, X
// : buf[0] & 0x3 == 1
// ? 2 // LD Rd, X+
// : 3; // LD Rd, -X
// if (!STR_BEGINS (cpu->model, "ATxmega") && op->cycles > 1) {
// // AT*mega optimizes 1 cycle!
// op->cycles--;
// }
}
INST_HANDLER (swap) { // SWAP Rd
int d = ((buf[1] & 0x1) << 4) | ((buf[0] >> 4) & 0xf);
ESIL_A ("4,r%d,>>,0x0f,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("4,r%d,<<,0xf0,&,", d); // (Rd >> 4) & 0xf
ESIL_A ("|,", d); // S[0] | S[1]
ESIL_A ("r%d,=,", d); // Rd = result
}
OPCODE_DESC opcodes[] = {
// op mask select cycles size type
INST_DECL (break, 0xffff, 0x9698, 1, 2, TRAP ), // BREAK
INST_DECL (eicall, 0xffff, 0x9519, 0, 2, UCALL ), // EICALL
INST_DECL (eijmp, 0xffff, 0x9419, 0, 2, UJMP ), // EIJMP
INST_DECL (icall, 0xffff, 0x9509, 0, 2, UCALL ), // ICALL
INST_DECL (ijmp, 0xffff, 0x9409, 0, 2, UJMP ), // IJMP
INST_DECL (lpm, 0xffff, 0x95c8, 3, 2, LOAD ), // LPM
INST_DECL (nop, 0xffff, 0x0000, 1, 2, NOP ), // NOP
INST_DECL (ret, 0xffff, 0x9508, 4, 2, RET ), // RET
INST_DECL (reti, 0xffff, 0x9518, 4, 2, RET ), // RETI
INST_DECL (sleep, 0xffff, 0x9588, 1, 2, NOP ), // SLEEP
INST_DECL (spm, 0xffff, 0x95e8, 1, 2, TRAP ), // SPM ...
INST_DECL (bclr, 0xff8f, 0x9488, 1, 2, SWI ), // BCLR s
INST_DECL (bset, 0xff8f, 0x9408, 1, 2, SWI ), // BSET s
INST_DECL (fmul, 0xff88, 0x0308, 2, 2, MUL ), // FMUL Rd, Rr
INST_DECL (fmuls, 0xff88, 0x0380, 2, 2, MUL ), // FMULS Rd, Rr
INST_DECL (fmulsu, 0xff88, 0x0388, 2, 2, MUL ), // FMULSU Rd, Rr
INST_DECL (mulsu, 0xff88, 0x0300, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (des, 0xff0f, 0x940b, 0, 2, CRYPTO ), // DES k
INST_DECL (adiw, 0xff00, 0x9600, 2, 2, ADD ), // ADIW Rd+1:Rd, K
INST_DECL (sbiw, 0xff00, 0x9700, 2, 2, SUB ), // SBIW Rd+1:Rd, K
INST_DECL (cbi, 0xff00, 0x9800, 1, 2, IO ), // CBI A, K
INST_DECL (sbi, 0xff00, 0x9a00, 1, 2, IO ), // SBI A, K
INST_DECL (movw, 0xff00, 0x0100, 1, 2, MOV ), // MOVW Rd+1:Rd, Rr+1:Rr
INST_DECL (muls, 0xff00, 0x0200, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (asr, 0xfe0f, 0x9405, 1, 2, SAR ), // ASR Rd
INST_DECL (com, 0xfe0f, 0x9400, 1, 2, SWI ), // BLD Rd, b
INST_DECL (dec, 0xfe0f, 0x940a, 1, 2, SUB ), // DEC Rd
INST_DECL (elpm, 0xfe0f, 0x9006, 0, 2, LOAD ), // ELPM Rd, Z
INST_DECL (elpm, 0xfe0f, 0x9007, 0, 2, LOAD ), // ELPM Rd, Z+
INST_DECL (inc, 0xfe0f, 0x9403, 1, 2, ADD ), // INC Rd
INST_DECL (lac, 0xfe0f, 0x9206, 2, 2, LOAD ), // LAC Z, Rd
INST_DECL (las, 0xfe0f, 0x9205, 2, 2, LOAD ), // LAS Z, Rd
INST_DECL (lat, 0xfe0f, 0x9207, 2, 2, LOAD ), // LAT Z, Rd
INST_DECL (ld, 0xfe0f, 0x900c, 0, 2, LOAD ), // LD Rd, X
INST_DECL (ld, 0xfe0f, 0x900d, 0, 2, LOAD ), // LD Rd, X+
INST_DECL (ld, 0xfe0f, 0x900e, 0, 2, LOAD ), // LD Rd, -X
INST_DECL (lds, 0xfe0f, 0x9000, 0, 4, LOAD ), // LDS Rd, k
INST_DECL (sts, 0xfe0f, 0x9200, 2, 4, STORE ), // STS k, Rr
INST_DECL (lpm, 0xfe0f, 0x9004, 3, 2, LOAD ), // LPM Rd, Z
INST_DECL (lpm, 0xfe0f, 0x9005, 3, 2, LOAD ), // LPM Rd, Z+
INST_DECL (lsr, 0xfe0f, 0x9406, 1, 2, SHR ), // LSR Rd
INST_DECL (neg, 0xfe0f, 0x9401, 2, 2, SUB ), // NEG Rd
INST_DECL (pop, 0xfe0f, 0x900f, 2, 2, POP ), // POP Rd
INST_DECL (push, 0xfe0f, 0x920f, 0, 2, PUSH ), // PUSH Rr
INST_DECL (ror, 0xfe0f, 0x9407, 1, 2, SAR ), // ROR Rd
INST_DECL (st, 0xfe0f, 0x920c, 2, 2, STORE ), // ST X, Rr
INST_DECL (st, 0xfe0f, 0x920d, 0, 2, STORE ), // ST X+, Rr
INST_DECL (st, 0xfe0f, 0x920e, 0, 2, STORE ), // ST -X, Rr
INST_DECL (swap, 0xfe0f, 0x9402, 1, 2, SAR ), // SWAP Rd
INST_DECL (call, 0xfe0e, 0x940e, 0, 4, CALL ), // CALL k
INST_DECL (jmp, 0xfe0e, 0x940c, 2, 4, JMP ), // JMP k
INST_DECL (bld, 0xfe08, 0xf800, 1, 2, SWI ), // BLD Rd, b
INST_DECL (bst, 0xfe08, 0xfa00, 1, 2, SWI ), // BST Rd, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIC A, b
INST_DECL (sbix, 0xfe08, 0x9900, 2, 2, CJMP ), // SBIS A, b
INST_DECL (sbrx, 0xfe08, 0xfc00, 2, 2, CJMP ), // SBRC Rr, b
INST_DECL (sbrx, 0xfe08, 0xfe00, 2, 2, CJMP ), // SBRS Rr, b
INST_DECL (ldd, 0xfe07, 0x9001, 0, 2, LOAD ), // LD Rd, Y/Z+
INST_DECL (ldd, 0xfe07, 0x9002, 0, 2, LOAD ), // LD Rd, -Y/Z
INST_DECL (std, 0xfe07, 0x9201, 0, 2, STORE ), // ST Y/Z+, Rr
INST_DECL (std, 0xfe07, 0x9202, 0, 2, STORE ), // ST -Y/Z, Rr
INST_DECL (adc, 0xfc00, 0x1c00, 1, 2, ADD ), // ADC Rd, Rr
INST_DECL (add, 0xfc00, 0x0c00, 1, 2, ADD ), // ADD Rd, Rr
INST_DECL (and, 0xfc00, 0x2000, 1, 2, AND ), // AND Rd, Rr
INST_DECL (brbx, 0xfc00, 0xf000, 0, 2, CJMP ), // BRBS s, k
INST_DECL (brbx, 0xfc00, 0xf400, 0, 2, CJMP ), // BRBC s, k
INST_DECL (cp, 0xfc00, 0x1400, 1, 2, CMP ), // CP Rd, Rr
INST_DECL (cpc, 0xfc00, 0x0400, 1, 2, CMP ), // CPC Rd, Rr
INST_DECL (cpse, 0xfc00, 0x1000, 0, 2, CJMP ), // CPSE Rd, Rr
INST_DECL (eor, 0xfc00, 0x2400, 1, 2, XOR ), // EOR Rd, Rr
INST_DECL (mov, 0xfc00, 0x2c00, 1, 2, MOV ), // MOV Rd, Rr
INST_DECL (mul, 0xfc00, 0x9c00, 2, 2, AND ), // MUL Rd, Rr
INST_DECL (or, 0xfc00, 0x2800, 1, 2, OR ), // OR Rd, Rr
INST_DECL (sbc, 0xfc00, 0x0800, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (sub, 0xfc00, 0x1800, 1, 2, SUB ), // SUB Rd, Rr
INST_DECL (in, 0xf800, 0xb000, 1, 2, IO ), // IN Rd, A
//INST_DECL (lds16, 0xf800, 0xa000, 1, 2, LOAD ), // LDS Rd, k
INST_DECL (out, 0xf800, 0xb800, 1, 2, IO ), // OUT A, Rr
INST_DECL (andi, 0xf000, 0x7000, 1, 2, AND ), // ANDI Rd, K
INST_DECL (cpi, 0xf000, 0x3000, 1, 2, CMP ), // CPI Rd, K
INST_DECL (ldi, 0xf000, 0xe000, 1, 2, LOAD ), // LDI Rd, K
INST_DECL (ori, 0xf000, 0x6000, 1, 2, OR ), // ORI Rd, K
INST_DECL (rcall, 0xf000, 0xd000, 0, 2, CALL ), // RCALL k
INST_DECL (rjmp, 0xf000, 0xc000, 2, 2, JMP ), // RJMP k
INST_DECL (sbci, 0xf000, 0x4000, 1, 2, SUB ), // SBC Rd, Rr
INST_DECL (subi, 0xf000, 0x5000, 1, 2, SUB ), // SUBI Rd, Rr
INST_DECL (ldd, 0xd200, 0x8000, 0, 2, LOAD ), // LD Rd, Y/Z+q
INST_DECL (std, 0xd200, 0x8200, 0, 2, STORE ), // ST Y/Z+q, Rr
INST_LAST
};
static OPCODE_DESC* avr_op_analyze(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len, CPU_MODEL *cpu) {
OPCODE_DESC *opcode_desc;
if (len < 2) {
return NULL;
}
ut16 ins = (buf[1] << 8) | buf[0];
int fail;
char *t;
// initialize op struct
memset (op, 0, sizeof (RAnalOp));
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->jump = UT64_MAX;
r_strbuf_init (&op->esil);
// process opcode
for (opcode_desc = opcodes; opcode_desc->handler; opcode_desc++) {
if ((ins & opcode_desc->mask) == opcode_desc->selector) {
fail = 0;
// copy default cycles/size values
op->cycles = opcode_desc->cycles;
op->size = opcode_desc->size;
op->type = opcode_desc->type;
op->jump = UT64_MAX;
op->fail = UT64_MAX;
// op->fail = addr + op->size;
op->addr = addr;
// start void esil expression
r_strbuf_setf (&op->esil, "");
// handle opcode
opcode_desc->handler (anal, op, buf, len, &fail, cpu);
if (fail) {
goto INVALID_OP;
}
if (op->cycles <= 0) {
// eprintf ("opcode %s @%"PFMT64x" returned 0 cycles.\n", opcode_desc->name, op->addr);
opcode_desc->cycles = 2;
}
op->nopcode = (op->type == R_ANAL_OP_TYPE_UNK);
// remove trailing coma (COMETE LA COMA)
t = r_strbuf_get (&op->esil);
if (t && strlen (t) > 1) {
t += strlen (t) - 1;
if (*t == ',') {
*t = '\0';
}
}
return opcode_desc;
}
}
// ignore reserved opcodes (if they have not been caught by the previous loop)
if ((ins & 0xff00) == 0xff00 && (ins & 0xf) > 7) {
goto INVALID_OP;
}
INVALID_OP:
// An unknown or invalid option has appeared.
// -- Throw pokeball!
op->family = R_ANAL_OP_FAMILY_UNKNOWN;
op->type = R_ANAL_OP_TYPE_UNK;
op->addr = addr;
op->fail = UT64_MAX;
op->jump = UT64_MAX;
op->ptr = UT64_MAX;
op->val = UT64_MAX;
op->nopcode = 1;
op->cycles = 1;
op->size = 2;
// launch esil trap (for communicating upper layers about this weird
// and stinky situation
r_strbuf_set (&op->esil, "1,$");
return NULL;
}
static int avr_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) {
CPU_MODEL *cpu;
ut64 offset;
// init op
if (!op) {
return 2;
}
// select cpu info
cpu = get_cpu_model (anal->cpu);
// set memory layout registers
if (anal->esil) {
offset = 0;
r_anal_esil_reg_write (anal->esil, "_prog", offset);
offset += (1 << cpu->pc);
r_anal_esil_reg_write (anal->esil, "_io", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_start"));
r_anal_esil_reg_write (anal->esil, "_sram", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "sram_size"));
r_anal_esil_reg_write (anal->esil, "_eeprom", offset);
offset += const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "eeprom_size"));
r_anal_esil_reg_write (anal->esil, "_page", offset);
}
// process opcode
avr_op_analyze (anal, op, addr, buf, len, cpu);
return op->size;
}
static int avr_custom_des (RAnalEsil *esil) {
ut64 key, encrypt, text,des_round;
ut32 key_lo, key_hi, buf_lo, buf_hi;
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
if (!__esil_pop_argument (esil, &des_round)) {
return false;
}
r_anal_esil_reg_read (esil, "hf", &encrypt, NULL);
r_anal_esil_reg_read (esil, "deskey", &key, NULL);
r_anal_esil_reg_read (esil, "text", &text, NULL);
key_lo = key & UT32_MAX;
key_hi = key >> 32;
buf_lo = text & UT32_MAX;
buf_hi = text >> 32;
if (des_round != desctx.round) {
desctx.round = des_round;
}
if (!desctx.round) {
int i;
//generating all round keys
r_des_permute_key (&key_lo, &key_hi);
for (i = 0; i < 16; i++) {
r_des_round_key (i, &desctx.round_key_lo[i], &desctx.round_key_hi[i], &key_lo, &key_hi);
}
r_des_permute_block0 (&buf_lo, &buf_hi);
}
if (encrypt) {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[desctx.round], &desctx.round_key_hi[desctx.round]);
} else {
r_des_round (&buf_lo, &buf_hi, &desctx.round_key_lo[15 - desctx.round], &desctx.round_key_hi[15 - desctx.round]);
}
if (desctx.round == 15) {
r_des_permute_block1 (&buf_hi, &buf_lo);
desctx.round = 0;
} else {
desctx.round++;
}
r_anal_esil_reg_write (esil, "text", text);
return true;
}
// ESIL operation SPM_PAGE_ERASE
static int avr_custom_spm_page_erase(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut8 c;
ut64 addr, page_size_bits, i;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align base address to page_size_bits
addr &= ~(MASK (page_size_bits));
// perform erase
//eprintf ("SPM_PAGE_ERASE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
c = 0xff;
for (i = 0; i < (1ULL << page_size_bits); i++) {
r_anal_esil_mem_write (
esil, (addr + i) & CPU_PC_MASK (cpu), &c, 1);
}
return true;
}
// ESIL operation SPM_PAGE_FILL
static int avr_custom_spm_page_fill(RAnalEsil *esil) {
CPU_MODEL *cpu;
ut64 addr, page_size_bits, i;
ut8 r0, r1;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address, r0, r1
if (!__esil_pop_argument(esil, &addr)) {
return false;
}
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r0 = i;
if (!__esil_pop_argument (esil, &i)) {
return false;
}
r1 = i;
// get details about current MCU and fix input address
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
// align and crop base address
addr &= (MASK (page_size_bits) ^ 1);
// perform write to temporary page
//eprintf ("SPM_PAGE_FILL bytes (%02x, %02x) @ 0x%08" PFMT64x ".\n", r1, r0, addr);
r_anal_esil_mem_write (esil, addr++, &r0, 1);
r_anal_esil_mem_write (esil, addr++, &r1, 1);
return true;
}
// ESIL operation SPM_PAGE_WRITE
static int avr_custom_spm_page_write(RAnalEsil *esil) {
CPU_MODEL *cpu;
char *t = NULL;
ut64 addr, page_size_bits, tmp_page;
// sanity check
if (!esil || !esil->anal || !esil->anal->reg) {
return false;
}
// get target address
if (!__esil_pop_argument (esil, &addr)) {
return false;
}
// get details about current MCU and fix input address and base address
// of the internal temporary page
cpu = get_cpu_model (esil->anal->cpu);
page_size_bits = const_get_value (const_by_name (cpu, CPU_CONST_PARAM, "page_size"));
r_anal_esil_reg_read (esil, "_page", &tmp_page, NULL);
// align base address to page_size_bits
addr &= (~(MASK (page_size_bits)) & CPU_PC_MASK (cpu));
// perform writing
//eprintf ("SPM_PAGE_WRITE %ld bytes @ 0x%08" PFMT64x ".\n", page_size, addr);
if (!(t = malloc (1 << page_size_bits))) {
eprintf ("Cannot alloc a buffer for copying the temporary page.\n");
return false;
}
r_anal_esil_mem_read (esil, tmp_page, (ut8 *) t, 1 << page_size_bits);
r_anal_esil_mem_write (esil, addr, (ut8 *) t, 1 << page_size_bits);
return true;
}
static int esil_avr_hook_reg_write(RAnalEsil *esil, const char *name, ut64 *val) {
CPU_MODEL *cpu;
if (!esil || !esil->anal) {
return 0;
}
// select cpu info
cpu = get_cpu_model (esil->anal->cpu);
// crop registers and force certain values
if (!strcmp (name, "pc")) {
*val &= CPU_PC_MASK (cpu);
} else if (!strcmp (name, "pcl")) {
if (cpu->pc < 8) {
*val &= MASK (8);
}
} else if (!strcmp (name, "pch")) {
*val = cpu->pc > 8
? *val & MASK (cpu->pc - 8)
: 0;
}
return 0;
}
static int esil_avr_init(RAnalEsil *esil) {
if (!esil) {
return false;
}
desctx.round = 0;
r_anal_esil_set_op (esil, "des", avr_custom_des);
r_anal_esil_set_op (esil, "SPM_PAGE_ERASE", avr_custom_spm_page_erase);
r_anal_esil_set_op (esil, "SPM_PAGE_FILL", avr_custom_spm_page_fill);
r_anal_esil_set_op (esil, "SPM_PAGE_WRITE", avr_custom_spm_page_write);
esil->cb.hook_reg_write = esil_avr_hook_reg_write;
return true;
}
static int esil_avr_fini(RAnalEsil *esil) {
return true;
}
static int set_reg_profile(RAnal *anal) {
const char *p =
"=PC pcl\n"
"=SP sp\n"
// explained in http://www.nongnu.org/avr-libc/user-manual/FAQ.html
// and http://www.avrfreaks.net/forum/function-calling-convention-gcc-generated-assembly-file
"=A0 r25\n"
"=A1 r24\n"
"=A2 r23\n"
"=A3 r22\n"
"=R0 r24\n"
#if 0
PC: 16- or 22-bit program counter
SP: 8- or 16-bit stack pointer
SREG: 8-bit status register
RAMPX, RAMPY, RAMPZ, RAMPD and EIND:
#endif
// 8bit registers x 32
"gpr r0 .8 0 0\n"
"gpr r1 .8 1 0\n"
"gpr r2 .8 2 0\n"
"gpr r3 .8 3 0\n"
"gpr r4 .8 4 0\n"
"gpr r5 .8 5 0\n"
"gpr r6 .8 6 0\n"
"gpr r7 .8 7 0\n"
"gpr text .64 0 0\n"
"gpr r8 .8 8 0\n"
"gpr r9 .8 9 0\n"
"gpr r10 .8 10 0\n"
"gpr r11 .8 11 0\n"
"gpr r12 .8 12 0\n"
"gpr r13 .8 13 0\n"
"gpr r14 .8 14 0\n"
"gpr r15 .8 15 0\n"
"gpr deskey .64 8 0\n"
"gpr r16 .8 16 0\n"
"gpr r17 .8 17 0\n"
"gpr r18 .8 18 0\n"
"gpr r19 .8 19 0\n"
"gpr r20 .8 20 0\n"
"gpr r21 .8 21 0\n"
"gpr r22 .8 22 0\n"
"gpr r23 .8 23 0\n"
"gpr r24 .8 24 0\n"
"gpr r25 .8 25 0\n"
"gpr r26 .8 26 0\n"
"gpr r27 .8 27 0\n"
"gpr r28 .8 28 0\n"
"gpr r29 .8 29 0\n"
"gpr r30 .8 30 0\n"
"gpr r31 .8 31 0\n"
// 16 bit overlapped registers for 16 bit math
"gpr r17:r16 .16 16 0\n"
"gpr r19:r18 .16 18 0\n"
"gpr r21:r20 .16 20 0\n"
"gpr r23:r22 .16 22 0\n"
"gpr r25:r24 .16 24 0\n"
"gpr r27:r26 .16 26 0\n"
"gpr r29:r28 .16 28 0\n"
"gpr r31:r30 .16 30 0\n"
// 16 bit overlapped registers for memory addressing
"gpr x .16 26 0\n"
"gpr y .16 28 0\n"
"gpr z .16 30 0\n"
// program counter
// NOTE: program counter size in AVR depends on the CPU model. It seems that
// the PC may range from 16 bits to 22 bits.
"gpr pc .32 32 0\n"
"gpr pcl .16 32 0\n"
"gpr pch .16 34 0\n"
// special purpose registers
"gpr sp .16 36 0\n"
"gpr spl .8 36 0\n"
"gpr sph .8 37 0\n"
// status bit register (SREG)
"gpr sreg .8 38 0\n"
"gpr cf .1 38.0 0\n" // Carry. This is a borrow flag on subtracts.
"gpr zf .1 38.1 0\n" // Zero. Set to 1 when an arithmetic result is zero.
"gpr nf .1 38.2 0\n" // Negative. Set to a copy of the most significant bit of an arithmetic result.
"gpr vf .1 38.3 0\n" // Overflow flag. Set in case of two's complement overflow.
"gpr sf .1 38.4 0\n" // Sign flag. Unique to AVR, this is always (N ^ V) (xor), and shows the true sign of a comparison.
"gpr hf .1 38.5 0\n" // Half carry. This is an internal carry from additions and is used to support BCD arithmetic.
"gpr tf .1 38.6 0\n" // Bit copy. Special bit load and bit store instructions use this bit.
"gpr if .1 38.7 0\n" // Interrupt flag. Set when interrupts are enabled.
// 8bit segment registers to be added to X, Y, Z to get 24bit offsets
"gpr rampx .8 39 0\n"
"gpr rampy .8 40 0\n"
"gpr rampz .8 41 0\n"
"gpr rampd .8 42 0\n"
"gpr eind .8 43 0\n"
// memory mapping emulator registers
// _prog
// the program flash. It has its own address space.
// _ram
// _io
// start of the data addres space. It is the same address of IO,
// because IO is the first memory space addressable in the AVR.
// _sram
// start of the SRAM (this offset depends on IO size, and it is
// inside the _ram address space)
// _eeprom
// this is another address space, outside ram and flash
// _page
// this is the temporary page used by the SPM instruction. This
// memory is not directly addressable and it is used internally by
// the CPU when autoflashing.
"gpr _prog .32 44 0\n"
"gpr _page .32 48 0\n"
"gpr _eeprom .32 52 0\n"
"gpr _ram .32 56 0\n"
"gpr _io .32 56 0\n"
"gpr _sram .32 60 0\n"
// other important MCU registers
// spmcsr/spmcr
// Store Program Memory Control and Status Register (SPMCSR)
"gpr spmcsr .8 64 0\n"
;
return r_reg_set_profile_string (anal->reg, p);
}
static int archinfo(RAnal *anal, int q) {
if (q == R_ANAL_ARCHINFO_ALIGN)
return 2;
if (q == R_ANAL_ARCHINFO_MAX_OP_SIZE)
return 4;
if (q == R_ANAL_ARCHINFO_MIN_OP_SIZE)
return 2;
return 2; // XXX
}
static ut8 *anal_mask_avr(RAnal *anal, int size, const ut8 *data, ut64 at) {
RAnalOp *op = NULL;
ut8 *ret = NULL;
int idx;
if (!(op = r_anal_op_new ())) {
return NULL;
}
if (!(ret = malloc (size))) {
r_anal_op_free (op);
return NULL;
}
memset (ret, 0xff, size);
CPU_MODEL *cpu = get_cpu_model (anal->cpu);
for (idx = 0; idx + 1 < size; idx += op->size) {
OPCODE_DESC* opcode_desc = avr_op_analyze (anal, op, at + idx, data + idx, size - idx, cpu);
if (op->size < 1) {
break;
}
if (!opcode_desc) { // invalid instruction
continue;
}
// the additional data for "long" opcodes (4 bytes) is usually something we want to ignore for matching
// (things like memory offsets or jump addresses)
if (op->size == 4) {
ret[idx + 2] = 0;
ret[idx + 3] = 0;
}
if (op->ptr != UT64_MAX || op->jump != UT64_MAX) {
ret[idx] = opcode_desc->mask;
ret[idx + 1] = opcode_desc->mask >> 8;
}
}
r_anal_op_free (op);
return ret;
}
RAnalPlugin r_anal_plugin_avr = {
.name = "avr",
.desc = "AVR code analysis plugin",
.license = "LGPL3",
.arch = "avr",
.esil = true,
.archinfo = archinfo,
.bits = 8 | 16, // 24 big regs conflicts
.op = &avr_op,
.set_reg_profile = &set_reg_profile,
.esil_init = esil_avr_init,
.esil_fini = esil_avr_fini,
.anal_mask = anal_mask_avr,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_avr,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_142_0 |
crossvul-cpp_data_bad_2648_2 | /*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: MPLS LSP PING printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "l2vpn.h"
#include "oui.h"
/* RFC 4349 */
/*
* LSPPING common header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version Number | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Message Type | Reply mode | Return Code | Return Subcode|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's Handle |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Sent (seconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Sent (microseconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Received (seconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Received (microseconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TLVs ... |
* . .
* . .
* . .
*/
struct lspping_common_header {
uint8_t version[2];
uint8_t global_flags[2];
uint8_t msg_type;
uint8_t reply_mode;
uint8_t return_code;
uint8_t return_subcode;
uint8_t sender_handle[4];
uint8_t seq_number[4];
uint8_t ts_sent_sec[4];
uint8_t ts_sent_usec[4];
uint8_t ts_rcvd_sec[4];
uint8_t ts_rcvd_usec[4];
};
#define LSPPING_VERSION 1
static const struct tok lspping_msg_type_values[] = {
{ 1, "MPLS Echo Request"},
{ 2, "MPLS Echo Reply"},
{ 0, NULL}
};
static const struct tok lspping_reply_mode_values[] = {
{ 1, "Do not reply"},
{ 2, "Reply via an IPv4/IPv6 UDP packet"},
{ 3, "Reply via an IPv4/IPv6 UDP packet with Router Alert"},
{ 4, "Reply via application level control channel"},
{ 0, NULL}
};
static const struct tok lspping_return_code_values[] = {
{ 0, "No return code or return code contained in the Error Code TLV"},
{ 1, "Malformed echo request received"},
{ 2, "One or more of the TLVs was not understood"},
{ 3, "Replying router is an egress for the FEC at stack depth"},
{ 4, "Replying router has no mapping for the FEC at stack depth"},
{ 5, "Reserved"},
{ 6, "Reserved"},
{ 7, "Reserved"},
{ 8, "Label switched at stack-depth"},
{ 9, "Label switched but no MPLS forwarding at stack-depth"},
{ 10, "Mapping for this FEC is not the given label at stack depth"},
{ 11, "No label entry at stack-depth"},
{ 12, "Protocol not associated with interface at FEC stack depth"},
{ 13, "Premature termination of ping due to label stack shrinking to a single label"},
};
/*
* LSPPING TLV header
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Value |
* . .
* . .
* . .
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
#define LSPPING_TLV_TARGET_FEC_STACK 1
#define LSPPING_TLV_DOWNSTREAM_MAPPING 2
#define LSPPING_TLV_PAD 3
/* not assigned 4 */
#define LSPPING_TLV_VENDOR_ENTERPRISE 5
#define LSPPING_TLV_VENDOR_ENTERPRISE_LEN 4
/* not assigned 6 */
#define LSPPING_TLV_INTERFACE_LABEL_STACK 7
/* not assigned 8 */
#define LSPPING_TLV_ERROR_CODE 9
#define LSPPING_TLV_REPLY_TOS_BYTE 10
#define LSPPING_TLV_BFD_DISCRIMINATOR 15 /* draft-ietf-bfd-mpls-02 */
#define LSPPING_TLV_BFD_DISCRIMINATOR_LEN 4
#define LSPPING_TLV_VENDOR_PRIVATE 0xfc00
static const struct tok lspping_tlv_values[] = {
{ LSPPING_TLV_TARGET_FEC_STACK, "Target FEC Stack" },
{ LSPPING_TLV_DOWNSTREAM_MAPPING, "Downstream Mapping" },
{ LSPPING_TLV_PAD, "Pad" },
{ LSPPING_TLV_ERROR_CODE, "Error Code" },
{ LSPPING_TLV_VENDOR_ENTERPRISE, "Vendor Enterprise Code" },
{ LSPPING_TLV_INTERFACE_LABEL_STACK, "Interface Label Stack" },
{ LSPPING_TLV_REPLY_TOS_BYTE, "Reply TOS Byte" },
{ LSPPING_TLV_BFD_DISCRIMINATOR, "BFD Discriminator" },
{ LSPPING_TLV_VENDOR_PRIVATE, "Vendor Private Code" },
{ 0, NULL}
};
#define LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4 1
#define LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6 2
#define LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4 3
#define LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6 4
/* not assigned 5 */
#define LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4 6
#define LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6 7
#define LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT 8
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD 9
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW 10
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_129_PW 11
#define LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4 12
#define LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6 13
#define LSPPING_TLV_TARGETFEC_SUBTLV_GENERIC_IPV4 14
#define LSPPING_TLV_TARGETFEC_SUBTLV_GENERIC_IPV6 15
#define LSPPING_TLV_TARGETFEC_SUBTLV_NIL_FEC 16
static const struct tok lspping_tlvtargetfec_subtlv_values[] = {
{ LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4, "LDP IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6, "LDP IPv6 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4, "RSVP IPv4 Session Query"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6, "RSVP IPv6 Session Query"},
{ 5, "Reserved"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4, "VPN IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6, "VPN IPv6 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT, "L2 VPN endpoint"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD, "FEC 128 pseudowire (old)"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW, "FEC 128 pseudowire"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4, "BGP labeled IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6, "BGP labeled IPv6 prefix"},
{ 0, NULL}
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t {
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t {
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 tunnel end point address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Extended Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 tunnel sender address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | LSP ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t {
uint8_t tunnel_endpoint [4];
uint8_t res[2];
uint8_t tunnel_id[2];
uint8_t extended_tunnel_id[4];
uint8_t tunnel_sender [4];
uint8_t res2[2];
uint8_t lsp_id [2];
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 tunnel end point address |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Extended Tunnel ID |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 tunnel sender address |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | LSP ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t {
uint8_t tunnel_endpoint [16];
uint8_t res[2];
uint8_t tunnel_id[2];
uint8_t extended_tunnel_id[16];
uint8_t tunnel_sender [16];
uint8_t res2[2];
uint8_t lsp_id [2];
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t {
uint8_t rd [8];
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t {
uint8_t rd [8];
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's VE ID | Receiver's VE ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encapsulation Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 0 1 2 3
*/
struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t {
uint8_t rd [8];
uint8_t sender_ve_id [2];
uint8_t receiver_ve_id [2];
uint8_t encapsulation[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Remote PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_fec_128_pw_old {
uint8_t remote_pe_address [4];
uint8_t pw_id [4];
uint8_t pw_type[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Remote PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_fec_128_pw {
uint8_t sender_pe_address [4];
uint8_t remote_pe_address [4];
uint8_t pw_id [4];
uint8_t pw_type[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t {
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t {
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MTU | Address Type | Resvd (SBZ) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream IP Address (4 or 16 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Interface Address (4 or 16 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Multipath Type| Depth Limit | Multipath Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . (Multipath Information) .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Label | Protocol |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Label | Protocol |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
/* Enough to get the address type */
struct lspping_tlv_downstream_map_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
};
struct lspping_tlv_downstream_map_ipv4_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[4];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_ipv4_unmb_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[4];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_ipv6_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[16];
uint8_t downstream_interface[16];
};
struct lspping_tlv_downstream_map_ipv6_unmb_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[16];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_info_t {
uint8_t multipath_type;
uint8_t depth_limit;
uint8_t multipath_length [2];
};
#define LSPPING_AFI_IPV4 1
#define LSPPING_AFI_IPV4_UNMB 2
#define LSPPING_AFI_IPV6 3
#define LSPPING_AFI_IPV6_UNMB 4
static const struct tok lspping_tlv_downstream_addr_values[] = {
{ LSPPING_AFI_IPV4, "IPv4"},
{ LSPPING_AFI_IPV4_UNMB, "Unnumbered IPv4"},
{ LSPPING_AFI_IPV6, "IPv6"},
{ LSPPING_AFI_IPV6_UNMB, "IPv6"},
{ 0, NULL}
};
void
lspping_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lspping_common_header *lspping_com_header;
const struct lspping_tlv_header *lspping_tlv_header;
const struct lspping_tlv_header *lspping_subtlv_header;
const u_char *tptr,*tlv_tptr,*subtlv_tptr;
u_int tlen,lspping_tlv_len,lspping_tlv_type,tlv_tlen;
int tlv_hexdump,subtlv_hexdump;
u_int lspping_subtlv_len,lspping_subtlv_type;
struct timeval timestamp;
union {
const struct lspping_tlv_downstream_map_t *lspping_tlv_downstream_map;
const struct lspping_tlv_downstream_map_ipv4_t *lspping_tlv_downstream_map_ipv4;
const struct lspping_tlv_downstream_map_ipv4_unmb_t *lspping_tlv_downstream_map_ipv4_unmb;
const struct lspping_tlv_downstream_map_ipv6_t *lspping_tlv_downstream_map_ipv6;
const struct lspping_tlv_downstream_map_ipv6_unmb_t *lspping_tlv_downstream_map_ipv6_unmb;
const struct lspping_tlv_downstream_map_info_t *lspping_tlv_downstream_map_info;
} tlv_ptr;
union {
const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *lspping_tlv_targetfec_subtlv_ldp_ipv4;
const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *lspping_tlv_targetfec_subtlv_ldp_ipv6;
const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *lspping_tlv_targetfec_subtlv_rsvp_ipv4;
const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *lspping_tlv_targetfec_subtlv_rsvp_ipv6;
const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv4;
const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv6;
const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *lspping_tlv_targetfec_subtlv_l2vpn_endpt;
const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *lspping_tlv_targetfec_subtlv_l2vpn_vcid_old;
const struct lspping_tlv_targetfec_subtlv_fec_128_pw *lspping_tlv_targetfec_subtlv_l2vpn_vcid;
const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *lspping_tlv_targetfec_subtlv_bgp_ipv4;
const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *lspping_tlv_targetfec_subtlv_bgp_ipv6;
} subtlv_ptr;
tptr=pptr;
lspping_com_header = (const struct lspping_common_header *)pptr;
if (len < sizeof(const struct lspping_common_header))
goto tooshort;
ND_TCHECK(*lspping_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&lspping_com_header->version[0]) != LSPPING_VERSION) {
ND_PRINT((ndo, "LSP-PING version %u packet not supported",
EXTRACT_16BITS(&lspping_com_header->version[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LSP-PINGv%u, %s, seq %u, length: %u",
EXTRACT_16BITS(&lspping_com_header->version[0]),
tok2str(lspping_msg_type_values, "unknown (%u)",lspping_com_header->msg_type),
EXTRACT_32BITS(lspping_com_header->seq_number),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=len;
ND_PRINT((ndo, "\n\tLSP-PINGv%u, msg-type: %s (%u), length: %u\n\t reply-mode: %s (%u)",
EXTRACT_16BITS(&lspping_com_header->version[0]),
tok2str(lspping_msg_type_values, "unknown",lspping_com_header->msg_type),
lspping_com_header->msg_type,
len,
tok2str(lspping_reply_mode_values, "unknown",lspping_com_header->reply_mode),
lspping_com_header->reply_mode));
/*
* the following return codes require that the subcode is attached
* at the end of the translated token output
*/
if (lspping_com_header->return_code == 3 ||
lspping_com_header->return_code == 4 ||
lspping_com_header->return_code == 8 ||
lspping_com_header->return_code == 10 ||
lspping_com_header->return_code == 11 ||
lspping_com_header->return_code == 12 )
ND_PRINT((ndo, "\n\t Return Code: %s %u (%u)\n\t Return Subcode: (%u)",
tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code),
lspping_com_header->return_subcode,
lspping_com_header->return_code,
lspping_com_header->return_subcode));
else
ND_PRINT((ndo, "\n\t Return Code: %s (%u)\n\t Return Subcode: (%u)",
tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code),
lspping_com_header->return_code,
lspping_com_header->return_subcode));
ND_PRINT((ndo, "\n\t Sender Handle: 0x%08x, Sequence: %u",
EXTRACT_32BITS(lspping_com_header->sender_handle),
EXTRACT_32BITS(lspping_com_header->seq_number)));
timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_sent_sec);
timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_sent_usec);
ND_PRINT((ndo, "\n\t Sender Timestamp: "));
ts_print(ndo, ×tamp);
timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_sec);
timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_usec);
ND_PRINT((ndo, "Receiver Timestamp: "));
if ((timestamp.tv_sec != 0) && (timestamp.tv_usec != 0))
ts_print(ndo, ×tamp);
else
ND_PRINT((ndo, "no timestamp"));
tptr+=sizeof(const struct lspping_common_header);
tlen-=sizeof(const struct lspping_common_header);
while (tlen != 0) {
/* Does the TLV go past the end of the packet? */
if (tlen < sizeof(struct lspping_tlv_header))
goto tooshort;
/* did we capture enough for fully decoding the tlv header ? */
ND_TCHECK2(*tptr, sizeof(struct lspping_tlv_header));
lspping_tlv_header = (const struct lspping_tlv_header *)tptr;
lspping_tlv_type=EXTRACT_16BITS(lspping_tlv_header->type);
lspping_tlv_len=EXTRACT_16BITS(lspping_tlv_header->length);
ND_PRINT((ndo, "\n\t %s TLV (%u), length: %u",
tok2str(lspping_tlv_values,
"Unknown",
lspping_tlv_type),
lspping_tlv_type,
lspping_tlv_len));
/* some little sanity checking */
if (lspping_tlv_len == 0) {
tptr+=sizeof(struct lspping_tlv_header);
tlen-=sizeof(struct lspping_tlv_header);
continue; /* no value to dissect */
}
tlv_tptr=tptr+sizeof(struct lspping_tlv_header);
tlv_tlen=lspping_tlv_len; /* header not included -> no adjustment */
/* Does the TLV go past the end of the packet? */
if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header))
goto tooshort;
/* did we capture enough for fully decoding the tlv ? */
ND_TCHECK2(*tlv_tptr, lspping_tlv_len);
tlv_hexdump=FALSE;
switch(lspping_tlv_type) {
case LSPPING_TLV_TARGET_FEC_STACK:
while (tlv_tlen != 0) {
/* Does the subTLV header go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* did we capture enough for fully decoding the subtlv header ? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_header));
subtlv_hexdump=FALSE;
lspping_subtlv_header = (const struct lspping_tlv_header *)tlv_tptr;
lspping_subtlv_type=EXTRACT_16BITS(lspping_subtlv_header->type);
lspping_subtlv_len=EXTRACT_16BITS(lspping_subtlv_header->length);
subtlv_tptr=tlv_tptr+sizeof(struct lspping_tlv_header);
/* Does the subTLV go past the end of the TLV? */
if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for fully decoding the subTLV? */
ND_TCHECK2(*subtlv_tptr, lspping_subtlv_len);
ND_PRINT((ndo, "\n\t %s subTLV (%u), length: %u",
tok2str(lspping_tlvtargetfec_subtlv_values,
"Unknown",
lspping_subtlv_type),
lspping_subtlv_type,
lspping_subtlv_len));
switch(lspping_subtlv_type) {
case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 5) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 17) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 5) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 17) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 20) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 20"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \
"\n\t tunnel-id 0x%04x, extended tunnel-id %s",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_endpoint),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_sender),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->lsp_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_id),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->extended_tunnel_id)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 56) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 56"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \
"\n\t tunnel-id 0x%04x, extended tunnel-id %s",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_endpoint),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_sender),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->lsp_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_id),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->extended_tunnel_id)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 13) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 13"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, %s/%u",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->rd),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 25) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 25"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, %s/%u",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->rd),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 14) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt = \
(const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, Sender VE ID: %u, Receiver VE ID: %u" \
"\n\t Encapsulation Type: %s (%u)",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->rd),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->sender_ve_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->receiver_ve_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation)));
}
break;
/* the old L2VPN VCID subTLV does not have support for the sender field */
case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 10) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 10"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old = \
(const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *)subtlv_tptr;
ND_PRINT((ndo, "\n\t Remote PE: %s" \
"\n\t PW ID: 0x%08x, PW Type: %s (%u)",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->remote_pe_address),
EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 14) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid = \
(const struct lspping_tlv_targetfec_subtlv_fec_128_pw *)subtlv_tptr;
ND_PRINT((ndo, "\n\t Sender PE: %s, Remote PE: %s" \
"\n\t PW ID: 0x%08x, PW Type: %s (%u)",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->sender_pe_address),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->remote_pe_address),
EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type)));
}
break;
default:
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
break;
}
/* do we want to see an additionally subtlv hexdump ? */
if (ndo->ndo_vflag > 1 || subtlv_hexdump==TRUE)
print_unknown_data(ndo, tlv_tptr+sizeof(struct lspping_tlv_header), \
"\n\t ",
lspping_subtlv_len);
/* All subTLVs are aligned to four octet boundary */
if (lspping_subtlv_len % 4) {
lspping_subtlv_len += 4 - (lspping_subtlv_len % 4);
/* Does the subTLV, including padding, go past the end of the TLV? */
if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t\t TLV is too short"));
return;
}
}
tlv_tptr+=lspping_subtlv_len;
tlv_tlen-=lspping_subtlv_len+sizeof(struct lspping_tlv_header);
}
break;
case LSPPING_TLV_DOWNSTREAM_MAPPING:
/* Does the header go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough to get the address family? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_t));
tlv_ptr.lspping_tlv_downstream_map= \
(const struct lspping_tlv_downstream_map_t *)tlv_tptr;
/* that strange thing with the downstream map TLV is that until now
* we do not know if its IPv4 or IPv6 or is unnumbered; after
* we find the address-type, we recast the tlv_tptr and move on. */
ND_PRINT((ndo, "\n\t MTU: %u, Address-Type: %s (%u)",
EXTRACT_16BITS(tlv_ptr.lspping_tlv_downstream_map->mtu),
tok2str(lspping_tlv_downstream_addr_values,
"unknown",
tlv_ptr.lspping_tlv_downstream_map->address_type),
tlv_ptr.lspping_tlv_downstream_map->address_type));
switch(tlv_ptr.lspping_tlv_downstream_map->address_type) {
case LSPPING_AFI_IPV4:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_t));
tlv_ptr.lspping_tlv_downstream_map_ipv4= \
(const struct lspping_tlv_downstream_map_ipv4_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface IP: %s",
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_ip),
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_t);
break;
case LSPPING_AFI_IPV4_UNMB:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t));
tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb= \
(const struct lspping_tlv_downstream_map_ipv4_unmb_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface Index: 0x%08x",
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_ip),
EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t);
break;
case LSPPING_AFI_IPV6:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_t));
tlv_ptr.lspping_tlv_downstream_map_ipv6= \
(const struct lspping_tlv_downstream_map_ipv6_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface IP: %s",
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_ip),
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_t);
break;
case LSPPING_AFI_IPV6_UNMB:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t));
tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb= \
(const struct lspping_tlv_downstream_map_ipv6_unmb_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface Index: 0x%08x",
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_ip),
EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t);
break;
default:
/* should not happen ! - no error message - tok2str() has barked already */
break;
}
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_info_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_info_t));
tlv_ptr.lspping_tlv_downstream_map_info= \
(const struct lspping_tlv_downstream_map_info_t *)tlv_tptr;
/* FIXME add hash-key type, depth limit, multipath processing */
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_info_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_info_t);
/* FIXME print downstream labels */
tlv_hexdump=TRUE; /* dump the TLV until code complete */
break;
case LSPPING_TLV_BFD_DISCRIMINATOR:
if (tlv_tlen < LSPPING_TLV_BFD_DISCRIMINATOR_LEN) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
} else {
ND_TCHECK2(*tptr, LSPPING_TLV_BFD_DISCRIMINATOR_LEN);
ND_PRINT((ndo, "\n\t BFD Discriminator 0x%08x", EXTRACT_32BITS(tptr)));
}
break;
case LSPPING_TLV_VENDOR_ENTERPRISE:
{
uint32_t vendor_id;
if (tlv_tlen < LSPPING_TLV_VENDOR_ENTERPRISE_LEN) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
} else {
ND_TCHECK2(*tptr, LSPPING_TLV_VENDOR_ENTERPRISE_LEN);
vendor_id = EXTRACT_32BITS(tlv_tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (0x%04x)",
tok2str(smi_values, "Unknown", vendor_id),
vendor_id));
}
}
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case LSPPING_TLV_PAD:
case LSPPING_TLV_ERROR_CODE:
case LSPPING_TLV_VENDOR_PRIVATE:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tlv_tptr, "\n\t ", tlv_tlen);
break;
}
/* do we want to see an additionally tlv hexdump ? */
tlv_tooshort:
if (ndo->ndo_vflag > 1 || tlv_hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct lspping_tlv_header), "\n\t ",
lspping_tlv_len);
/* All TLVs are aligned to four octet boundary */
if (lspping_tlv_len % 4) {
lspping_tlv_len += (4 - lspping_tlv_len % 4);
/* Does the TLV, including padding, go past the end of the packet? */
if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header))
goto tooshort;
}
tptr+=lspping_tlv_len+sizeof(struct lspping_tlv_header);
tlen-=lspping_tlv_len+sizeof(struct lspping_tlv_header);
}
return;
tooshort:
ND_PRINT((ndo, "\n\t\t packet is too short"));
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2648_2 |
crossvul-cpp_data_bad_2592_0 | /*
* VC3/DNxHD decoder.
* Copyright (c) 2007 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com>
* Copyright (c) 2011 MirriAd Ltd
* Copyright (c) 2015 Christophe Gisquet
*
* 10 bit support added by MirriAd Ltd, Joseph Artsimovich <joseph@mirriad.com>
* Slice multithreading and MB interlaced support added by Christophe Gisquet
*
* 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 "libavutil/imgutils.h"
#include "libavutil/timer.h"
#include "avcodec.h"
#include "blockdsp.h"
#define UNCHECKED_BITSTREAM_READER 1
#include "get_bits.h"
#include "dnxhddata.h"
#include "idctdsp.h"
#include "internal.h"
#include "profiles.h"
#include "thread.h"
typedef struct RowContext {
DECLARE_ALIGNED(16, int16_t, blocks)[12][64];
int luma_scale[64];
int chroma_scale[64];
GetBitContext gb;
int last_dc[3];
int last_qscale;
int errors;
/** -1:not set yet 0:off=RGB 1:on=YUV 2:variable */
int format;
} RowContext;
typedef struct DNXHDContext {
AVCodecContext *avctx;
RowContext *rows;
BlockDSPContext bdsp;
const uint8_t* buf;
int buf_size;
int64_t cid; ///< compression id
unsigned int width, height;
enum AVPixelFormat pix_fmt;
unsigned int mb_width, mb_height;
uint32_t mb_scan_index[512];
int data_offset; // End of mb_scan_index, where macroblocks start
int cur_field; ///< current interlaced field
VLC ac_vlc, dc_vlc, run_vlc;
IDCTDSPContext idsp;
ScanTable scantable;
const CIDEntry *cid_table;
int bit_depth; // 8, 10, 12 or 0 if not initialized at all.
int is_444;
int mbaff;
int act;
int (*decode_dct_block)(const struct DNXHDContext *ctx,
RowContext *row, int n);
} DNXHDContext;
#define DNXHD_VLC_BITS 9
#define DNXHD_DC_VLC_BITS 7
static int dnxhd_decode_dct_block_8(const DNXHDContext *ctx,
RowContext *row, int n);
static int dnxhd_decode_dct_block_10(const DNXHDContext *ctx,
RowContext *row, int n);
static int dnxhd_decode_dct_block_10_444(const DNXHDContext *ctx,
RowContext *row, int n);
static int dnxhd_decode_dct_block_12(const DNXHDContext *ctx,
RowContext *row, int n);
static int dnxhd_decode_dct_block_12_444(const DNXHDContext *ctx,
RowContext *row, int n);
static av_cold int dnxhd_decode_init(AVCodecContext *avctx)
{
DNXHDContext *ctx = avctx->priv_data;
ctx->avctx = avctx;
ctx->cid = -1;
avctx->colorspace = AVCOL_SPC_BT709;
avctx->coded_width = FFALIGN(avctx->width, 16);
avctx->coded_height = FFALIGN(avctx->height, 16);
ctx->rows = av_mallocz_array(avctx->thread_count, sizeof(RowContext));
if (!ctx->rows)
return AVERROR(ENOMEM);
return 0;
}
static int dnxhd_init_vlc(DNXHDContext *ctx, uint32_t cid, int bitdepth)
{
if (cid != ctx->cid) {
int index;
if ((index = ff_dnxhd_get_cid_table(cid)) < 0) {
av_log(ctx->avctx, AV_LOG_ERROR, "unsupported cid %"PRIu32"\n", cid);
return AVERROR(ENOSYS);
}
if (ff_dnxhd_cid_table[index].bit_depth != bitdepth &&
ff_dnxhd_cid_table[index].bit_depth != DNXHD_VARIABLE) {
av_log(ctx->avctx, AV_LOG_ERROR, "bit depth mismatches %d %d\n", ff_dnxhd_cid_table[index].bit_depth, bitdepth);
return AVERROR_INVALIDDATA;
}
ctx->cid_table = &ff_dnxhd_cid_table[index];
av_log(ctx->avctx, AV_LOG_VERBOSE, "Profile cid %"PRIu32".\n", cid);
ff_free_vlc(&ctx->ac_vlc);
ff_free_vlc(&ctx->dc_vlc);
ff_free_vlc(&ctx->run_vlc);
init_vlc(&ctx->ac_vlc, DNXHD_VLC_BITS, 257,
ctx->cid_table->ac_bits, 1, 1,
ctx->cid_table->ac_codes, 2, 2, 0);
init_vlc(&ctx->dc_vlc, DNXHD_DC_VLC_BITS, bitdepth > 8 ? 14 : 12,
ctx->cid_table->dc_bits, 1, 1,
ctx->cid_table->dc_codes, 1, 1, 0);
init_vlc(&ctx->run_vlc, DNXHD_VLC_BITS, 62,
ctx->cid_table->run_bits, 1, 1,
ctx->cid_table->run_codes, 2, 2, 0);
ctx->cid = cid;
}
return 0;
}
static av_cold int dnxhd_decode_init_thread_copy(AVCodecContext *avctx)
{
DNXHDContext *ctx = avctx->priv_data;
ctx->avctx = avctx;
// make sure VLC tables will be loaded when cid is parsed
ctx->cid = -1;
ctx->rows = av_mallocz_array(avctx->thread_count, sizeof(RowContext));
if (!ctx->rows)
return AVERROR(ENOMEM);
return 0;
}
static int dnxhd_get_profile(int cid)
{
switch(cid) {
case 1270:
return FF_PROFILE_DNXHR_444;
case 1271:
return FF_PROFILE_DNXHR_HQX;
case 1272:
return FF_PROFILE_DNXHR_HQ;
case 1273:
return FF_PROFILE_DNXHR_SQ;
case 1274:
return FF_PROFILE_DNXHR_LB;
}
return FF_PROFILE_DNXHD;
}
static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame,
const uint8_t *buf, int buf_size,
int first_field)
{
int i, cid, ret;
int old_bit_depth = ctx->bit_depth, bitdepth;
uint64_t header_prefix;
if (buf_size < 0x280) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < 640).\n", buf_size);
return AVERROR_INVALIDDATA;
}
header_prefix = ff_dnxhd_parse_header_prefix(buf);
if (header_prefix == 0) {
av_log(ctx->avctx, AV_LOG_ERROR,
"unknown header 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n",
buf[0], buf[1], buf[2], buf[3], buf[4]);
return AVERROR_INVALIDDATA;
}
if (buf[5] & 2) { /* interlaced */
ctx->cur_field = buf[5] & 1;
frame->interlaced_frame = 1;
frame->top_field_first = first_field ^ ctx->cur_field;
av_log(ctx->avctx, AV_LOG_DEBUG,
"interlaced %d, cur field %d\n", buf[5] & 3, ctx->cur_field);
} else {
ctx->cur_field = 0;
}
ctx->mbaff = (buf[0x6] >> 5) & 1;
ctx->height = AV_RB16(buf + 0x18);
ctx->width = AV_RB16(buf + 0x1a);
switch(buf[0x21] >> 5) {
case 1: bitdepth = 8; break;
case 2: bitdepth = 10; break;
case 3: bitdepth = 12; break;
default:
av_log(ctx->avctx, AV_LOG_ERROR,
"Unknown bitdepth indicator (%d)\n", buf[0x21] >> 5);
return AVERROR_INVALIDDATA;
}
cid = AV_RB32(buf + 0x28);
ctx->avctx->profile = dnxhd_get_profile(cid);
if ((ret = dnxhd_init_vlc(ctx, cid, bitdepth)) < 0)
return ret;
if (ctx->mbaff && ctx->cid_table->cid != 1260)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive MB interlace flag in an unsupported profile.\n");
ctx->act = buf[0x2C] & 7;
if (ctx->act && ctx->cid_table->cid != 1256 && ctx->cid_table->cid != 1270)
av_log(ctx->avctx, AV_LOG_WARNING,
"Adaptive color transform in an unsupported profile.\n");
ctx->is_444 = (buf[0x2C] >> 6) & 1;
if (ctx->is_444) {
if (bitdepth == 8) {
avpriv_request_sample(ctx->avctx, "4:4:4 8 bits");
return AVERROR_INVALIDDATA;
} else if (bitdepth == 10) {
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P10
: AV_PIX_FMT_GBRP10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_12_444;
ctx->pix_fmt = ctx->act ? AV_PIX_FMT_YUV444P12
: AV_PIX_FMT_GBRP12;
}
} else if (bitdepth == 12) {
ctx->decode_dct_block = dnxhd_decode_dct_block_12;
ctx->pix_fmt = AV_PIX_FMT_YUV422P12;
} else if (bitdepth == 10) {
if (ctx->avctx->profile == FF_PROFILE_DNXHR_HQX)
ctx->decode_dct_block = dnxhd_decode_dct_block_10_444;
else
ctx->decode_dct_block = dnxhd_decode_dct_block_10;
ctx->pix_fmt = AV_PIX_FMT_YUV422P10;
} else {
ctx->decode_dct_block = dnxhd_decode_dct_block_8;
ctx->pix_fmt = AV_PIX_FMT_YUV422P;
}
ctx->avctx->bits_per_raw_sample = ctx->bit_depth = bitdepth;
if (ctx->bit_depth != old_bit_depth) {
ff_blockdsp_init(&ctx->bdsp, ctx->avctx);
ff_idctdsp_init(&ctx->idsp, ctx->avctx);
ff_init_scantable(ctx->idsp.idct_permutation, &ctx->scantable,
ff_zigzag_direct);
}
// make sure profile size constraints are respected
// DNx100 allows 1920->1440 and 1280->960 subsampling
if (ctx->width != ctx->cid_table->width &&
ctx->cid_table->width != DNXHD_VARIABLE) {
av_reduce(&ctx->avctx->sample_aspect_ratio.num,
&ctx->avctx->sample_aspect_ratio.den,
ctx->width, ctx->cid_table->width, 255);
ctx->width = ctx->cid_table->width;
}
if (buf_size < ctx->cid_table->coding_unit_size) {
av_log(ctx->avctx, AV_LOG_ERROR, "incorrect frame size (%d < %u).\n",
buf_size, ctx->cid_table->coding_unit_size);
return AVERROR_INVALIDDATA;
}
ctx->mb_width = (ctx->width + 15)>> 4;
ctx->mb_height = AV_RB16(buf + 0x16c);
if ((ctx->height + 15) >> 4 == ctx->mb_height && frame->interlaced_frame)
ctx->height <<= 1;
av_log(ctx->avctx, AV_LOG_VERBOSE, "%dx%d, 4:%s %d bits, MBAFF=%d ACT=%d\n",
ctx->width, ctx->height, ctx->is_444 ? "4:4" : "2:2",
ctx->bit_depth, ctx->mbaff, ctx->act);
// Newer format supports variable mb_scan_index sizes
if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) {
ctx->data_offset = 0x170 + (ctx->mb_height << 2);
} else {
if (ctx->mb_height > 68 ||
(ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb height too big: %d\n", ctx->mb_height);
return AVERROR_INVALIDDATA;
}
ctx->data_offset = 0x280;
}
if (buf_size < ctx->data_offset) {
av_log(ctx->avctx, AV_LOG_ERROR,
"buffer too small (%d < %d).\n", buf_size, ctx->data_offset);
return AVERROR_INVALIDDATA;
}
if (ctx->mb_height > FF_ARRAY_ELEMS(ctx->mb_scan_index)) {
av_log(ctx->avctx, AV_LOG_ERROR,
"mb_height too big (%d > %"SIZE_SPECIFIER").\n", ctx->mb_height, FF_ARRAY_ELEMS(ctx->mb_scan_index));
return AVERROR_INVALIDDATA;
}
for (i = 0; i < ctx->mb_height; i++) {
ctx->mb_scan_index[i] = AV_RB32(buf + 0x170 + (i << 2));
ff_dlog(ctx->avctx, "mb scan index %d, pos %d: %"PRIu32"\n",
i, 0x170 + (i << 2), ctx->mb_scan_index[i]);
if (buf_size - ctx->data_offset < ctx->mb_scan_index[i]) {
av_log(ctx->avctx, AV_LOG_ERROR,
"invalid mb scan index (%"PRIu32" vs %u).\n",
ctx->mb_scan_index[i], buf_size - ctx->data_offset);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
static av_always_inline int dnxhd_decode_dct_block(const DNXHDContext *ctx,
RowContext *row,
int n,
int index_bits,
int level_bias,
int level_shift,
int dc_shift)
{
int i, j, index1, index2, len, flags;
int level, component, sign;
const int *scale;
const uint8_t *weight_matrix;
const uint8_t *ac_info = ctx->cid_table->ac_info;
int16_t *block = row->blocks[n];
const int eob_index = ctx->cid_table->eob_index;
int ret = 0;
OPEN_READER(bs, &row->gb);
ctx->bdsp.clear_block(block);
if (!ctx->is_444) {
if (n & 2) {
component = 1 + (n & 1);
scale = row->chroma_scale;
weight_matrix = ctx->cid_table->chroma_weight;
} else {
component = 0;
scale = row->luma_scale;
weight_matrix = ctx->cid_table->luma_weight;
}
} else {
component = (n >> 1) % 3;
if (component) {
scale = row->chroma_scale;
weight_matrix = ctx->cid_table->chroma_weight;
} else {
scale = row->luma_scale;
weight_matrix = ctx->cid_table->luma_weight;
}
}
UPDATE_CACHE(bs, &row->gb);
GET_VLC(len, bs, &row->gb, ctx->dc_vlc.table, DNXHD_DC_VLC_BITS, 1);
if (len) {
level = GET_CACHE(bs, &row->gb);
LAST_SKIP_BITS(bs, &row->gb, len);
sign = ~level >> 31;
level = (NEG_USR32(sign ^ level, len) ^ sign) - sign;
row->last_dc[component] += level * (1 << dc_shift);
}
block[0] = row->last_dc[component];
i = 0;
UPDATE_CACHE(bs, &row->gb);
GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,
DNXHD_VLC_BITS, 2);
while (index1 != eob_index) {
level = ac_info[2*index1+0];
flags = ac_info[2*index1+1];
sign = SHOW_SBITS(bs, &row->gb, 1);
SKIP_BITS(bs, &row->gb, 1);
if (flags & 1) {
level += SHOW_UBITS(bs, &row->gb, index_bits) << 7;
SKIP_BITS(bs, &row->gb, index_bits);
}
if (flags & 2) {
UPDATE_CACHE(bs, &row->gb);
GET_VLC(index2, bs, &row->gb, ctx->run_vlc.table,
DNXHD_VLC_BITS, 2);
i += ctx->cid_table->run[index2];
}
if (++i > 63) {
av_log(ctx->avctx, AV_LOG_ERROR, "ac tex damaged %d, %d\n", n, i);
ret = -1;
break;
}
j = ctx->scantable.permutated[i];
level *= scale[i];
level += scale[i] >> 1;
if (level_bias < 32 || weight_matrix[i] != level_bias)
level += level_bias; // 1<<(level_shift-1)
level >>= level_shift;
block[j] = (level ^ sign) - sign;
UPDATE_CACHE(bs, &row->gb);
GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,
DNXHD_VLC_BITS, 2);
}
CLOSE_READER(bs, &row->gb);
return ret;
}
static int dnxhd_decode_dct_block_8(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 4, 32, 6, 0);
}
static int dnxhd_decode_dct_block_10(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 8, 4, 0);
}
static int dnxhd_decode_dct_block_10_444(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 32, 6, 0);
}
static int dnxhd_decode_dct_block_12(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 8, 4, 2);
}
static int dnxhd_decode_dct_block_12_444(const DNXHDContext *ctx,
RowContext *row, int n)
{
return dnxhd_decode_dct_block(ctx, row, n, 6, 32, 4, 2);
}
static int dnxhd_decode_macroblock(const DNXHDContext *ctx, RowContext *row,
AVFrame *frame, int x, int y)
{
int shift1 = ctx->bit_depth >= 10;
int dct_linesize_luma = frame->linesize[0];
int dct_linesize_chroma = frame->linesize[1];
uint8_t *dest_y, *dest_u, *dest_v;
int dct_y_offset, dct_x_offset;
int qscale, i, act;
int interlaced_mb = 0;
if (ctx->mbaff) {
interlaced_mb = get_bits1(&row->gb);
qscale = get_bits(&row->gb, 10);
} else {
qscale = get_bits(&row->gb, 11);
}
act = get_bits1(&row->gb);
if (act) {
if (!ctx->act) {
static int act_warned;
if (!act_warned) {
act_warned = 1;
av_log(ctx->avctx, AV_LOG_ERROR,
"ACT flag set, in violation of frame header.\n");
}
} else if (row->format == -1) {
row->format = act;
} else if (row->format != act) {
row->format = 2; // Variable
}
}
if (qscale != row->last_qscale) {
for (i = 0; i < 64; i++) {
row->luma_scale[i] = qscale * ctx->cid_table->luma_weight[i];
row->chroma_scale[i] = qscale * ctx->cid_table->chroma_weight[i];
}
row->last_qscale = qscale;
}
for (i = 0; i < 8 + 4 * ctx->is_444; i++) {
if (ctx->decode_dct_block(ctx, row, i) < 0)
return AVERROR_INVALIDDATA;
}
if (frame->interlaced_frame) {
dct_linesize_luma <<= 1;
dct_linesize_chroma <<= 1;
}
dest_y = frame->data[0] + ((y * dct_linesize_luma) << 4) + (x << (4 + shift1));
dest_u = frame->data[1] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));
dest_v = frame->data[2] + ((y * dct_linesize_chroma) << 4) + (x << (3 + shift1 + ctx->is_444));
if (frame->interlaced_frame && ctx->cur_field) {
dest_y += frame->linesize[0];
dest_u += frame->linesize[1];
dest_v += frame->linesize[2];
}
if (interlaced_mb) {
dct_linesize_luma <<= 1;
dct_linesize_chroma <<= 1;
}
dct_y_offset = interlaced_mb ? frame->linesize[0] : (dct_linesize_luma << 3);
dct_x_offset = 8 << shift1;
if (!ctx->is_444) {
ctx->idsp.idct_put(dest_y, dct_linesize_luma, row->blocks[0]);
ctx->idsp.idct_put(dest_y + dct_x_offset, dct_linesize_luma, row->blocks[1]);
ctx->idsp.idct_put(dest_y + dct_y_offset, dct_linesize_luma, row->blocks[4]);
ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[5]);
if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) {
dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3);
ctx->idsp.idct_put(dest_u, dct_linesize_chroma, row->blocks[2]);
ctx->idsp.idct_put(dest_v, dct_linesize_chroma, row->blocks[3]);
ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, row->blocks[6]);
ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, row->blocks[7]);
}
} else {
ctx->idsp.idct_put(dest_y, dct_linesize_luma, row->blocks[0]);
ctx->idsp.idct_put(dest_y + dct_x_offset, dct_linesize_luma, row->blocks[1]);
ctx->idsp.idct_put(dest_y + dct_y_offset, dct_linesize_luma, row->blocks[6]);
ctx->idsp.idct_put(dest_y + dct_y_offset + dct_x_offset, dct_linesize_luma, row->blocks[7]);
if (!(ctx->avctx->flags & AV_CODEC_FLAG_GRAY)) {
dct_y_offset = interlaced_mb ? frame->linesize[1] : (dct_linesize_chroma << 3);
ctx->idsp.idct_put(dest_u, dct_linesize_chroma, row->blocks[2]);
ctx->idsp.idct_put(dest_u + dct_x_offset, dct_linesize_chroma, row->blocks[3]);
ctx->idsp.idct_put(dest_u + dct_y_offset, dct_linesize_chroma, row->blocks[8]);
ctx->idsp.idct_put(dest_u + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[9]);
ctx->idsp.idct_put(dest_v, dct_linesize_chroma, row->blocks[4]);
ctx->idsp.idct_put(dest_v + dct_x_offset, dct_linesize_chroma, row->blocks[5]);
ctx->idsp.idct_put(dest_v + dct_y_offset, dct_linesize_chroma, row->blocks[10]);
ctx->idsp.idct_put(dest_v + dct_y_offset + dct_x_offset, dct_linesize_chroma, row->blocks[11]);
}
}
return 0;
}
static int dnxhd_decode_row(AVCodecContext *avctx, void *data,
int rownb, int threadnb)
{
const DNXHDContext *ctx = avctx->priv_data;
uint32_t offset = ctx->mb_scan_index[rownb];
RowContext *row = ctx->rows + threadnb;
int x;
row->last_dc[0] =
row->last_dc[1] =
row->last_dc[2] = 1 << (ctx->bit_depth + 2); // for levels +2^(bitdepth-1)
init_get_bits(&row->gb, ctx->buf + offset, (ctx->buf_size - offset) << 3);
for (x = 0; x < ctx->mb_width; x++) {
//START_TIMER;
int ret = dnxhd_decode_macroblock(ctx, row, data, x, rownb);
if (ret < 0) {
row->errors++;
return ret;
}
//STOP_TIMER("decode macroblock");
}
return 0;
}
static int dnxhd_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame, AVPacket *avpkt)
{
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
DNXHDContext *ctx = avctx->priv_data;
ThreadFrame frame = { .f = data };
AVFrame *picture = data;
int first_field = 1;
int ret, i;
ff_dlog(avctx, "frame size %d\n", buf_size);
for (i = 0; i < avctx->thread_count; i++)
ctx->rows[i].format = -1;
decode_coding_unit:
if ((ret = dnxhd_decode_header(ctx, picture, buf, buf_size, first_field)) < 0)
return ret;
if ((avctx->width || avctx->height) &&
(ctx->width != avctx->width || ctx->height != avctx->height)) {
av_log(avctx, AV_LOG_WARNING, "frame size changed: %dx%d -> %ux%u\n",
avctx->width, avctx->height, ctx->width, ctx->height);
first_field = 1;
}
if (avctx->pix_fmt != AV_PIX_FMT_NONE && avctx->pix_fmt != ctx->pix_fmt) {
av_log(avctx, AV_LOG_WARNING, "pix_fmt changed: %s -> %s\n",
av_get_pix_fmt_name(avctx->pix_fmt), av_get_pix_fmt_name(ctx->pix_fmt));
first_field = 1;
}
avctx->pix_fmt = ctx->pix_fmt;
ret = ff_set_dimensions(avctx, ctx->width, ctx->height);
if (ret < 0)
return ret;
if (first_field) {
if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)
return ret;
picture->pict_type = AV_PICTURE_TYPE_I;
picture->key_frame = 1;
}
ctx->buf_size = buf_size - ctx->data_offset;
ctx->buf = buf + ctx->data_offset;
avctx->execute2(avctx, dnxhd_decode_row, picture, NULL, ctx->mb_height);
if (first_field && picture->interlaced_frame) {
buf += ctx->cid_table->coding_unit_size;
buf_size -= ctx->cid_table->coding_unit_size;
first_field = 0;
goto decode_coding_unit;
}
ret = 0;
for (i = 0; i < avctx->thread_count; i++) {
ret += ctx->rows[i].errors;
ctx->rows[i].errors = 0;
}
if (ctx->act) {
static int act_warned;
int format = ctx->rows[0].format;
for (i = 1; i < avctx->thread_count; i++) {
if (ctx->rows[i].format != format &&
ctx->rows[i].format != -1 /* not run */) {
format = 2;
break;
}
}
switch (format) {
case -1:
case 2:
if (!act_warned) {
act_warned = 1;
av_log(ctx->avctx, AV_LOG_ERROR,
"Unsupported: variable ACT flag.\n");
}
break;
case 0:
ctx->pix_fmt = ctx->bit_depth==10
? AV_PIX_FMT_GBRP10 : AV_PIX_FMT_GBRP12;
break;
case 1:
ctx->pix_fmt = ctx->bit_depth==10
? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV444P12;
break;
}
}
avctx->pix_fmt = ctx->pix_fmt;
if (ret) {
av_log(ctx->avctx, AV_LOG_ERROR, "%d lines with errors\n", ret);
return AVERROR_INVALIDDATA;
}
*got_frame = 1;
return avpkt->size;
}
static av_cold int dnxhd_decode_close(AVCodecContext *avctx)
{
DNXHDContext *ctx = avctx->priv_data;
ff_free_vlc(&ctx->ac_vlc);
ff_free_vlc(&ctx->dc_vlc);
ff_free_vlc(&ctx->run_vlc);
av_freep(&ctx->rows);
return 0;
}
AVCodec ff_dnxhd_decoder = {
.name = "dnxhd",
.long_name = NULL_IF_CONFIG_SMALL("VC3/DNxHD"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_DNXHD,
.priv_data_size = sizeof(DNXHDContext),
.init = dnxhd_decode_init,
.close = dnxhd_decode_close,
.decode = dnxhd_decode_frame,
.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_FRAME_THREADS |
AV_CODEC_CAP_SLICE_THREADS,
.init_thread_copy = ONLY_IF_THREADS_ENABLED(dnxhd_decode_init_thread_copy),
.profiles = NULL_IF_CONFIG_SMALL(ff_dnxhd_profiles),
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2592_0 |
crossvul-cpp_data_good_289_0 | /*
* Copyright (C) 1999 WIDE Project.
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ 2, "Administratively Shutdown"},
{ 3, "Peer Unconfigured"},
{ 4, "Administratively Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN + 4;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601)
ND_PRINT((ndo, " = %s", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4)));
/* rfc1888 mapped IPv6 address ? */
else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "[|BGP]"));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "[|BGP]"));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " [|BGP]"));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, " [|BGP]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_289_0 |
crossvul-cpp_data_bad_2731_0 | /*
* Copyright (c) 1992, 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Original code by Matt Thomas, Digital Equipment Corporation
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete IS-IS & CLNP support.
*/
/* \summary: ISO CLNS, ESIS, and ISIS printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "ether.h"
#include "nlpid.h"
#include "extract.h"
#include "gmpls.h"
#include "oui.h"
#include "signature.h"
static const char tstr[] = " [|isis]";
/*
* IS-IS is defined in ISO 10589. Look there for protocol definitions.
*/
#define SYSTEM_ID_LEN ETHER_ADDR_LEN
#define NODE_ID_LEN SYSTEM_ID_LEN+1
#define LSP_ID_LEN SYSTEM_ID_LEN+2
#define ISIS_VERSION 1
#define ESIS_VERSION 1
#define CLNP_VERSION 1
#define ISIS_PDU_TYPE_MASK 0x1F
#define ESIS_PDU_TYPE_MASK 0x1F
#define CLNP_PDU_TYPE_MASK 0x1F
#define CLNP_FLAG_MASK 0xE0
#define ISIS_LAN_PRIORITY_MASK 0x7F
#define ISIS_PDU_L1_LAN_IIH 15
#define ISIS_PDU_L2_LAN_IIH 16
#define ISIS_PDU_PTP_IIH 17
#define ISIS_PDU_L1_LSP 18
#define ISIS_PDU_L2_LSP 20
#define ISIS_PDU_L1_CSNP 24
#define ISIS_PDU_L2_CSNP 25
#define ISIS_PDU_L1_PSNP 26
#define ISIS_PDU_L2_PSNP 27
static const struct tok isis_pdu_values[] = {
{ ISIS_PDU_L1_LAN_IIH, "L1 Lan IIH"},
{ ISIS_PDU_L2_LAN_IIH, "L2 Lan IIH"},
{ ISIS_PDU_PTP_IIH, "p2p IIH"},
{ ISIS_PDU_L1_LSP, "L1 LSP"},
{ ISIS_PDU_L2_LSP, "L2 LSP"},
{ ISIS_PDU_L1_CSNP, "L1 CSNP"},
{ ISIS_PDU_L2_CSNP, "L2 CSNP"},
{ ISIS_PDU_L1_PSNP, "L1 PSNP"},
{ ISIS_PDU_L2_PSNP, "L2 PSNP"},
{ 0, NULL}
};
/*
* A TLV is a tuple of a type, length and a value and is normally used for
* encoding information in all sorts of places. This is an enumeration of
* the well known types.
*
* list taken from rfc3359 plus some memory from veterans ;-)
*/
#define ISIS_TLV_AREA_ADDR 1 /* iso10589 */
#define ISIS_TLV_IS_REACH 2 /* iso10589 */
#define ISIS_TLV_ESNEIGH 3 /* iso10589 */
#define ISIS_TLV_PART_DIS 4 /* iso10589 */
#define ISIS_TLV_PREFIX_NEIGH 5 /* iso10589 */
#define ISIS_TLV_ISNEIGH 6 /* iso10589 */
#define ISIS_TLV_ISNEIGH_VARLEN 7 /* iso10589 */
#define ISIS_TLV_PADDING 8 /* iso10589 */
#define ISIS_TLV_LSP 9 /* iso10589 */
#define ISIS_TLV_AUTH 10 /* iso10589, rfc3567 */
#define ISIS_TLV_CHECKSUM 12 /* rfc3358 */
#define ISIS_TLV_CHECKSUM_MINLEN 2
#define ISIS_TLV_POI 13 /* rfc6232 */
#define ISIS_TLV_LSP_BUFFERSIZE 14 /* iso10589 rev2 */
#define ISIS_TLV_LSP_BUFFERSIZE_MINLEN 2
#define ISIS_TLV_EXT_IS_REACH 22 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_IS_ALIAS_ID 24 /* draft-ietf-isis-ext-lsp-frags-02 */
#define ISIS_TLV_DECNET_PHASE4 42
#define ISIS_TLV_LUCENT_PRIVATE 66
#define ISIS_TLV_INT_IP_REACH 128 /* rfc1195, rfc2966 */
#define ISIS_TLV_PROTOCOLS 129 /* rfc1195 */
#define ISIS_TLV_EXT_IP_REACH 130 /* rfc1195, rfc2966 */
#define ISIS_TLV_IDRP_INFO 131 /* rfc1195 */
#define ISIS_TLV_IDRP_INFO_MINLEN 1
#define ISIS_TLV_IPADDR 132 /* rfc1195 */
#define ISIS_TLV_IPAUTH 133 /* rfc1195 */
#define ISIS_TLV_TE_ROUTER_ID 134 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_EXTD_IP_REACH 135 /* draft-ietf-isis-traffic-05 */
#define ISIS_TLV_HOSTNAME 137 /* rfc2763 */
#define ISIS_TLV_SHARED_RISK_GROUP 138 /* draft-ietf-isis-gmpls-extensions */
#define ISIS_TLV_MT_PORT_CAP 143 /* rfc6165 */
#define ISIS_TLV_MT_CAPABILITY 144 /* rfc6329 */
#define ISIS_TLV_NORTEL_PRIVATE1 176
#define ISIS_TLV_NORTEL_PRIVATE2 177
#define ISIS_TLV_RESTART_SIGNALING 211 /* rfc3847 */
#define ISIS_TLV_RESTART_SIGNALING_FLAGLEN 1
#define ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN 2
#define ISIS_TLV_MT_IS_REACH 222 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED 229 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_MT_SUPPORTED_MINLEN 2
#define ISIS_TLV_IP6ADDR 232 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP_REACH 235 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_IP6_REACH 236 /* draft-ietf-isis-ipv6-02 */
#define ISIS_TLV_MT_IP6_REACH 237 /* draft-ietf-isis-wg-multi-topology-05 */
#define ISIS_TLV_PTP_ADJ 240 /* rfc3373 */
#define ISIS_TLV_IIH_SEQNR 241 /* draft-shen-isis-iih-sequence-00 */
#define ISIS_TLV_IIH_SEQNR_MINLEN 4
#define ISIS_TLV_VENDOR_PRIVATE 250 /* draft-ietf-isis-experimental-tlv-01 */
#define ISIS_TLV_VENDOR_PRIVATE_MINLEN 3
static const struct tok isis_tlv_values[] = {
{ ISIS_TLV_AREA_ADDR, "Area address(es)"},
{ ISIS_TLV_IS_REACH, "IS Reachability"},
{ ISIS_TLV_ESNEIGH, "ES Neighbor(s)"},
{ ISIS_TLV_PART_DIS, "Partition DIS"},
{ ISIS_TLV_PREFIX_NEIGH, "Prefix Neighbors"},
{ ISIS_TLV_ISNEIGH, "IS Neighbor(s)"},
{ ISIS_TLV_ISNEIGH_VARLEN, "IS Neighbor(s) (variable length)"},
{ ISIS_TLV_PADDING, "Padding"},
{ ISIS_TLV_LSP, "LSP entries"},
{ ISIS_TLV_AUTH, "Authentication"},
{ ISIS_TLV_CHECKSUM, "Checksum"},
{ ISIS_TLV_POI, "Purge Originator Identifier"},
{ ISIS_TLV_LSP_BUFFERSIZE, "LSP Buffersize"},
{ ISIS_TLV_EXT_IS_REACH, "Extended IS Reachability"},
{ ISIS_TLV_IS_ALIAS_ID, "IS Alias ID"},
{ ISIS_TLV_DECNET_PHASE4, "DECnet Phase IV"},
{ ISIS_TLV_LUCENT_PRIVATE, "Lucent Proprietary"},
{ ISIS_TLV_INT_IP_REACH, "IPv4 Internal Reachability"},
{ ISIS_TLV_PROTOCOLS, "Protocols supported"},
{ ISIS_TLV_EXT_IP_REACH, "IPv4 External Reachability"},
{ ISIS_TLV_IDRP_INFO, "Inter-Domain Information Type"},
{ ISIS_TLV_IPADDR, "IPv4 Interface address(es)"},
{ ISIS_TLV_IPAUTH, "IPv4 authentication (deprecated)"},
{ ISIS_TLV_TE_ROUTER_ID, "Traffic Engineering Router ID"},
{ ISIS_TLV_EXTD_IP_REACH, "Extended IPv4 Reachability"},
{ ISIS_TLV_SHARED_RISK_GROUP, "Shared Risk Link Group"},
{ ISIS_TLV_MT_PORT_CAP, "Multi-Topology-Aware Port Capability"},
{ ISIS_TLV_MT_CAPABILITY, "Multi-Topology Capability"},
{ ISIS_TLV_NORTEL_PRIVATE1, "Nortel Proprietary"},
{ ISIS_TLV_NORTEL_PRIVATE2, "Nortel Proprietary"},
{ ISIS_TLV_HOSTNAME, "Hostname"},
{ ISIS_TLV_RESTART_SIGNALING, "Restart Signaling"},
{ ISIS_TLV_MT_IS_REACH, "Multi Topology IS Reachability"},
{ ISIS_TLV_MT_SUPPORTED, "Multi Topology"},
{ ISIS_TLV_IP6ADDR, "IPv6 Interface address(es)"},
{ ISIS_TLV_MT_IP_REACH, "Multi-Topology IPv4 Reachability"},
{ ISIS_TLV_IP6_REACH, "IPv6 reachability"},
{ ISIS_TLV_MT_IP6_REACH, "Multi-Topology IP6 Reachability"},
{ ISIS_TLV_PTP_ADJ, "Point-to-point Adjacency State"},
{ ISIS_TLV_IIH_SEQNR, "Hello PDU Sequence Number"},
{ ISIS_TLV_VENDOR_PRIVATE, "Vendor Private"},
{ 0, NULL }
};
#define ESIS_OPTION_PROTOCOLS 129
#define ESIS_OPTION_QOS_MAINTENANCE 195 /* iso9542 */
#define ESIS_OPTION_SECURITY 197 /* iso9542 */
#define ESIS_OPTION_ES_CONF_TIME 198 /* iso9542 */
#define ESIS_OPTION_PRIORITY 205 /* iso9542 */
#define ESIS_OPTION_ADDRESS_MASK 225 /* iso9542 */
#define ESIS_OPTION_SNPA_MASK 226 /* iso9542 */
static const struct tok esis_option_values[] = {
{ ESIS_OPTION_PROTOCOLS, "Protocols supported"},
{ ESIS_OPTION_QOS_MAINTENANCE, "QoS Maintenance" },
{ ESIS_OPTION_SECURITY, "Security" },
{ ESIS_OPTION_ES_CONF_TIME, "ES Configuration Time" },
{ ESIS_OPTION_PRIORITY, "Priority" },
{ ESIS_OPTION_ADDRESS_MASK, "Addressk Mask" },
{ ESIS_OPTION_SNPA_MASK, "SNPA Mask" },
{ 0, NULL }
};
#define CLNP_OPTION_DISCARD_REASON 193
#define CLNP_OPTION_QOS_MAINTENANCE 195 /* iso8473 */
#define CLNP_OPTION_SECURITY 197 /* iso8473 */
#define CLNP_OPTION_SOURCE_ROUTING 200 /* iso8473 */
#define CLNP_OPTION_ROUTE_RECORDING 203 /* iso8473 */
#define CLNP_OPTION_PADDING 204 /* iso8473 */
#define CLNP_OPTION_PRIORITY 205 /* iso8473 */
static const struct tok clnp_option_values[] = {
{ CLNP_OPTION_DISCARD_REASON, "Discard Reason"},
{ CLNP_OPTION_PRIORITY, "Priority"},
{ CLNP_OPTION_QOS_MAINTENANCE, "QoS Maintenance"},
{ CLNP_OPTION_SECURITY, "Security"},
{ CLNP_OPTION_SOURCE_ROUTING, "Source Routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "Route Recording"},
{ CLNP_OPTION_PADDING, "Padding"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_class_values[] = {
{ 0x0, "General"},
{ 0x8, "Address"},
{ 0x9, "Source Routeing"},
{ 0xa, "Lifetime"},
{ 0xb, "PDU Discarded"},
{ 0xc, "Reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_general_values[] = {
{ 0x0, "Reason not specified"},
{ 0x1, "Protocol procedure error"},
{ 0x2, "Incorrect checksum"},
{ 0x3, "PDU discarded due to congestion"},
{ 0x4, "Header syntax error (cannot be parsed)"},
{ 0x5, "Segmentation needed but not permitted"},
{ 0x6, "Incomplete PDU received"},
{ 0x7, "Duplicate option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_address_values[] = {
{ 0x0, "Destination address unreachable"},
{ 0x1, "Destination address unknown"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_source_routeing_values[] = {
{ 0x0, "Unspecified source routeing error"},
{ 0x1, "Syntax error in source routeing field"},
{ 0x2, "Unknown address in source routeing field"},
{ 0x3, "Path not acceptable"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_lifetime_values[] = {
{ 0x0, "Lifetime expired while data unit in transit"},
{ 0x1, "Lifetime expired during reassembly"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_pdu_discard_values[] = {
{ 0x0, "Unsupported option not specified"},
{ 0x1, "Unsupported protocol version"},
{ 0x2, "Unsupported security option"},
{ 0x3, "Unsupported source routeing option"},
{ 0x4, "Unsupported recording of route option"},
{ 0, NULL }
};
static const struct tok clnp_option_rfd_reassembly_values[] = {
{ 0x0, "Reassembly interference"},
{ 0, NULL }
};
/* array of 16 error-classes */
static const struct tok *clnp_option_rfd_error_class[] = {
clnp_option_rfd_general_values,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
clnp_option_rfd_address_values,
clnp_option_rfd_source_routeing_values,
clnp_option_rfd_lifetime_values,
clnp_option_rfd_pdu_discard_values,
clnp_option_rfd_reassembly_values,
NULL,
NULL,
NULL
};
#define CLNP_OPTION_OPTION_QOS_MASK 0x3f
#define CLNP_OPTION_SCOPE_MASK 0xc0
#define CLNP_OPTION_SCOPE_SA_SPEC 0x40
#define CLNP_OPTION_SCOPE_DA_SPEC 0x80
#define CLNP_OPTION_SCOPE_GLOBAL 0xc0
static const struct tok clnp_option_scope_values[] = {
{ CLNP_OPTION_SCOPE_SA_SPEC, "Source Address Specific"},
{ CLNP_OPTION_SCOPE_DA_SPEC, "Destination Address Specific"},
{ CLNP_OPTION_SCOPE_GLOBAL, "Globally unique"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_values[] = {
{ 0x0, "partial"},
{ 0x1, "complete"},
{ 0, NULL }
};
static const struct tok clnp_option_sr_rr_string_values[] = {
{ CLNP_OPTION_SOURCE_ROUTING, "source routing"},
{ CLNP_OPTION_ROUTE_RECORDING, "recording of route in progress"},
{ 0, NULL }
};
static const struct tok clnp_option_qos_global_values[] = {
{ 0x20, "reserved"},
{ 0x10, "sequencing vs. delay"},
{ 0x08, "congested"},
{ 0x04, "delay vs. cost"},
{ 0x02, "error vs. delay"},
{ 0x01, "error vs. cost"},
{ 0, NULL }
};
#define ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP 3 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID 4 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID 5 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR 6 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR 8 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW 9 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW 10 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW 11 /* rfc4124 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD 12 /* draft-ietf-tewg-diff-te-proto-06 */
#define ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC 18 /* draft-ietf-isis-traffic-05 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE 19 /* draft-ietf-isis-link-attr-01 */
#define ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE 20 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR 21 /* rfc4205 */
#define ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS 22 /* rfc4124 */
#define ISIS_SUBTLV_SPB_METRIC 29 /* rfc6329 */
static const struct tok isis_ext_is_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP, "Administrative groups" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID, "Link Local/Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID, "Link Remote Identifier" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR, "IPv4 interface address" },
{ ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR, "IPv4 neighbor address" },
{ ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW, "Maximum link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW, "Reservable link bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW, "Unreserved bandwidth" },
{ ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC, "Traffic Engineering Metric" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE, "Link Attribute" },
{ ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE, "Link Protection Type" },
{ ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR, "Interface Switching Capability" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD, "Bandwidth Constraints (old)" },
{ ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS, "Bandwidth Constraints" },
{ ISIS_SUBTLV_SPB_METRIC, "SPB Metric" },
{ 250, "Reserved for cisco specific extensions" },
{ 251, "Reserved for cisco specific extensions" },
{ 252, "Reserved for cisco specific extensions" },
{ 253, "Reserved for cisco specific extensions" },
{ 254, "Reserved for cisco specific extensions" },
{ 255, "Reserved for future expansion" },
{ 0, NULL }
};
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32 1 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64 2 /* draft-ietf-isis-admin-tags-01 */
#define ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR 117 /* draft-ietf-isis-wg-multi-topology-05 */
static const struct tok isis_ext_ip_reach_subtlv_values[] = {
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32, "32-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64, "64-Bit Administrative tag" },
{ ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR, "Management Prefix Color" },
{ 0, NULL }
};
static const struct tok isis_subtlv_link_attribute_values[] = {
{ 0x01, "Local Protection Available" },
{ 0x02, "Link excluded from local protection path" },
{ 0x04, "Local maintenance required"},
{ 0, NULL }
};
#define ISIS_SUBTLV_AUTH_SIMPLE 1
#define ISIS_SUBTLV_AUTH_GENERIC 3 /* rfc 5310 */
#define ISIS_SUBTLV_AUTH_MD5 54
#define ISIS_SUBTLV_AUTH_MD5_LEN 16
#define ISIS_SUBTLV_AUTH_PRIVATE 255
static const struct tok isis_subtlv_auth_values[] = {
{ ISIS_SUBTLV_AUTH_SIMPLE, "simple text password"},
{ ISIS_SUBTLV_AUTH_GENERIC, "Generic Crypto key-id"},
{ ISIS_SUBTLV_AUTH_MD5, "HMAC-MD5 password"},
{ ISIS_SUBTLV_AUTH_PRIVATE, "Routing Domain private password"},
{ 0, NULL }
};
#define ISIS_SUBTLV_IDRP_RES 0
#define ISIS_SUBTLV_IDRP_LOCAL 1
#define ISIS_SUBTLV_IDRP_ASN 2
static const struct tok isis_subtlv_idrp_values[] = {
{ ISIS_SUBTLV_IDRP_RES, "Reserved"},
{ ISIS_SUBTLV_IDRP_LOCAL, "Routing-Domain Specific"},
{ ISIS_SUBTLV_IDRP_ASN, "AS Number Tag"},
{ 0, NULL}
};
#define ISIS_SUBTLV_SPB_MCID 4
#define ISIS_SUBTLV_SPB_DIGEST 5
#define ISIS_SUBTLV_SPB_BVID 6
#define ISIS_SUBTLV_SPB_INSTANCE 1
#define ISIS_SUBTLV_SPBM_SI 3
#define ISIS_SPB_MCID_LEN 51
#define ISIS_SUBTLV_SPB_MCID_MIN_LEN 102
#define ISIS_SUBTLV_SPB_DIGEST_MIN_LEN 33
#define ISIS_SUBTLV_SPB_BVID_MIN_LEN 6
#define ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN 19
#define ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN 8
static const struct tok isis_mt_port_cap_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_MCID, "SPB MCID" },
{ ISIS_SUBTLV_SPB_DIGEST, "SPB Digest" },
{ ISIS_SUBTLV_SPB_BVID, "SPB BVID" },
{ 0, NULL }
};
static const struct tok isis_mt_capability_subtlv_values[] = {
{ ISIS_SUBTLV_SPB_INSTANCE, "SPB Instance" },
{ ISIS_SUBTLV_SPBM_SI, "SPBM Service Identifier and Unicast Address" },
{ 0, NULL }
};
struct isis_spb_mcid {
uint8_t format_id;
uint8_t name[32];
uint8_t revision_lvl[2];
uint8_t digest[16];
};
struct isis_subtlv_spb_mcid {
struct isis_spb_mcid mcid;
struct isis_spb_mcid aux_mcid;
};
struct isis_subtlv_spb_instance {
uint8_t cist_root_id[8];
uint8_t cist_external_root_path_cost[4];
uint8_t bridge_priority[2];
uint8_t spsourceid[4];
uint8_t no_of_trees;
};
#define CLNP_SEGMENT_PART 0x80
#define CLNP_MORE_SEGMENTS 0x40
#define CLNP_REQUEST_ER 0x20
static const struct tok clnp_flag_values[] = {
{ CLNP_SEGMENT_PART, "Segmentation permitted"},
{ CLNP_MORE_SEGMENTS, "more Segments"},
{ CLNP_REQUEST_ER, "request Error Report"},
{ 0, NULL}
};
#define ISIS_MASK_LSP_OL_BIT(x) ((x)&0x4)
#define ISIS_MASK_LSP_ISTYPE_BITS(x) ((x)&0x3)
#define ISIS_MASK_LSP_PARTITION_BIT(x) ((x)&0x80)
#define ISIS_MASK_LSP_ATT_BITS(x) ((x)&0x78)
#define ISIS_MASK_LSP_ATT_ERROR_BIT(x) ((x)&0x40)
#define ISIS_MASK_LSP_ATT_EXPENSE_BIT(x) ((x)&0x20)
#define ISIS_MASK_LSP_ATT_DELAY_BIT(x) ((x)&0x10)
#define ISIS_MASK_LSP_ATT_DEFAULT_BIT(x) ((x)&0x8)
#define ISIS_MASK_MTID(x) ((x)&0x0fff)
#define ISIS_MASK_MTFLAGS(x) ((x)&0xf000)
static const struct tok isis_mt_flag_values[] = {
{ 0x4000, "ATT bit set"},
{ 0x8000, "Overload bit set"},
{ 0, NULL}
};
#define ISIS_MASK_TLV_EXTD_IP_UPDOWN(x) ((x)&0x80)
#define ISIS_MASK_TLV_EXTD_IP_SUBTLV(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_IE(x) ((x)&0x40)
#define ISIS_MASK_TLV_EXTD_IP6_SUBTLV(x) ((x)&0x20)
#define ISIS_LSP_TLV_METRIC_SUPPORTED(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_IE(x) ((x)&0x40)
#define ISIS_LSP_TLV_METRIC_UPDOWN(x) ((x)&0x80)
#define ISIS_LSP_TLV_METRIC_VALUE(x) ((x)&0x3f)
#define ISIS_MASK_TLV_SHARED_RISK_GROUP(x) ((x)&0x1)
static const struct tok isis_mt_values[] = {
{ 0, "IPv4 unicast"},
{ 1, "In-Band Management"},
{ 2, "IPv6 unicast"},
{ 3, "Multicast"},
{ 4095, "Development, Experimental or Proprietary"},
{ 0, NULL }
};
static const struct tok isis_iih_circuit_type_values[] = {
{ 1, "Level 1 only"},
{ 2, "Level 2 only"},
{ 3, "Level 1, Level 2"},
{ 0, NULL}
};
#define ISIS_LSP_TYPE_UNUSED0 0
#define ISIS_LSP_TYPE_LEVEL_1 1
#define ISIS_LSP_TYPE_UNUSED2 2
#define ISIS_LSP_TYPE_LEVEL_2 3
static const struct tok isis_lsp_istype_values[] = {
{ ISIS_LSP_TYPE_UNUSED0, "Unused 0x0 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_1, "L1 IS"},
{ ISIS_LSP_TYPE_UNUSED2, "Unused 0x2 (invalid)"},
{ ISIS_LSP_TYPE_LEVEL_2, "L2 IS"},
{ 0, NULL }
};
/*
* Katz's point to point adjacency TLV uses codes to tell us the state of
* the remote adjacency. Enumerate them.
*/
#define ISIS_PTP_ADJ_UP 0
#define ISIS_PTP_ADJ_INIT 1
#define ISIS_PTP_ADJ_DOWN 2
static const struct tok isis_ptp_adjancey_values[] = {
{ ISIS_PTP_ADJ_UP, "Up" },
{ ISIS_PTP_ADJ_INIT, "Initializing" },
{ ISIS_PTP_ADJ_DOWN, "Down" },
{ 0, NULL}
};
struct isis_tlv_ptp_adj {
uint8_t adjacency_state;
uint8_t extd_local_circuit_id[4];
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
uint8_t neighbor_extd_local_circuit_id[4];
};
static void osi_print_cksum(netdissect_options *, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length);
static int clnp_print(netdissect_options *, const uint8_t *, u_int);
static void esis_print(netdissect_options *, const uint8_t *, u_int);
static int isis_print(netdissect_options *, const uint8_t *, u_int);
struct isis_metric_block {
uint8_t metric_default;
uint8_t metric_delay;
uint8_t metric_expense;
uint8_t metric_error;
};
struct isis_tlv_is_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_nodeid[NODE_ID_LEN];
};
struct isis_tlv_es_reach {
struct isis_metric_block isis_metric_block;
uint8_t neighbor_sysid[SYSTEM_ID_LEN];
};
struct isis_tlv_ip_reach {
struct isis_metric_block isis_metric_block;
uint8_t prefix[4];
uint8_t mask[4];
};
static const struct tok isis_is_reach_virtual_values[] = {
{ 0, "IsNotVirtual"},
{ 1, "IsVirtual"},
{ 0, NULL }
};
static const struct tok isis_restart_flag_values[] = {
{ 0x1, "Restart Request"},
{ 0x2, "Restart Acknowledgement"},
{ 0x4, "Suppress adjacency advertisement"},
{ 0, NULL }
};
struct isis_common_header {
uint8_t nlpid;
uint8_t fixed_len;
uint8_t version; /* Protocol version */
uint8_t id_length;
uint8_t pdu_type; /* 3 MSbits are reserved */
uint8_t pdu_version; /* Packet format version */
uint8_t reserved;
uint8_t max_area;
};
struct isis_iih_lan_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t priority;
uint8_t lan_id[NODE_ID_LEN];
};
struct isis_iih_ptp_header {
uint8_t circuit_type;
uint8_t source_id[SYSTEM_ID_LEN];
uint8_t holding_time[2];
uint8_t pdu_len[2];
uint8_t circuit_id;
};
struct isis_lsp_header {
uint8_t pdu_len[2];
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
uint8_t typeblock;
};
struct isis_csnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
uint8_t start_lsp_id[LSP_ID_LEN];
uint8_t end_lsp_id[LSP_ID_LEN];
};
struct isis_psnp_header {
uint8_t pdu_len[2];
uint8_t source_id[NODE_ID_LEN];
};
struct isis_tlv_lsp {
uint8_t remaining_lifetime[2];
uint8_t lsp_id[LSP_ID_LEN];
uint8_t sequence_number[4];
uint8_t checksum[2];
};
#define ISIS_COMMON_HEADER_SIZE (sizeof(struct isis_common_header))
#define ISIS_IIH_LAN_HEADER_SIZE (sizeof(struct isis_iih_lan_header))
#define ISIS_IIH_PTP_HEADER_SIZE (sizeof(struct isis_iih_ptp_header))
#define ISIS_LSP_HEADER_SIZE (sizeof(struct isis_lsp_header))
#define ISIS_CSNP_HEADER_SIZE (sizeof(struct isis_csnp_header))
#define ISIS_PSNP_HEADER_SIZE (sizeof(struct isis_psnp_header))
void
isoclns_print(netdissect_options *ndo, const uint8_t *p, u_int length)
{
if (!ND_TTEST(*p)) { /* enough bytes on the wire ? */
ND_PRINT((ndo, "|OSI"));
return;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID %s (0x%02x): ", tok2str(nlpid_values, "Unknown", *p), *p));
switch (*p) {
case NLPID_CLNP:
if (!clnp_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_ESIS:
esis_print(ndo, p, length);
return;
case NLPID_ISIS:
if (!isis_print(ndo, p, length))
print_unknown_data(ndo, p, "\n\t", length);
break;
case NLPID_NULLNS:
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
break;
case NLPID_Q933:
q933_print(ndo, p + 1, length - 1);
break;
case NLPID_IP:
ip_print(ndo, p + 1, length - 1);
break;
case NLPID_IP6:
ip6_print(ndo, p + 1, length - 1);
break;
case NLPID_PPP:
ppp_print(ndo, p + 1, length - 1);
break;
default:
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "OSI NLPID 0x%02x unknown", *p));
ND_PRINT((ndo, "%slength: %u", ndo->ndo_eflag ? "" : ", ", length));
if (length > 1)
print_unknown_data(ndo, p, "\n\t", length);
break;
}
}
#define CLNP_PDU_ER 1
#define CLNP_PDU_DT 28
#define CLNP_PDU_MD 29
#define CLNP_PDU_ERQ 30
#define CLNP_PDU_ERP 31
static const struct tok clnp_pdu_values[] = {
{ CLNP_PDU_ER, "Error Report"},
{ CLNP_PDU_MD, "MD"},
{ CLNP_PDU_DT, "Data"},
{ CLNP_PDU_ERQ, "Echo Request"},
{ CLNP_PDU_ERP, "Echo Response"},
{ 0, NULL }
};
struct clnp_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t lifetime; /* units of 500ms */
uint8_t type;
uint8_t segment_length[2];
uint8_t cksum[2];
};
struct clnp_segment_header_t {
uint8_t data_unit_id[2];
uint8_t segment_offset[2];
uint8_t total_length[2];
};
/*
* clnp_print
* Decode CLNP packets. Return 0 on error.
*/
static int
clnp_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr,*source_address,*dest_address;
u_int li,tlen,nsap_offset,source_address_length,dest_address_length, clnp_pdu_type, clnp_flags;
const struct clnp_header_t *clnp_header;
const struct clnp_segment_header_t *clnp_segment_header;
uint8_t rfd_error_major,rfd_error_minor;
clnp_header = (const struct clnp_header_t *) pptr;
ND_TCHECK(*clnp_header);
li = clnp_header->length_indicator;
optr = pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "CLNP"));
/*
* Sanity checking of the header.
*/
if (clnp_header->version != CLNP_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", clnp_header->version));
return (0);
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return (0);
}
if (li < sizeof(struct clnp_header_t)) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return (0);
}
/* FIXME further header sanity checking */
clnp_pdu_type = clnp_header->type & CLNP_PDU_TYPE_MASK;
clnp_flags = clnp_header->type & CLNP_FLAG_MASK;
pptr += sizeof(struct clnp_header_t);
li -= sizeof(struct clnp_header_t);
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
dest_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < dest_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, dest_address_length);
dest_address = pptr;
pptr += dest_address_length;
li -= dest_address_length;
if (li < 1) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK(*pptr);
source_address_length = *pptr;
pptr += 1;
li -= 1;
if (li < source_address_length) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header and addresses"));
return (0);
}
ND_TCHECK2(*pptr, source_address_length);
source_address = pptr;
pptr += source_address_length;
li -= source_address_length;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s > %s, %s, length %u",
ndo->ndo_eflag ? "" : ", ",
isonsap_string(ndo, source_address, source_address_length),
isonsap_string(ndo, dest_address, dest_address_length),
tok2str(clnp_pdu_values,"unknown (%u)",clnp_pdu_type),
length));
return (1);
}
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s PDU, hlen: %u, v: %u, lifetime: %u.%us, Segment PDU length: %u, checksum: 0x%04x",
tok2str(clnp_pdu_values, "unknown (%u)",clnp_pdu_type),
clnp_header->length_indicator,
clnp_header->version,
clnp_header->lifetime/2,
(clnp_header->lifetime%2)*5,
EXTRACT_16BITS(clnp_header->segment_length),
EXTRACT_16BITS(clnp_header->cksum)));
osi_print_cksum(ndo, optr, EXTRACT_16BITS(clnp_header->cksum), 7,
clnp_header->length_indicator);
ND_PRINT((ndo, "\n\tFlags [%s]",
bittok2str(clnp_flag_values, "none", clnp_flags)));
ND_PRINT((ndo, "\n\tsource address (length %u): %s\n\tdest address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length),
dest_address_length,
isonsap_string(ndo, dest_address, dest_address_length)));
if (clnp_flags & CLNP_SEGMENT_PART) {
if (li < sizeof(const struct clnp_segment_header_t)) {
ND_PRINT((ndo, "li < size of fixed part of CLNP header, addresses, and segment part"));
return (0);
}
clnp_segment_header = (const struct clnp_segment_header_t *) pptr;
ND_TCHECK(*clnp_segment_header);
ND_PRINT((ndo, "\n\tData Unit ID: 0x%04x, Segment Offset: %u, Total PDU Length: %u",
EXTRACT_16BITS(clnp_segment_header->data_unit_id),
EXTRACT_16BITS(clnp_segment_header->segment_offset),
EXTRACT_16BITS(clnp_segment_header->total_length)));
pptr+=sizeof(const struct clnp_segment_header_t);
li-=sizeof(const struct clnp_segment_header_t);
}
/* now walk the options */
while (li >= 2) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return (0);
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return (0);
}
ND_TCHECK2(*pptr, opli);
li -= opli;
tptr = pptr;
tlen = opli;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(clnp_option_values,"Unknown",op),
op,
opli));
/*
* We've already checked that the entire option is present
* in the captured packet with the ND_TCHECK2() call.
* Therefore, we don't need to do ND_TCHECK()/ND_TCHECK2()
* checks.
* We do, however, need to check tlen, to make sure we
* don't run past the end of the option.
*/
switch (op) {
case CLNP_OPTION_ROUTE_RECORDING: /* those two options share the format */
case CLNP_OPTION_SOURCE_ROUTING:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "%s %s",
tok2str(clnp_option_sr_rr_values,"Unknown",*tptr),
tok2str(clnp_option_sr_rr_string_values, "Unknown Option %u", op)));
nsap_offset=*(tptr+1);
if (nsap_offset == 0) {
ND_PRINT((ndo, " Bad NSAP offset (0)"));
break;
}
nsap_offset-=1; /* offset to nsap list */
if (nsap_offset > tlen) {
ND_PRINT((ndo, " Bad NSAP offset (past end of option)"));
break;
}
tptr+=nsap_offset;
tlen-=nsap_offset;
while (tlen > 0) {
source_address_length=*tptr;
if (tlen < source_address_length+1) {
ND_PRINT((ndo, "\n\t NSAP address goes past end of option"));
break;
}
if (source_address_length > 0) {
source_address=(tptr+1);
ND_TCHECK2(*source_address, source_address_length);
ND_PRINT((ndo, "\n\t NSAP address (length %u): %s",
source_address_length,
isonsap_string(ndo, source_address, source_address_length)));
}
tlen-=source_address_length+1;
}
break;
case CLNP_OPTION_PRIORITY:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "0x%1x", *tptr&0x0f));
break;
case CLNP_OPTION_QOS_MAINTENANCE:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s",
tok2str(clnp_option_scope_values, "Reserved", *tptr&CLNP_OPTION_SCOPE_MASK)));
if ((*tptr&CLNP_OPTION_SCOPE_MASK) == CLNP_OPTION_SCOPE_GLOBAL)
ND_PRINT((ndo, "\n\t QoS Flags [%s]",
bittok2str(clnp_option_qos_global_values,
"none",
*tptr&CLNP_OPTION_OPTION_QOS_MASK)));
break;
case CLNP_OPTION_SECURITY:
if (tlen < 2) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
ND_PRINT((ndo, "\n\t Format Code: %s, Security-Level %u",
tok2str(clnp_option_scope_values,"Reserved",*tptr&CLNP_OPTION_SCOPE_MASK),
*(tptr+1)));
break;
case CLNP_OPTION_DISCARD_REASON:
if (tlen < 1) {
ND_PRINT((ndo, ", bad opt len"));
return (0);
}
rfd_error_major = (*tptr&0xf0) >> 4;
rfd_error_minor = *tptr&0x0f;
ND_PRINT((ndo, "\n\t Class: %s Error (0x%01x), %s (0x%01x)",
tok2str(clnp_option_rfd_class_values,"Unknown",rfd_error_major),
rfd_error_major,
tok2str(clnp_option_rfd_error_class[rfd_error_major],"Unknown",rfd_error_minor),
rfd_error_minor));
break;
case CLNP_OPTION_PADDING:
ND_PRINT((ndo, "padding data"));
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
switch (clnp_pdu_type) {
case CLNP_PDU_ER: /* fall through */
case CLNP_PDU_ERP:
ND_TCHECK(*pptr);
if (*(pptr) == NLPID_CLNP) {
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
/* FIXME recursion protection */
clnp_print(ndo, pptr, length - clnp_header->length_indicator);
break;
}
case CLNP_PDU_DT:
case CLNP_PDU_MD:
case CLNP_PDU_ERQ:
default:
/* dump the PDU specific data */
if (length-(pptr-optr) > 0) {
ND_PRINT((ndo, "\n\t undecoded non-header data, length %u", length-clnp_header->length_indicator));
print_unknown_data(ndo, pptr, "\n\t ", length - (pptr - optr));
}
}
return (1);
trunc:
ND_PRINT((ndo, "[|clnp]"));
return (1);
}
#define ESIS_PDU_REDIRECT 6
#define ESIS_PDU_ESH 2
#define ESIS_PDU_ISH 4
static const struct tok esis_pdu_values[] = {
{ ESIS_PDU_REDIRECT, "redirect"},
{ ESIS_PDU_ESH, "ESH"},
{ ESIS_PDU_ISH, "ISH"},
{ 0, NULL }
};
struct esis_header_t {
uint8_t nlpid;
uint8_t length_indicator;
uint8_t version;
uint8_t reserved;
uint8_t type;
uint8_t holdtime[2];
uint8_t cksum[2];
};
static void
esis_print(netdissect_options *ndo,
const uint8_t *pptr, u_int length)
{
const uint8_t *optr;
u_int li,esis_pdu_type,source_address_length, source_address_number;
const struct esis_header_t *esis_header;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "ES-IS"));
if (length <= 2) {
ND_PRINT((ndo, ndo->ndo_qflag ? "bad pkt!" : "no header at all!"));
return;
}
esis_header = (const struct esis_header_t *) pptr;
ND_TCHECK(*esis_header);
li = esis_header->length_indicator;
optr = pptr;
/*
* Sanity checking of the header.
*/
if (esis_header->nlpid != NLPID_ESIS) {
ND_PRINT((ndo, " nlpid 0x%02x packet not supported", esis_header->nlpid));
return;
}
if (esis_header->version != ESIS_VERSION) {
ND_PRINT((ndo, " version %d packet not supported", esis_header->version));
return;
}
if (li > length) {
ND_PRINT((ndo, " length indicator(%u) > PDU size (%u)!", li, length));
return;
}
if (li < sizeof(struct esis_header_t) + 2) {
ND_PRINT((ndo, " length indicator %u < min PDU size:", li));
while (pptr < ndo->ndo_snapend)
ND_PRINT((ndo, "%02X", *pptr++));
return;
}
esis_pdu_type = esis_header->type & ESIS_PDU_TYPE_MASK;
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "%s%s, length %u",
ndo->ndo_eflag ? "" : ", ",
tok2str(esis_pdu_values,"unknown type (%u)",esis_pdu_type),
length));
return;
} else
ND_PRINT((ndo, "%slength %u\n\t%s (%u)",
ndo->ndo_eflag ? "" : ", ",
length,
tok2str(esis_pdu_values,"unknown type: %u", esis_pdu_type),
esis_pdu_type));
ND_PRINT((ndo, ", v: %u%s", esis_header->version, esis_header->version == ESIS_VERSION ? "" : "unsupported" ));
ND_PRINT((ndo, ", checksum: 0x%04x", EXTRACT_16BITS(esis_header->cksum)));
osi_print_cksum(ndo, pptr, EXTRACT_16BITS(esis_header->cksum), 7, li);
ND_PRINT((ndo, ", holding time: %us, length indicator: %u",
EXTRACT_16BITS(esis_header->holdtime), li));
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, optr, "\n\t", sizeof(struct esis_header_t));
pptr += sizeof(struct esis_header_t);
li -= sizeof(struct esis_header_t);
switch (esis_pdu_type) {
case ESIS_PDU_REDIRECT: {
const uint8_t *dst, *snpa, *neta;
u_int dstl, snpal, netal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dstl = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, dstl);
if (li < dstl) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
dst = pptr;
pptr += dstl;
li -= dstl;
ND_PRINT((ndo, "\n\t %s", isonsap_string(ndo, dst, dstl)));
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpal = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, snpal);
if (li < snpal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
snpa = pptr;
pptr += snpal;
li -= snpal;
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
netal = *pptr;
pptr++;
ND_TCHECK2(*pptr, netal);
if (li < netal) {
ND_PRINT((ndo, ", bad redirect/li"));
return;
}
neta = pptr;
pptr += netal;
li -= netal;
if (snpal == 6)
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
etheraddr_string(ndo, snpa)));
else
ND_PRINT((ndo, "\n\t SNPA (length: %u): %s",
snpal,
linkaddr_string(ndo, snpa, LINKADDR_OTHER, snpal)));
if (netal != 0)
ND_PRINT((ndo, "\n\t NET (length: %u) %s",
netal,
isonsap_string(ndo, neta, netal)));
break;
}
case ESIS_PDU_ESH:
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_number = *pptr;
pptr++;
li--;
ND_PRINT((ndo, "\n\t Number of Source Addresses: %u", source_address_number));
while (source_address_number > 0) {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad esh/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s",
source_address_length,
isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
source_address_number--;
}
break;
case ESIS_PDU_ISH: {
ND_TCHECK(*pptr);
if (li < 1) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
source_address_length = *pptr;
pptr++;
li--;
ND_TCHECK2(*pptr, source_address_length);
if (li < source_address_length) {
ND_PRINT((ndo, ", bad ish/li"));
return;
}
ND_PRINT((ndo, "\n\t NET (length: %u): %s", source_address_length, isonsap_string(ndo, pptr, source_address_length)));
pptr += source_address_length;
li -= source_address_length;
break;
}
default:
if (ndo->ndo_vflag <= 1) {
if (pptr < ndo->ndo_snapend)
print_unknown_data(ndo, pptr, "\n\t ", ndo->ndo_snapend - pptr);
}
return;
}
/* now walk the options */
while (li != 0) {
u_int op, opli;
const uint8_t *tptr;
if (li < 2) {
ND_PRINT((ndo, ", bad opts/li"));
return;
}
ND_TCHECK2(*pptr, 2);
op = *pptr++;
opli = *pptr++;
li -= 2;
if (opli > li) {
ND_PRINT((ndo, ", opt (%d) too long", op));
return;
}
li -= opli;
tptr = pptr;
ND_PRINT((ndo, "\n\t %s Option #%u, length %u, value: ",
tok2str(esis_option_values,"Unknown",op),
op,
opli));
switch (op) {
case ESIS_OPTION_ES_CONF_TIME:
if (opli == 2) {
ND_TCHECK2(*pptr, 2);
ND_PRINT((ndo, "%us", EXTRACT_16BITS(tptr)));
} else
ND_PRINT((ndo, "(bad length)"));
break;
case ESIS_OPTION_PROTOCOLS:
while (opli>0) {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (opli>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
opli--;
}
break;
/*
* FIXME those are the defined Options that lack a decoder
* you are welcome to contribute code ;-)
*/
case ESIS_OPTION_QOS_MAINTENANCE:
case ESIS_OPTION_SECURITY:
case ESIS_OPTION_PRIORITY:
case ESIS_OPTION_ADDRESS_MASK:
case ESIS_OPTION_SNPA_MASK:
default:
print_unknown_data(ndo, tptr, "\n\t ", opli);
break;
}
if (ndo->ndo_vflag > 1)
print_unknown_data(ndo, pptr, "\n\t ", opli);
pptr += opli;
}
trunc:
ND_PRINT((ndo, "[|esis]"));
}
static void
isis_print_mcid(netdissect_options *ndo,
const struct isis_spb_mcid *mcid)
{
int i;
ND_TCHECK(*mcid);
ND_PRINT((ndo, "ID: %d, Name: ", mcid->format_id));
if (fn_printzp(ndo, mcid->name, 32, ndo->ndo_snapend))
goto trunc;
ND_PRINT((ndo, "\n\t Lvl: %d", EXTRACT_16BITS(mcid->revision_lvl)));
ND_PRINT((ndo, ", Digest: "));
for(i=0;i<16;i++)
ND_PRINT((ndo, "%.2x ", mcid->digest[i]));
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
isis_print_mt_port_cap_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len;
const struct isis_subtlv_spb_mcid *subtlv_spb_mcid;
int i;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_port_cap_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
/*len -= TLV_TYPE_LEN_OFFSET;*/
len = len -2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_MCID:
{
if (stlv_len < ISIS_SUBTLV_SPB_MCID_MIN_LEN)
goto trunc;
subtlv_spb_mcid = (const struct isis_subtlv_spb_mcid *)tptr;
ND_PRINT((ndo, "\n\t MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
ND_PRINT((ndo, "\n\t AUX-MCID: "));
isis_print_mcid(ndo, &(subtlv_spb_mcid->aux_mcid));
/*tptr += SPB_MCID_MIN_LEN;
len -= SPB_MCID_MIN_LEN; */
tptr = tptr + ISIS_SUBTLV_SPB_MCID_MIN_LEN;
len = len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_MCID_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_DIGEST:
{
if (stlv_len < ISIS_SUBTLV_SPB_DIGEST_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t RES: %d V: %d A: %d D: %d",
(*(tptr) >> 5), (((*tptr)>> 4) & 0x01),
((*(tptr) >> 2) & 0x03), ((*tptr) & 0x03)));
tptr++;
ND_PRINT((ndo, "\n\t Digest: "));
for(i=1;i<=8; i++)
{
ND_PRINT((ndo, "%08x ", EXTRACT_32BITS(tptr)));
if (i%4 == 0 && i != 8)
ND_PRINT((ndo, "\n\t "));
tptr = tptr + 4;
}
len = len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_DIGEST_MIN_LEN;
break;
}
case ISIS_SUBTLV_SPB_BVID:
{
while (stlv_len >= ISIS_SUBTLV_SPB_BVID_MIN_LEN)
{
ND_PRINT((ndo, "\n\t ECT: %08x",
EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " BVID: %d, U:%01x M:%01x ",
(EXTRACT_16BITS (tptr) >> 4) ,
(EXTRACT_16BITS (tptr) >> 3) & 0x01,
(EXTRACT_16BITS (tptr) >> 2) & 0x01));
tptr = tptr + 2;
len = len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_BVID_MIN_LEN;
}
break;
}
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static int
isis_print_mt_capability_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int len)
{
int stlv_type, stlv_len, tmp;
while (len > 2)
{
ND_TCHECK2(*tptr, 2);
stlv_type = *(tptr++);
stlv_len = *(tptr++);
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "\n\t %s subTLV #%u, length: %u",
tok2str(isis_mt_capability_subtlv_values, "unknown", stlv_type),
stlv_type,
stlv_len));
len = len - 2;
/* Make sure the subTLV fits within the space left */
if (len < stlv_len)
goto trunc;
/* Make sure the entire subTLV is in the captured data */
ND_TCHECK2(*(tptr), stlv_len);
switch (stlv_type)
{
case ISIS_SUBTLV_SPB_INSTANCE:
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t CIST Root-ID: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, " %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Path Cost: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, ", Prio: %d", EXTRACT_16BITS(tptr)));
tptr = tptr + 2;
ND_PRINT((ndo, "\n\t RES: %d",
EXTRACT_16BITS(tptr) >> 5));
ND_PRINT((ndo, ", V: %d",
(EXTRACT_16BITS(tptr) >> 4) & 0x0001));
ND_PRINT((ndo, ", SPSource-ID: %d",
(EXTRACT_32BITS(tptr) & 0x000fffff)));
tptr = tptr+4;
ND_PRINT((ndo, ", No of Trees: %x", *(tptr)));
tmp = *(tptr++);
len = len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_MIN_LEN;
while (tmp)
{
if (stlv_len < ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN)
goto trunc;
ND_PRINT((ndo, "\n\t U:%d, M:%d, A:%d, RES:%d",
*(tptr) >> 7, (*(tptr) >> 6) & 0x01,
(*(tptr) >> 5) & 0x01, (*(tptr) & 0x1f)));
tptr++;
ND_PRINT((ndo, ", ECT: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr + 4;
ND_PRINT((ndo, ", BVID: %d, SPVID: %d",
(EXTRACT_24BITS(tptr) >> 12) & 0x000fff,
EXTRACT_24BITS(tptr) & 0x000fff));
tptr = tptr + 3;
len = len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
stlv_len = stlv_len - ISIS_SUBTLV_SPB_INSTANCE_VLAN_TUPLE_LEN;
tmp--;
}
break;
case ISIS_SUBTLV_SPBM_SI:
if (stlv_len < 8)
goto trunc;
ND_PRINT((ndo, "\n\t BMAC: %08x", EXTRACT_32BITS(tptr)));
tptr = tptr+4;
ND_PRINT((ndo, "%04x", EXTRACT_16BITS(tptr)));
tptr = tptr+2;
ND_PRINT((ndo, ", RES: %d, VID: %d", EXTRACT_16BITS(tptr) >> 12,
(EXTRACT_16BITS(tptr)) & 0x0fff));
tptr = tptr+2;
len = len - 8;
stlv_len = stlv_len - 8;
while (stlv_len >= 4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t T: %d, R: %d, RES: %d, ISID: %d",
(EXTRACT_32BITS(tptr) >> 31),
(EXTRACT_32BITS(tptr) >> 30) & 0x01,
(EXTRACT_32BITS(tptr) >> 24) & 0x03f,
(EXTRACT_32BITS(tptr)) & 0x0ffffff));
tptr = tptr + 4;
len = len - 4;
stlv_len = stlv_len - 4;
}
break;
default:
break;
}
tptr += stlv_len;
len -= stlv_len;
}
return 0;
trunc:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
/* shared routine for printing system, node and lsp-ids */
static char *
isis_print_id(const uint8_t *cp, int id_len)
{
int i;
static char id[sizeof("xxxx.xxxx.xxxx.yy-zz")];
char *pos = id;
int sysid_len;
sysid_len = SYSTEM_ID_LEN;
if (sysid_len > id_len)
sysid_len = id_len;
for (i = 1; i <= sysid_len; i++) {
snprintf(pos, sizeof(id) - (pos - id), "%02x", *cp++);
pos += strlen(pos);
if (i == 2 || i == 4)
*pos++ = '.';
}
if (id_len >= NODE_ID_LEN) {
snprintf(pos, sizeof(id) - (pos - id), ".%02x", *cp++);
pos += strlen(pos);
}
if (id_len == LSP_ID_LEN)
snprintf(pos, sizeof(id) - (pos - id), "-%02x", *cp);
return (id);
}
/* print the 4-byte metric block which is common found in the old-style TLVs */
static int
isis_print_metric_block(netdissect_options *ndo,
const struct isis_metric_block *isis_metric_block)
{
ND_PRINT((ndo, ", Default Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_default),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_delay))
ND_PRINT((ndo, "\n\t\t Delay Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_delay),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_expense))
ND_PRINT((ndo, "\n\t\t Expense Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_expense),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(isis_metric_block->metric_error))
ND_PRINT((ndo, "\n\t\t Error Metric: %d, %s",
ISIS_LSP_TLV_METRIC_VALUE(isis_metric_block->metric_error),
ISIS_LSP_TLV_METRIC_IE(isis_metric_block->metric_error) ? "External" : "Internal"));
return(1); /* everything is ok */
}
static int
isis_print_tlv_ip_reach(netdissect_options *ndo,
const uint8_t *cp, const char *ident, int length)
{
int prefix_len;
const struct isis_tlv_ip_reach *tlv_ip_reach;
tlv_ip_reach = (const struct isis_tlv_ip_reach *)cp;
while (length > 0) {
if ((size_t)length < sizeof(*tlv_ip_reach)) {
ND_PRINT((ndo, "short IPv4 Reachability (%d vs %lu)",
length,
(unsigned long)sizeof(*tlv_ip_reach)));
return (0);
}
if (!ND_TTEST(*tlv_ip_reach))
return (0);
prefix_len = mask2plen(EXTRACT_32BITS(tlv_ip_reach->mask));
if (prefix_len == -1)
ND_PRINT((ndo, "%sIPv4 prefix: %s mask %s",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
ipaddr_string(ndo, (tlv_ip_reach->mask))));
else
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, (tlv_ip_reach->prefix)),
prefix_len));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u, %s",
ISIS_LSP_TLV_METRIC_UPDOWN(tlv_ip_reach->isis_metric_block.metric_default) ? "down" : "up",
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_default),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_default) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_delay))
ND_PRINT((ndo, "%s Delay Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_delay),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_delay) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_expense))
ND_PRINT((ndo, "%s Expense Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_expense),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_expense) ? "External" : "Internal"));
if (!ISIS_LSP_TLV_METRIC_SUPPORTED(tlv_ip_reach->isis_metric_block.metric_error))
ND_PRINT((ndo, "%s Error Metric: %u, %s",
ident,
ISIS_LSP_TLV_METRIC_VALUE(tlv_ip_reach->isis_metric_block.metric_error),
ISIS_LSP_TLV_METRIC_IE(tlv_ip_reach->isis_metric_block.metric_error) ? "External" : "Internal"));
length -= sizeof(struct isis_tlv_ip_reach);
tlv_ip_reach++;
}
return (1);
}
/*
* this is the common IP-REACH subTLV decoder it is called
* from various EXTD-IP REACH TLVs (135,235,236,237)
*/
static int
isis_print_ip_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, int subt, int subl,
const char *ident)
{
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_ip_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr,subl);
switch(subt) {
case ISIS_SUBTLV_EXTD_IP_REACH_MGMT_PREFIX_COLOR: /* fall through */
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG32:
while (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x (=%u)",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr)));
tptr+=4;
subl-=4;
}
break;
case ISIS_SUBTLV_EXTD_IP_REACH_ADMIN_TAG64:
while (subl >= 8) {
ND_PRINT((ndo, ", 0x%08x%08x",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr+4)));
tptr+=8;
subl-=8;
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
ND_PRINT((ndo, "%s", ident));
ND_PRINT((ndo, "%s", tstr));
return(0);
}
/*
* this is the common IS-REACH subTLV decoder it is called
* from isis_print_ext_is_reach()
*/
static int
isis_print_is_reach_subtlv(netdissect_options *ndo,
const uint8_t *tptr, u_int subt, u_int subl,
const char *ident)
{
u_int te_class,priority_level,gmpls_switch_cap;
union { /* int to float conversion buffer for several subTLVs */
float f;
uint32_t i;
} bw;
/* first lets see if we know the subTLVs name*/
ND_PRINT((ndo, "%s%s subTLV #%u, length: %u",
ident, tok2str(isis_ext_is_reach_subtlv_values, "unknown", subt),
subt, subl));
ND_TCHECK2(*tptr, subl);
switch(subt) {
case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID:
case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID:
if (subl >= 4) {
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr)));
if (subl == 8) /* rfc4205 */
ND_PRINT((ndo, ", 0x%08x", EXTRACT_32BITS(tptr+4)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR:
case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR:
if (subl >= sizeof(struct in_addr))
ND_PRINT((ndo, ", %s", ipaddr_string(ndo, tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW :
case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW:
if (subl >= 4) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, ", %.3f Mbps", bw.f * 8 / 1000000));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW :
if (subl >= 32) {
for (te_class = 0; te_class < 8; te_class++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s TE-Class %u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */
case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD:
ND_PRINT((ndo, "%sBandwidth Constraints Model ID: %s (%u)",
ident,
tok2str(diffserv_te_bc_values, "unknown", *tptr),
*tptr));
tptr++;
/* decode BCs until the subTLV ends */
for (te_class = 0; te_class < (subl-1)/4; te_class++) {
ND_TCHECK2(*tptr, 4);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Bandwidth constraint CT%u: %.3f Mbps",
ident,
te_class,
bw.f * 8 / 1000000));
tptr+=4;
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC:
if (subl >= 3)
ND_PRINT((ndo, ", %u", EXTRACT_24BITS(tptr)));
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE:
if (subl == 2) {
ND_PRINT((ndo, ", [ %s ] (0x%04x)",
bittok2str(isis_subtlv_link_attribute_values,
"Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE:
if (subl >= 2) {
ND_PRINT((ndo, ", %s, Priority %u",
bittok2str(gmpls_link_prot_values, "none", *tptr),
*(tptr+1)));
}
break;
case ISIS_SUBTLV_SPB_METRIC:
if (subl >= 6) {
ND_PRINT((ndo, ", LM: %u", EXTRACT_24BITS(tptr)));
tptr=tptr+3;
ND_PRINT((ndo, ", P: %u", *(tptr)));
tptr++;
ND_PRINT((ndo, ", P-ID: %u", EXTRACT_16BITS(tptr)));
}
break;
case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR:
if (subl >= 36) {
gmpls_switch_cap = *tptr;
ND_PRINT((ndo, "%s Interface Switching Capability:%s",
ident,
tok2str(gmpls_switch_cap_values, "Unknown", gmpls_switch_cap)));
ND_PRINT((ndo, ", LSP Encoding: %s",
tok2str(gmpls_encoding_values, "Unknown", *(tptr + 1))));
tptr+=4;
ND_PRINT((ndo, "%s Max LSP Bandwidth:", ident));
for (priority_level = 0; priority_level < 8; priority_level++) {
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s priority level %d: %.3f Mbps",
ident,
priority_level,
bw.f * 8 / 1000000));
tptr+=4;
}
subl-=36;
switch (gmpls_switch_cap) {
case GMPLS_PSC1:
case GMPLS_PSC2:
case GMPLS_PSC3:
case GMPLS_PSC4:
ND_TCHECK2(*tptr, 6);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Interface MTU: %u", ident, EXTRACT_16BITS(tptr + 4)));
break;
case GMPLS_TSC:
ND_TCHECK2(*tptr, 8);
bw.i = EXTRACT_32BITS(tptr);
ND_PRINT((ndo, "%s Min LSP Bandwidth: %.3f Mbps", ident, bw.f * 8 / 1000000));
ND_PRINT((ndo, "%s Indication %s", ident,
tok2str(gmpls_switch_cap_tsc_indication_values, "Unknown (%u)", *(tptr + 4))));
break;
default:
/* there is some optional stuff left to decode but this is as of yet
not specified so just lets hexdump what is left */
if(subl>0){
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
}
}
}
break;
default:
if (!print_unknown_data(ndo, tptr, "\n\t\t ", subl))
return(0);
break;
}
return(1);
trunc:
return(0);
}
/*
* this is the common IS-REACH decoder it is called
* from various EXTD-IS REACH style TLVs (22,24,222)
*/
static int
isis_print_ext_is_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, int tlv_type)
{
char ident_buffer[20];
int subtlv_type,subtlv_len,subtlv_sum_len;
int proc_bytes = 0; /* how many bytes did we process ? */
if (!ND_TTEST2(*tptr, NODE_ID_LEN))
return(0);
ND_PRINT((ndo, "%sIS Neighbor: %s", ident, isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
if (tlv_type != ISIS_TLV_IS_ALIAS_ID) { /* the Alias TLV Metric field is implicit 0 */
if (!ND_TTEST2(*tptr, 3)) /* and is therefore skipped */
return(0);
ND_PRINT((ndo, ", Metric: %d", EXTRACT_24BITS(tptr)));
tptr+=3;
}
if (!ND_TTEST2(*tptr, 1))
return(0);
subtlv_sum_len=*(tptr++); /* read out subTLV length */
proc_bytes=NODE_ID_LEN+3+1;
ND_PRINT((ndo, ", %ssub-TLVs present",subtlv_sum_len ? "" : "no "));
if (subtlv_sum_len) {
ND_PRINT((ndo, " (%u)", subtlv_sum_len));
while (subtlv_sum_len>0) {
if (!ND_TTEST2(*tptr,2))
return(0);
subtlv_type=*(tptr++);
subtlv_len=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_is_reach_subtlv(ndo, tptr, subtlv_type, subtlv_len, ident_buffer))
return(0);
tptr+=subtlv_len;
subtlv_sum_len-=(subtlv_len+2);
proc_bytes+=(subtlv_len+2);
}
}
return(proc_bytes);
}
/*
* this is the common Multi Topology ID decoder
* it is called from various MT-TLVs (222,229,235,237)
*/
static int
isis_print_mtid(netdissect_options *ndo,
const uint8_t *tptr, const char *ident)
{
if (!ND_TTEST2(*tptr, 2))
return(0);
ND_PRINT((ndo, "%s%s",
ident,
tok2str(isis_mt_values,
"Reserved for IETF Consensus",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)))));
ND_PRINT((ndo, " Topology (0x%03x), Flags: [%s]",
ISIS_MASK_MTID(EXTRACT_16BITS(tptr)),
bittok2str(isis_mt_flag_values, "none",ISIS_MASK_MTFLAGS(EXTRACT_16BITS(tptr)))));
return(2);
}
/*
* this is the common extended IP reach decoder
* it is called from TLVs (135,235,236,237)
* we process the TLV and optional subTLVs and return
* the amount of processed bytes
*/
static int
isis_print_extd_ip_reach(netdissect_options *ndo,
const uint8_t *tptr, const char *ident, uint16_t afi)
{
char ident_buffer[20];
uint8_t prefix[sizeof(struct in6_addr)]; /* shared copy buffer for IPv4 and IPv6 prefixes */
u_int metric, status_byte, bit_length, byte_length, sublen, processed, subtlvtype, subtlvlen;
if (!ND_TTEST2(*tptr, 4))
return (0);
metric = EXTRACT_32BITS(tptr);
processed=4;
tptr+=4;
if (afi == AF_INET) {
if (!ND_TTEST2(*tptr, 1)) /* fetch status byte */
return (0);
status_byte=*(tptr++);
bit_length = status_byte&0x3f;
if (bit_length > 32) {
ND_PRINT((ndo, "%sIPv4 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed++;
} else if (afi == AF_INET6) {
if (!ND_TTEST2(*tptr, 2)) /* fetch status & prefix_len byte */
return (0);
status_byte=*(tptr++);
bit_length=*(tptr++);
if (bit_length > 128) {
ND_PRINT((ndo, "%sIPv6 prefix: bad bit length %u",
ident,
bit_length));
return (0);
}
processed+=2;
} else
return (0); /* somebody is fooling us */
byte_length = (bit_length + 7) / 8; /* prefix has variable length encoding */
if (!ND_TTEST2(*tptr, byte_length))
return (0);
memset(prefix, 0, sizeof prefix); /* clear the copy buffer */
memcpy(prefix,tptr,byte_length); /* copy as much as is stored in the TLV */
tptr+=byte_length;
processed+=byte_length;
if (afi == AF_INET)
ND_PRINT((ndo, "%sIPv4 prefix: %15s/%u",
ident,
ipaddr_string(ndo, prefix),
bit_length));
else if (afi == AF_INET6)
ND_PRINT((ndo, "%sIPv6 prefix: %s/%u",
ident,
ip6addr_string(ndo, prefix),
bit_length));
ND_PRINT((ndo, ", Distribution: %s, Metric: %u",
ISIS_MASK_TLV_EXTD_IP_UPDOWN(status_byte) ? "down" : "up",
metric));
if (afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
ND_PRINT((ndo, ", sub-TLVs present"));
else if (afi == AF_INET6)
ND_PRINT((ndo, ", %s%s",
ISIS_MASK_TLV_EXTD_IP6_IE(status_byte) ? "External" : "Internal",
ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte) ? ", sub-TLVs present" : ""));
if ((afi == AF_INET && ISIS_MASK_TLV_EXTD_IP_SUBTLV(status_byte))
|| (afi == AF_INET6 && ISIS_MASK_TLV_EXTD_IP6_SUBTLV(status_byte))
) {
/* assume that one prefix can hold more
than one subTLV - therefore the first byte must reflect
the aggregate bytecount of the subTLVs for this prefix
*/
if (!ND_TTEST2(*tptr, 1))
return (0);
sublen=*(tptr++);
processed+=sublen+1;
ND_PRINT((ndo, " (%u)", sublen)); /* print out subTLV length */
while (sublen>0) {
if (!ND_TTEST2(*tptr,2))
return (0);
subtlvtype=*(tptr++);
subtlvlen=*(tptr++);
/* prepend the indent string */
snprintf(ident_buffer, sizeof(ident_buffer), "%s ",ident);
if (!isis_print_ip_reach_subtlv(ndo, tptr, subtlvtype, subtlvlen, ident_buffer))
return(0);
tptr+=subtlvlen;
sublen-=(subtlvlen+2);
}
}
return (processed);
}
/*
* Clear checksum and lifetime prior to signature verification.
*/
static void
isis_clear_checksum_lifetime(void *header)
{
struct isis_lsp_header *header_lsp = (struct isis_lsp_header *) header;
header_lsp->checksum[0] = 0;
header_lsp->checksum[1] = 0;
header_lsp->remaining_lifetime[0] = 0;
header_lsp->remaining_lifetime[1] = 0;
}
/*
* isis_print
* Decode IS-IS packets. Return 0 on error.
*/
static int
isis_print(netdissect_options *ndo,
const uint8_t *p, u_int length)
{
const struct isis_common_header *isis_header;
const struct isis_iih_lan_header *header_iih_lan;
const struct isis_iih_ptp_header *header_iih_ptp;
const struct isis_lsp_header *header_lsp;
const struct isis_csnp_header *header_csnp;
const struct isis_psnp_header *header_psnp;
const struct isis_tlv_lsp *tlv_lsp;
const struct isis_tlv_ptp_adj *tlv_ptp_adj;
const struct isis_tlv_is_reach *tlv_is_reach;
const struct isis_tlv_es_reach *tlv_es_reach;
uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len;
uint8_t ext_is_len, ext_ip_len, mt_len;
const uint8_t *optr, *pptr, *tptr;
u_short packet_len,pdu_len, key_id;
u_int i,vendor_id;
int sigcheck;
packet_len=length;
optr = p; /* initialize the _o_riginal pointer to the packet start -
need it for parsing the checksum TLV and authentication
TLV verification */
isis_header = (const struct isis_common_header *)p;
ND_TCHECK(*isis_header);
if (length < ISIS_COMMON_HEADER_SIZE)
goto trunc;
pptr = p+(ISIS_COMMON_HEADER_SIZE);
header_iih_lan = (const struct isis_iih_lan_header *)pptr;
header_iih_ptp = (const struct isis_iih_ptp_header *)pptr;
header_lsp = (const struct isis_lsp_header *)pptr;
header_csnp = (const struct isis_csnp_header *)pptr;
header_psnp = (const struct isis_psnp_header *)pptr;
if (!ndo->ndo_eflag)
ND_PRINT((ndo, "IS-IS"));
/*
* Sanity checking of the header.
*/
if (isis_header->version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->version));
return (0);
}
if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) {
ND_PRINT((ndo, "system ID length of %d is not supported",
isis_header->id_length));
return (0);
}
if (isis_header->pdu_version != ISIS_VERSION) {
ND_PRINT((ndo, "version %d packet not supported", isis_header->pdu_version));
return (0);
}
if (length < isis_header->fixed_len) {
ND_PRINT((ndo, "fixed header length %u > packet length %u", isis_header->fixed_len, length));
return (0);
}
if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) {
ND_PRINT((ndo, "fixed header length %u < minimum header size %u", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE));
return (0);
}
max_area = isis_header->max_area;
switch(max_area) {
case 0:
max_area = 3; /* silly shit */
break;
case 255:
ND_PRINT((ndo, "bad packet -- 255 areas"));
return (0);
default:
break;
}
id_length = isis_header->id_length;
switch(id_length) {
case 0:
id_length = 6; /* silly shit again */
break;
case 1: /* 1-8 are valid sys-ID lenghts */
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
break;
case 255:
id_length = 0; /* entirely useless */
break;
default:
break;
}
/* toss any non 6-byte sys-ID len PDUs */
if (id_length != 6 ) {
ND_PRINT((ndo, "bad packet -- illegal sys-ID length (%u)", id_length));
return (0);
}
pdu_type=isis_header->pdu_type;
/* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, "%s%s",
ndo->ndo_eflag ? "" : ", ",
tok2str(isis_pdu_values, "unknown PDU-Type %u", pdu_type)));
} else {
/* ok they seem to want to know everything - lets fully decode it */
ND_PRINT((ndo, "%slength %u", ndo->ndo_eflag ? "" : ", ", length));
ND_PRINT((ndo, "\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)",
tok2str(isis_pdu_values,
"unknown, type %u",
pdu_type),
isis_header->fixed_len,
isis_header->version,
isis_header->pdu_version,
id_length,
isis_header->id_length,
max_area,
isis_header->max_area));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, optr, "\n\t", 8)) /* provide the _o_riginal pointer */
return (0); /* for optionally debugging the common header */
}
}
switch (pdu_type) {
case ISIS_PDU_L1_LAN_IIH:
case ISIS_PDU_L2_LAN_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_lan);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s",
isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", lan-id %s, prio %u",
isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN),
header_iih_lan->priority));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_lan->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_lan->circuit_type)));
ND_PRINT((ndo, "\n\t lan-id: %s, Priority: %u, PDU length: %u",
isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN),
(header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_LAN_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE);
break;
case ISIS_PDU_PTP_IIH:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_iih_ptp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, holding time: %us, Flags: [%s]",
isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN),
EXTRACT_16BITS(header_iih_ptp->holding_time),
tok2str(isis_iih_circuit_type_values,
"unknown circuit type 0x%02x",
header_iih_ptp->circuit_type)));
ND_PRINT((ndo, "\n\t circuit-id: 0x%02x, PDU length: %u",
header_iih_ptp->circuit_id,
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_IIH_PTP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE);
break;
case ISIS_PDU_L1_LSP:
case ISIS_PDU_L2_LSP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE));
return (0);
}
ND_TCHECK(*header_lsp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", lsp-id %s, seq 0x%08x, lifetime %5us",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_lsp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x",
isis_print_id(header_lsp->lsp_id, LSP_ID_LEN),
EXTRACT_32BITS(header_lsp->sequence_number),
EXTRACT_16BITS(header_lsp->remaining_lifetime),
EXTRACT_16BITS(header_lsp->checksum)));
osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id,
EXTRACT_16BITS(header_lsp->checksum),
12, length-12);
ND_PRINT((ndo, ", PDU length: %u, Flags: [ %s",
pdu_len,
ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? "Overload bit set, " : ""));
if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) {
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? "default " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? "delay " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? "expense " : ""));
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? "error " : ""));
ND_PRINT((ndo, "ATT bit set, "));
}
ND_PRINT((ndo, "%s", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? "P bit set, " : ""));
ND_PRINT((ndo, "%s ]", tok2str(isis_lsp_istype_values, "Unknown(0x%x)",
ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock))));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_LSP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE);
break;
case ISIS_PDU_L1_CSNP:
case ISIS_PDU_L2_CSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) {
ND_PRINT((ndo, ", bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_csnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_csnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_csnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_csnp->source_id, NODE_ID_LEN),
pdu_len));
ND_PRINT((ndo, "\n\t start lsp-id: %s",
isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN)));
ND_PRINT((ndo, "\n\t end lsp-id: %s",
isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN)));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_CSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE);
break;
case ISIS_PDU_L1_PSNP:
case ISIS_PDU_L2_PSNP:
if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) {
ND_PRINT((ndo, "- bogus fixed header length %u should be %lu",
isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)));
return (0);
}
ND_TCHECK(*header_psnp);
if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)
goto trunc;
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", src-id %s", isis_print_id(header_psnp->source_id, NODE_ID_LEN)));
ND_PRINT((ndo, ", length %u", length));
return (1);
}
pdu_len=EXTRACT_16BITS(header_psnp->pdu_len);
if (packet_len>pdu_len) {
packet_len=pdu_len; /* do TLV decoding as long as it makes sense */
length=pdu_len;
}
ND_PRINT((ndo, "\n\t source-id: %s, PDU length: %u",
isis_print_id(header_psnp->source_id, NODE_ID_LEN),
pdu_len));
if (ndo->ndo_vflag > 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", ISIS_PSNP_HEADER_SIZE))
return (0);
}
packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE);
break;
default:
if (ndo->ndo_vflag == 0) {
ND_PRINT((ndo, ", length %u", length));
return (1);
}
(void)print_unknown_data(ndo, pptr, "\n\t ", length);
return (0);
}
/*
* Now print the TLV's.
*/
while (packet_len > 0) {
ND_TCHECK2(*pptr, 2);
if (packet_len < 2)
goto trunc;
tlv_type = *pptr++;
tlv_len = *pptr++;
tmp =tlv_len; /* copy temporary len & pointer to packet data */
tptr = pptr;
packet_len -= 2;
/* first lets see if we know the TLVs name*/
ND_PRINT((ndo, "\n\t %s TLV #%u, length: %u",
tok2str(isis_tlv_values,
"unknown",
tlv_type),
tlv_type,
tlv_len));
if (tlv_len == 0) /* something is invalid */
continue;
if (packet_len < tlv_len)
goto trunc;
/* now check if we have a decoder otherwise do a hexdump at the end*/
switch (tlv_type) {
case ISIS_TLV_AREA_ADDR:
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
while (tmp && alen < tmp) {
ND_TCHECK2(*tptr, alen);
ND_PRINT((ndo, "\n\t Area address (length: %u): %s",
alen,
isonsap_string(ndo, tptr, alen)));
tptr += alen;
tmp -= alen + 1;
if (tmp==0) /* if this is the last area address do not attemt a boundary check */
break;
ND_TCHECK2(*tptr, 1);
alen = *tptr++;
}
break;
case ISIS_TLV_ISNEIGH:
while (tmp >= ETHER_ADDR_LEN) {
ND_TCHECK2(*tptr, ETHER_ADDR_LEN);
ND_PRINT((ndo, "\n\t SNPA: %s", isis_print_id(tptr, ETHER_ADDR_LEN)));
tmp -= ETHER_ADDR_LEN;
tptr += ETHER_ADDR_LEN;
}
break;
case ISIS_TLV_ISNEIGH_VARLEN:
if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */
goto trunctlv;
lan_alen = *tptr++; /* LAN address length */
if (lan_alen == 0) {
ND_PRINT((ndo, "\n\t LAN address length 0 bytes (invalid)"));
break;
}
tmp --;
ND_PRINT((ndo, "\n\t LAN address length %u bytes ", lan_alen));
while (tmp >= lan_alen) {
ND_TCHECK2(*tptr, lan_alen);
ND_PRINT((ndo, "\n\t\tIS Neighbor: %s", isis_print_id(tptr, lan_alen)));
tmp -= lan_alen;
tptr +=lan_alen;
}
break;
case ISIS_TLV_PADDING:
break;
case ISIS_TLV_MT_IS_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
while (tmp >= 2+NODE_ID_LEN+3+1) {
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_ALIAS_ID:
while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_EXT_IS_REACH:
while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */
ext_is_len = isis_print_ext_is_reach(ndo, tptr, "\n\t ", tlv_type);
if (ext_is_len == 0) /* did something go wrong ? */
goto trunctlv;
tmp-=ext_is_len;
tptr+=ext_is_len;
}
break;
case ISIS_TLV_IS_REACH:
ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */
ND_PRINT((ndo, "\n\t %s",
tok2str(isis_is_reach_virtual_values,
"bogus virtual flag 0x%02x",
*tptr++)));
tlv_is_reach = (const struct isis_tlv_is_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_is_reach)) {
ND_TCHECK(*tlv_is_reach);
ND_PRINT((ndo, "\n\t IS Neighbor: %s",
isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN)));
isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_is_reach);
tlv_is_reach++;
}
break;
case ISIS_TLV_ESNEIGH:
tlv_es_reach = (const struct isis_tlv_es_reach *)tptr;
while (tmp >= sizeof(struct isis_tlv_es_reach)) {
ND_TCHECK(*tlv_es_reach);
ND_PRINT((ndo, "\n\t ES Neighbor: %s",
isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN)));
isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block);
tmp -= sizeof(struct isis_tlv_es_reach);
tlv_es_reach++;
}
break;
/* those two TLVs share the same format */
case ISIS_TLV_INT_IP_REACH:
case ISIS_TLV_EXT_IP_REACH:
if (!isis_print_tlv_ip_reach(ndo, pptr, "\n\t ", tlv_len))
return (1);
break;
case ISIS_TLV_EXTD_IP_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6_REACH:
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_MT_IP6_REACH:
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) { /* did something go wrong ? */
goto trunctlv;
}
tptr+=mt_len;
tmp-=mt_len;
while (tmp>0) {
ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, "\n\t ", AF_INET6);
if (ext_ip_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=ext_ip_len;
tmp-=ext_ip_len;
}
break;
case ISIS_TLV_IP6ADDR:
while (tmp>=sizeof(struct in6_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in6_addr));
ND_PRINT((ndo, "\n\t IPv6 interface address: %s",
ip6addr_string(ndo, tptr)));
tptr += sizeof(struct in6_addr);
tmp -= sizeof(struct in6_addr);
}
break;
case ISIS_TLV_AUTH:
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t %s: ",
tok2str(isis_subtlv_auth_values,
"unknown Authentication type 0x%02x",
*tptr)));
switch (*tptr) {
case ISIS_SUBTLV_AUTH_SIMPLE:
if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_SUBTLV_AUTH_MD5:
for(i=1;i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
if (tlv_len != ISIS_SUBTLV_AUTH_MD5_LEN+1)
ND_PRINT((ndo, ", (invalid subTLV) "));
sigcheck = signature_verify(ndo, optr, length, tptr + 1,
isis_clear_checksum_lifetime,
header_lsp);
ND_PRINT((ndo, " (%s)", tok2str(signature_check_values, "Unknown", sigcheck)));
break;
case ISIS_SUBTLV_AUTH_GENERIC:
ND_TCHECK2(*(tptr + 1), 2);
key_id = EXTRACT_16BITS((tptr+1));
ND_PRINT((ndo, "%u, password: ", key_id));
for(i=1 + sizeof(uint16_t);i<tlv_len;i++) {
ND_TCHECK2(*(tptr + i), 1);
ND_PRINT((ndo, "%02x", *(tptr + i)));
}
break;
case ISIS_SUBTLV_AUTH_PRIVATE:
default:
if (!print_unknown_data(ndo, tptr + 1, "\n\t\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_PTP_ADJ:
tlv_ptp_adj = (const struct isis_tlv_ptp_adj *)tptr;
if(tmp>=1) {
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, "\n\t Adjacency State: %s (%u)",
tok2str(isis_ptp_adjancey_values, "unknown", *tptr),
*tptr));
tmp--;
}
if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id)));
tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id);
}
if(tmp>=SYSTEM_ID_LEN) {
ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t Neighbor System-ID: %s",
isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN)));
tmp-=SYSTEM_ID_LEN;
}
if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) {
ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id);
ND_PRINT((ndo, "\n\t Neighbor Extended Local circuit-ID: 0x%08x",
EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id)));
}
break;
case ISIS_TLV_PROTOCOLS:
ND_PRINT((ndo, "\n\t NLPID(s): "));
while (tmp>0) {
ND_TCHECK2(*(tptr), 1);
ND_PRINT((ndo, "%s (0x%02x)",
tok2str(nlpid_values,
"unknown",
*tptr),
*tptr));
if (tmp>1) /* further NPLIDs ? - put comma */
ND_PRINT((ndo, ", "));
tptr++;
tmp--;
}
break;
case ISIS_TLV_MT_PORT_CAP:
{
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t RES: %d, MTID(s): %d",
(EXTRACT_16BITS (tptr) >> 12),
(EXTRACT_16BITS (tptr) & 0x0fff)));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_port_cap_subtlv(ndo, tptr, tmp);
break;
}
case ISIS_TLV_MT_CAPABILITY:
ND_TCHECK2(*(tptr), 2);
ND_PRINT((ndo, "\n\t O: %d, RES: %d, MTID(s): %d",
(EXTRACT_16BITS(tptr) >> 15) & 0x01,
(EXTRACT_16BITS(tptr) >> 12) & 0x07,
EXTRACT_16BITS(tptr) & 0x0fff));
tmp = tmp-2;
tptr = tptr+2;
if (tmp)
isis_print_mt_capability_subtlv(ndo, tptr, tmp);
break;
case ISIS_TLV_TE_ROUTER_ID:
ND_TCHECK2(*pptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t Traffic Engineering Router ID: %s", ipaddr_string(ndo, pptr)));
break;
case ISIS_TLV_IPADDR:
while (tmp>=sizeof(struct in_addr)) {
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr += sizeof(struct in_addr);
tmp -= sizeof(struct in_addr);
}
break;
case ISIS_TLV_HOSTNAME:
ND_PRINT((ndo, "\n\t Hostname: "));
if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend))
goto trunctlv;
break;
case ISIS_TLV_SHARED_RISK_GROUP:
if (tmp < NODE_ID_LEN)
break;
ND_TCHECK2(*tptr, NODE_ID_LEN);
ND_PRINT((ndo, "\n\t IS Neighbor: %s", isis_print_id(tptr, NODE_ID_LEN)));
tptr+=(NODE_ID_LEN);
tmp-=(NODE_ID_LEN);
if (tmp < 1)
break;
ND_TCHECK2(*tptr, 1);
ND_PRINT((ndo, ", Flags: [%s]", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? "numbered" : "unnumbered"));
tmp--;
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 interface address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
if (tmp < sizeof(struct in_addr))
break;
ND_TCHECK2(*tptr, sizeof(struct in_addr));
ND_PRINT((ndo, "\n\t IPv4 neighbor address: %s", ipaddr_string(ndo, tptr)));
tptr+=sizeof(struct in_addr);
tmp-=sizeof(struct in_addr);
while (tmp>=4) {
ND_TCHECK2(*tptr, 4);
ND_PRINT((ndo, "\n\t Link-ID: 0x%08x", EXTRACT_32BITS(tptr)));
tptr+=4;
tmp-=4;
}
break;
case ISIS_TLV_LSP:
tlv_lsp = (const struct isis_tlv_lsp *)tptr;
while(tmp>=sizeof(struct isis_tlv_lsp)) {
ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]);
ND_PRINT((ndo, "\n\t lsp-id: %s",
isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN)));
ND_TCHECK2(tlv_lsp->sequence_number, 4);
ND_PRINT((ndo, ", seq: 0x%08x", EXTRACT_32BITS(tlv_lsp->sequence_number)));
ND_TCHECK2(tlv_lsp->remaining_lifetime, 2);
ND_PRINT((ndo, ", lifetime: %5ds", EXTRACT_16BITS(tlv_lsp->remaining_lifetime)));
ND_TCHECK2(tlv_lsp->checksum, 2);
ND_PRINT((ndo, ", chksum: 0x%04x", EXTRACT_16BITS(tlv_lsp->checksum)));
tmp-=sizeof(struct isis_tlv_lsp);
tlv_lsp++;
}
break;
case ISIS_TLV_CHECKSUM:
if (tmp < ISIS_TLV_CHECKSUM_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN);
ND_PRINT((ndo, "\n\t checksum: 0x%04x ", EXTRACT_16BITS(tptr)));
/* do not attempt to verify the checksum if it is zero
* most likely a HMAC-MD5 TLV is also present and
* to avoid conflicts the checksum TLV is zeroed.
* see rfc3358 for details
*/
osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr,
length);
break;
case ISIS_TLV_POI:
if (tlv_len >= SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Purge Originator System-ID: %s",
isis_print_id(tptr + 1, SYSTEM_ID_LEN)));
}
if (tlv_len == 2 * SYSTEM_ID_LEN + 1) {
ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1);
ND_PRINT((ndo, "\n\t Received from System-ID: %s",
isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_MT_SUPPORTED:
if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN)
break;
while (tmp>1) {
/* length can only be a multiple of 2, otherwise there is
something broken -> so decode down until length is 1 */
if (tmp!=1) {
mt_len = isis_print_mtid(ndo, tptr, "\n\t ");
if (mt_len == 0) /* did something go wrong ? */
goto trunctlv;
tptr+=mt_len;
tmp-=mt_len;
} else {
ND_PRINT((ndo, "\n\t invalid MT-ID"));
break;
}
}
break;
case ISIS_TLV_RESTART_SIGNALING:
/* first attempt to decode the flags */
if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN);
ND_PRINT((ndo, "\n\t Flags [%s]",
bittok2str(isis_restart_flag_values, "none", *tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN;
/* is there anything other than the flags field? */
if (tmp == 0)
break;
if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN);
ND_PRINT((ndo, ", Remaining holding time %us", EXTRACT_16BITS(tptr)));
tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN;
/* is there an additional sysid field present ?*/
if (tmp == SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, ", for %s", isis_print_id(tptr,SYSTEM_ID_LEN)));
}
break;
case ISIS_TLV_IDRP_INFO:
if (tmp < ISIS_TLV_IDRP_INFO_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN);
ND_PRINT((ndo, "\n\t Inter-Domain Information Type: %s",
tok2str(isis_subtlv_idrp_values,
"Unknown (0x%02x)",
*tptr)));
switch (*tptr++) {
case ISIS_SUBTLV_IDRP_ASN:
ND_TCHECK2(*tptr, 2); /* fetch AS number */
ND_PRINT((ndo, "AS Number: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_SUBTLV_IDRP_LOCAL:
case ISIS_SUBTLV_IDRP_RES:
default:
if (!print_unknown_data(ndo, tptr, "\n\t ", tlv_len - 1))
return(0);
break;
}
break;
case ISIS_TLV_LSP_BUFFERSIZE:
if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN);
ND_PRINT((ndo, "\n\t LSP Buffersize: %u", EXTRACT_16BITS(tptr)));
break;
case ISIS_TLV_PART_DIS:
while (tmp >= SYSTEM_ID_LEN) {
ND_TCHECK2(*tptr, SYSTEM_ID_LEN);
ND_PRINT((ndo, "\n\t %s", isis_print_id(tptr, SYSTEM_ID_LEN)));
tptr+=SYSTEM_ID_LEN;
tmp-=SYSTEM_ID_LEN;
}
break;
case ISIS_TLV_PREFIX_NEIGH:
if (tmp < sizeof(struct isis_metric_block))
break;
ND_TCHECK2(*tptr, sizeof(struct isis_metric_block));
ND_PRINT((ndo, "\n\t Metric Block"));
isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr);
tptr+=sizeof(struct isis_metric_block);
tmp-=sizeof(struct isis_metric_block);
while(tmp>0) {
ND_TCHECK2(*tptr, 1);
prefix_len=*tptr++; /* read out prefix length in semioctets*/
if (prefix_len < 2) {
ND_PRINT((ndo, "\n\t\tAddress: prefix length %u < 2", prefix_len));
break;
}
tmp--;
if (tmp < prefix_len/2)
break;
ND_TCHECK2(*tptr, prefix_len / 2);
ND_PRINT((ndo, "\n\t\tAddress: %s/%u",
isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4));
tptr+=prefix_len/2;
tmp-=prefix_len/2;
}
break;
case ISIS_TLV_IIH_SEQNR:
if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */
ND_PRINT((ndo, "\n\t Sequence number: %u", EXTRACT_32BITS(tptr)));
break;
case ISIS_TLV_VENDOR_PRIVATE:
if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN)
break;
ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */
vendor_id = EXTRACT_24BITS(tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (%u)",
tok2str(oui_values, "Unknown", vendor_id),
vendor_id));
tptr+=3;
tmp-=3;
if (tmp > 0) /* hexdump the rest */
if (!print_unknown_data(ndo, tptr, "\n\t\t", tmp))
return(0);
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case ISIS_TLV_DECNET_PHASE4:
case ISIS_TLV_LUCENT_PRIVATE:
case ISIS_TLV_IPAUTH:
case ISIS_TLV_NORTEL_PRIVATE1:
case ISIS_TLV_NORTEL_PRIVATE2:
default:
if (ndo->ndo_vflag <= 1) {
if (!print_unknown_data(ndo, pptr, "\n\t\t", tlv_len))
return(0);
}
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1) {
if (!print_unknown_data(ndo, pptr, "\n\t ", tlv_len))
return(0);
}
pptr += tlv_len;
packet_len -= tlv_len;
}
if (packet_len != 0) {
ND_PRINT((ndo, "\n\t %u straggler bytes", packet_len));
}
return (1);
trunc:
ND_PRINT((ndo, "%s", tstr));
return (1);
trunctlv:
ND_PRINT((ndo, "\n\t\t"));
ND_PRINT((ndo, "%s", tstr));
return(1);
}
static void
osi_print_cksum(netdissect_options *ndo, const uint8_t *pptr,
uint16_t checksum, int checksum_offset, u_int length)
{
uint16_t calculated_checksum;
/* do not attempt to verify the checksum if it is zero,
* if the offset is nonsense,
* or the base pointer is not sane
*/
if (!checksum
|| checksum_offset < 0
|| !ND_TTEST2(*(pptr + checksum_offset), 2)
|| (u_int)checksum_offset > length
|| !ND_TTEST2(*pptr, length)) {
ND_PRINT((ndo, " (unverified)"));
} else {
#if 0
printf("\nosi_print_cksum: %p %u %u\n", pptr, checksum_offset, length);
#endif
calculated_checksum = create_osi_cksum(pptr, checksum_offset, length);
if (checksum == calculated_checksum) {
ND_PRINT((ndo, " (correct)"));
} else {
ND_PRINT((ndo, " (incorrect should be 0x%04x)", calculated_checksum));
}
}
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2731_0 |
crossvul-cpp_data_good_2675_0 | /*
* Copyright (c) 2009
* Siemens AG, All rights reserved.
* Dmitry Eremin-Solenikov (dbaryshkov@gmail.com)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IEEE 802.15.4 printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char *ftypes[] = {
"Beacon", /* 0 */
"Data", /* 1 */
"ACK", /* 2 */
"Command", /* 3 */
"Reserved (0x4)", /* 4 */
"Reserved (0x5)", /* 5 */
"Reserved (0x6)", /* 6 */
"Reserved (0x7)", /* 7 */
};
/*
* Frame Control subfields.
*/
#define FC_FRAME_TYPE(fc) ((fc) & 0x7)
#define FC_SECURITY_ENABLED 0x0008
#define FC_FRAME_PENDING 0x0010
#define FC_ACK_REQUEST 0x0020
#define FC_PAN_ID_COMPRESSION 0x0040
#define FC_DEST_ADDRESSING_MODE(fc) (((fc) >> 10) & 0x3)
#define FC_FRAME_VERSION(fc) (((fc) >> 12) & 0x3)
#define FC_SRC_ADDRESSING_MODE(fc) (((fc) >> 14) & 0x3)
#define FC_ADDRESSING_MODE_NONE 0x00
#define FC_ADDRESSING_MODE_RESERVED 0x01
#define FC_ADDRESSING_MODE_SHORT 0x02
#define FC_ADDRESSING_MODE_LONG 0x03
u_int
ieee802_15_4_if_print(netdissect_options *ndo,
const struct pcap_pkthdr *h, const u_char *p)
{
u_int caplen = h->caplen;
u_int hdrlen;
uint16_t fc;
uint8_t seq;
uint16_t panid = 0;
if (caplen < 3) {
ND_PRINT((ndo, "[|802.15.4]"));
return caplen;
}
hdrlen = 3;
fc = EXTRACT_LE_16BITS(p);
seq = EXTRACT_LE_8BITS(p + 2);
p += 3;
caplen -= 3;
ND_PRINT((ndo,"IEEE 802.15.4 %s packet ", ftypes[FC_FRAME_TYPE(fc)]));
if (ndo->ndo_vflag)
ND_PRINT((ndo,"seq %02x ", seq));
/*
* Destination address and PAN ID, if present.
*/
switch (FC_DEST_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (fc & FC_PAN_ID_COMPRESSION) {
/*
* PAN ID compression; this requires that both
* the source and destination addresses be present,
* but the destination address is missing.
*/
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved destination addressing mode"));
return hdrlen;
case FC_ADDRESSING_MODE_SHORT:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p + 2)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"< "));
/*
* Source address and PAN ID, if present.
*/
switch (FC_SRC_ADDRESSING_MODE(fc)) {
case FC_ADDRESSING_MODE_NONE:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"none "));
break;
case FC_ADDRESSING_MODE_RESERVED:
if (ndo->ndo_vflag)
ND_PRINT((ndo,"reserved source addressing mode"));
return 0;
case FC_ADDRESSING_MODE_SHORT:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%04x ", panid, EXTRACT_LE_16BITS(p)));
p += 2;
caplen -= 2;
hdrlen += 2;
break;
case FC_ADDRESSING_MODE_LONG:
if (!(fc & FC_PAN_ID_COMPRESSION)) {
/*
* The source PAN ID is not compressed out, so
* fetch it. (Otherwise, we'll use the destination
* PAN ID, fetched above.)
*/
if (caplen < 2) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
panid = EXTRACT_LE_16BITS(p);
p += 2;
caplen -= 2;
hdrlen += 2;
}
if (caplen < 8) {
ND_PRINT((ndo, "[|802.15.4]"));
return hdrlen;
}
if (ndo->ndo_vflag)
ND_PRINT((ndo,"%04x:%s ", panid, le64addr_string(ndo, p)));
p += 8;
caplen -= 8;
hdrlen += 8;
break;
}
if (!ndo->ndo_suppress_default_print)
ND_DEFAULTPRINT(p, caplen);
return hdrlen;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2675_0 |
crossvul-cpp_data_bad_2700_0 | /*
* Copyright (C) 2002 WIDE Project.
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
/* \summary: IPv6 mobility printer */
/* RFC 3775 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "ip6.h"
static const char tstr[] = "[|MOBILITY]";
/* Mobility header */
struct ip6_mobility {
uint8_t ip6m_pproto; /* following payload protocol (for PG) */
uint8_t ip6m_len; /* length in units of 8 octets */
uint8_t ip6m_type; /* message type */
uint8_t reserved; /* reserved */
uint16_t ip6m_cksum; /* sum of IPv6 pseudo-header and MH */
union {
uint16_t ip6m_un_data16[1]; /* type-specific field */
uint8_t ip6m_un_data8[2]; /* type-specific field */
} ip6m_dataun;
};
#define ip6m_data16 ip6m_dataun.ip6m_un_data16
#define ip6m_data8 ip6m_dataun.ip6m_un_data8
#define IP6M_MINLEN 8
/* http://www.iana.org/assignments/mobility-parameters/mobility-parameters.xhtml */
/* message type */
#define IP6M_BINDING_REQUEST 0 /* Binding Refresh Request */
#define IP6M_HOME_TEST_INIT 1 /* Home Test Init */
#define IP6M_CAREOF_TEST_INIT 2 /* Care-of Test Init */
#define IP6M_HOME_TEST 3 /* Home Test */
#define IP6M_CAREOF_TEST 4 /* Care-of Test */
#define IP6M_BINDING_UPDATE 5 /* Binding Update */
#define IP6M_BINDING_ACK 6 /* Binding Acknowledgement */
#define IP6M_BINDING_ERROR 7 /* Binding Error */
#define IP6M_MAX 7
static const struct tok ip6m_str[] = {
{ IP6M_BINDING_REQUEST, "BRR" },
{ IP6M_HOME_TEST_INIT, "HoTI" },
{ IP6M_CAREOF_TEST_INIT, "CoTI" },
{ IP6M_HOME_TEST, "HoT" },
{ IP6M_CAREOF_TEST, "CoT" },
{ IP6M_BINDING_UPDATE, "BU" },
{ IP6M_BINDING_ACK, "BA" },
{ IP6M_BINDING_ERROR, "BE" },
{ 0, NULL }
};
static const unsigned ip6m_hdrlen[IP6M_MAX + 1] = {
IP6M_MINLEN, /* IP6M_BINDING_REQUEST */
IP6M_MINLEN + 8, /* IP6M_HOME_TEST_INIT */
IP6M_MINLEN + 8, /* IP6M_CAREOF_TEST_INIT */
IP6M_MINLEN + 16, /* IP6M_HOME_TEST */
IP6M_MINLEN + 16, /* IP6M_CAREOF_TEST */
IP6M_MINLEN + 4, /* IP6M_BINDING_UPDATE */
IP6M_MINLEN + 4, /* IP6M_BINDING_ACK */
IP6M_MINLEN + 16, /* IP6M_BINDING_ERROR */
};
/* Mobility Header Options */
#define IP6MOPT_MINLEN 2
#define IP6MOPT_PAD1 0x0 /* Pad1 */
#define IP6MOPT_PADN 0x1 /* PadN */
#define IP6MOPT_REFRESH 0x2 /* Binding Refresh Advice */
#define IP6MOPT_REFRESH_MINLEN 4
#define IP6MOPT_ALTCOA 0x3 /* Alternate Care-of Address */
#define IP6MOPT_ALTCOA_MINLEN 18
#define IP6MOPT_NONCEID 0x4 /* Nonce Indices */
#define IP6MOPT_NONCEID_MINLEN 6
#define IP6MOPT_AUTH 0x5 /* Binding Authorization Data */
#define IP6MOPT_AUTH_MINLEN 12
static int
mobility_opt_print(netdissect_options *ndo,
const u_char *bp, const unsigned len)
{
unsigned i, optlen;
for (i = 0; i < len; i += optlen) {
ND_TCHECK(bp[i]);
if (bp[i] == IP6MOPT_PAD1)
optlen = 1;
else {
if (i + 1 < len) {
ND_TCHECK(bp[i + 1]);
optlen = bp[i + 1] + 2;
}
else
goto trunc;
}
if (i + optlen > len)
goto trunc;
ND_TCHECK(bp[i + optlen]);
switch (bp[i]) {
case IP6MOPT_PAD1:
ND_PRINT((ndo, "(pad1)"));
break;
case IP6MOPT_PADN:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(padn: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(padn)"));
break;
case IP6MOPT_REFRESH:
if (len - i < IP6MOPT_REFRESH_MINLEN) {
ND_PRINT((ndo, "(refresh: trunc)"));
goto trunc;
}
/* units of 4 secs */
ND_TCHECK_16BITS(&bp[i+2]);
ND_PRINT((ndo, "(refresh: %u)",
EXTRACT_16BITS(&bp[i+2]) << 2));
break;
case IP6MOPT_ALTCOA:
if (len - i < IP6MOPT_ALTCOA_MINLEN) {
ND_PRINT((ndo, "(altcoa: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(alt-CoA: %s)", ip6addr_string(ndo, &bp[i+2])));
break;
case IP6MOPT_NONCEID:
if (len - i < IP6MOPT_NONCEID_MINLEN) {
ND_PRINT((ndo, "(ni: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(ni: ho=0x%04x co=0x%04x)",
EXTRACT_16BITS(&bp[i+2]),
EXTRACT_16BITS(&bp[i+4])));
break;
case IP6MOPT_AUTH:
if (len - i < IP6MOPT_AUTH_MINLEN) {
ND_PRINT((ndo, "(auth: trunc)"));
goto trunc;
}
ND_PRINT((ndo, "(auth)"));
break;
default:
if (len - i < IP6MOPT_MINLEN) {
ND_PRINT((ndo, "(sopt_type %u: trunc)", bp[i]));
goto trunc;
}
ND_PRINT((ndo, "(type-0x%02x: len=%u)", bp[i], bp[i + 1]));
break;
}
}
return 0;
trunc:
return 1;
}
/*
* Mobility Header
*/
int
mobility_print(netdissect_options *ndo,
const u_char *bp, const u_char *bp2 _U_)
{
const struct ip6_mobility *mh;
const u_char *ep;
unsigned mhlen, hlen;
uint8_t type;
mh = (const struct ip6_mobility *)bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(mh->ip6m_len)) {
/*
* There's not enough captured data to include the
* mobility header length.
*
* Our caller expects us to return the length, however,
* so return a value that will run to the end of the
* captured data.
*
* XXX - "ip6_print()" doesn't do anything with the
* returned length, however, as it breaks out of the
* header-processing loop.
*/
mhlen = ep - bp;
goto trunc;
}
mhlen = (mh->ip6m_len + 1) << 3;
/* XXX ip6m_cksum */
ND_TCHECK(mh->ip6m_type);
type = mh->ip6m_type;
if (type <= IP6M_MAX && mhlen < ip6m_hdrlen[type]) {
ND_PRINT((ndo, "(header length %u is too small for type %u)", mhlen, type));
goto trunc;
}
ND_PRINT((ndo, "mobility: %s", tok2str(ip6m_str, "type-#%u", type)));
switch (type) {
case IP6M_BINDING_REQUEST:
hlen = IP6M_MINLEN;
break;
case IP6M_HOME_TEST_INIT:
case IP6M_CAREOF_TEST_INIT:
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST_INIT ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_HOME_TEST:
case IP6M_CAREOF_TEST:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " nonce id=0x%x", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Init Cookie=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
if (ndo->ndo_vflag) {
ND_TCHECK_32BITS(&bp[hlen + 4]);
ND_PRINT((ndo, " %s Keygen Token=%08x:%08x",
type == IP6M_HOME_TEST ? "Home" : "Care-of",
EXTRACT_32BITS(&bp[hlen]),
EXTRACT_32BITS(&bp[hlen + 4])));
}
hlen += 8;
break;
case IP6M_BINDING_UPDATE:
ND_TCHECK(mh->ip6m_data16[0]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&mh->ip6m_data16[0])));
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
if (bp[hlen] & 0xf0) {
ND_PRINT((ndo, " "));
if (bp[hlen] & 0x80)
ND_PRINT((ndo, "A"));
if (bp[hlen] & 0x40)
ND_PRINT((ndo, "H"));
if (bp[hlen] & 0x20)
ND_PRINT((ndo, "L"));
if (bp[hlen] & 0x10)
ND_PRINT((ndo, "K"));
}
/* Reserved (4bits) */
hlen += 1;
/* Reserved (8bits) */
hlen += 1;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ACK:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
ND_TCHECK(mh->ip6m_data8[1]);
if (mh->ip6m_data8[1] & 0x80)
ND_PRINT((ndo, " K"));
/* Reserved (7bits) */
hlen = IP6M_MINLEN;
ND_TCHECK_16BITS(&bp[hlen]);
ND_PRINT((ndo, " seq#=%u", EXTRACT_16BITS(&bp[hlen])));
hlen += 2;
ND_TCHECK_16BITS(&bp[hlen]);
/* units of 4 secs */
ND_PRINT((ndo, " lifetime=%u", EXTRACT_16BITS(&bp[hlen]) << 2));
hlen += 2;
break;
case IP6M_BINDING_ERROR:
ND_TCHECK(mh->ip6m_data8[0]);
ND_PRINT((ndo, " status=%u", mh->ip6m_data8[0]));
/* Reserved */
hlen = IP6M_MINLEN;
ND_TCHECK2(bp[hlen], 16);
ND_PRINT((ndo, " homeaddr %s", ip6addr_string(ndo, &bp[hlen])));
hlen += 16;
break;
default:
ND_PRINT((ndo, " len=%u", mh->ip6m_len));
return(mhlen);
break;
}
if (ndo->ndo_vflag)
if (mobility_opt_print(ndo, &bp[hlen], mhlen - hlen))
goto trunc;
return(mhlen);
trunc:
ND_PRINT((ndo, "%s", tstr));
return(-1);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2700_0 |
crossvul-cpp_data_bad_4652_0 | /*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Francesco Fondelli (francesco dot fondelli, gmail dot com)
*/
/* \summary: Autosar SOME/IP Protocol printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "netdissect-stdinc.h"
#include "netdissect.h"
#include "extract.h"
#include "udp.h"
/*
* SOMEIP Header (R19-11)
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Message ID (Service ID/Method ID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Request ID (Client ID/Session ID) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Protocol Ver | Interface Ver | Message Type | Return Code |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Payload |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct tok message_type_values[] = {
{ 0x00, "REQUEST" },
{ 0x01, "REQUEST_NO_RETURN" },
{ 0x02, "NOTIFICATION" },
{ 0x80, "RESPONSE" },
{ 0x81, "ERROR" },
{ 0x20, "TP_REQUEST" },
{ 0x21, "TP_REQUEST_NO_RETURN" },
{ 0x22, "TP_NOTIFICATION" },
{ 0xa0, "TP_RESPONSE" },
{ 0xa1, "TP_ERROR" },
{ 0, NULL }
};
struct tok return_code_values[] = {
{ 0x00, "E_OK" },
{ 0x01, "E_NOT_OK" },
{ 0x02, "E_UNKNOWN_SERVICE" },
{ 0x03, "E_UNKNOWN_METHOD" },
{ 0x04, "E_NOT_READY" },
{ 0x05, "E_NOT_REACHABLE" },
{ 0x06, "E_TIMEOUT" },
{ 0x07, "E_WRONG_PROTOCOL_VERSION" },
{ 0x08, "E_WRONG_INTERFACE_VERSION" },
{ 0x09, "E_MALFORMED_MESSAGE" },
{ 0x0a, "E_WRONG_MESSAGE_TYPE" },
{ 0x0b, "E_E2E_REPEATED" },
{ 0x0c, "E_E2E_WRONG_SEQUENCE" },
{ 0x0d, "E_E2E" },
{ 0x0e, "E_E2E_NOT_AVAILABLE" },
{ 0x0f, "E_E2E_NO_NEW_DATA" },
};
void
someip_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
uint32_t message_id;
uint16_t service_id;
uint16_t method_or_event_id;
uint8_t event_flag;
uint32_t message_len;
uint32_t request_id;
uint16_t client_id;
uint16_t session_id;
uint8_t protocol_version;
uint8_t interface_version;
uint8_t message_type;
uint8_t return_code;
ndo->ndo_protocol = "someip";
if (len < 16) {
nd_print_trunc(ndo);
return;
}
message_id = GET_BE_U_4(bp);
service_id = message_id >> 16;
event_flag = (message_id & 0x00008000) >> 15;
method_or_event_id = message_id & 0x00007FFF;
bp += 4;
message_len = GET_BE_U_4(bp);
bp += 4;
request_id = GET_BE_U_4(bp);
client_id = request_id >> 16;
session_id = request_id & 0x0000FFFF;
bp += 4;
protocol_version = GET_U_1(bp);
bp += 1;
interface_version = GET_U_1(bp);
bp += 1;
message_type = GET_U_1(bp);
bp += 1;
return_code = GET_U_1(bp);
bp += 1;
ND_PRINT("SOMEIP, service %u, %s %u, len %u, client %u, session %u, "
"pver %u, iver %u, msgtype %s, retcode %s\n",
service_id, event_flag ? "event" : "method", method_or_event_id,
message_len, client_id, session_id, protocol_version,
interface_version,
tok2str(message_type_values, "Unknown", message_type),
tok2str(return_code_values, "Unknown", return_code));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4652_0 |
crossvul-cpp_data_good_1423_0 | /*
* Copyright (c) Christos Zoulas 2003.
* 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 immediately at the beginning of the file, without modification,
* 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 "file.h"
#ifndef lint
FILE_RCSID("@(#)$File: readelf.c,v 1.157 2019/01/02 19:44:14 christos Exp $")
#endif
#ifdef BUILTIN_ELF
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include "readelf.h"
#include "magic.h"
#ifdef ELFCORE
private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int *, uint16_t *);
#endif
private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int, int *, uint16_t *);
private int doshn(struct magic_set *, int, int, int, off_t, int, size_t,
off_t, int, int, int *, uint16_t *);
private size_t donote(struct magic_set *, void *, size_t, size_t, int,
int, size_t, int *, uint16_t *, int, off_t, int, off_t);
#define ELF_ALIGN(a) ((((a) + align - 1) / align) * align)
#define isquote(c) (strchr("'\"`", (c)) != NULL)
private uint16_t getu16(int, uint16_t);
private uint32_t getu32(int, uint32_t);
private uint64_t getu64(int, uint64_t);
#define MAX_PHNUM 128
#define MAX_SHNUM 32768
#define SIZE_UNKNOWN CAST(off_t, -1)
private int
toomany(struct magic_set *ms, const char *name, uint16_t num)
{
if (file_printf(ms, ", too many %s (%u)", name, num) == -1)
return -1;
return 1;
}
private uint16_t
getu16(int swap, uint16_t value)
{
union {
uint16_t ui;
char c[2];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[1];
retval.c[1] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint32_t
getu32(int swap, uint32_t value)
{
union {
uint32_t ui;
char c[4];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[3];
retval.c[1] = tmpval.c[2];
retval.c[2] = tmpval.c[1];
retval.c[3] = tmpval.c[0];
return retval.ui;
} else
return value;
}
private uint64_t
getu64(int swap, uint64_t value)
{
union {
uint64_t ui;
char c[8];
} retval, tmpval;
if (swap) {
tmpval.ui = value;
retval.c[0] = tmpval.c[7];
retval.c[1] = tmpval.c[6];
retval.c[2] = tmpval.c[5];
retval.c[3] = tmpval.c[4];
retval.c[4] = tmpval.c[3];
retval.c[5] = tmpval.c[2];
retval.c[6] = tmpval.c[1];
retval.c[7] = tmpval.c[0];
return retval.ui;
} else
return value;
}
#define elf_getu16(swap, value) getu16(swap, value)
#define elf_getu32(swap, value) getu32(swap, value)
#define elf_getu64(swap, value) getu64(swap, value)
#define xsh_addr (clazz == ELFCLASS32 \
? CAST(void *, &sh32) \
: CAST(void *, &sh64))
#define xsh_sizeof (clazz == ELFCLASS32 \
? sizeof(sh32) \
: sizeof(sh64))
#define xsh_size CAST(size_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_size) \
: elf_getu64(swap, sh64.sh_size)))
#define xsh_offset CAST(off_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_offset) \
: elf_getu64(swap, sh64.sh_offset)))
#define xsh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_type) \
: elf_getu32(swap, sh64.sh_type))
#define xsh_name (clazz == ELFCLASS32 \
? elf_getu32(swap, sh32.sh_name) \
: elf_getu32(swap, sh64.sh_name))
#define xph_addr (clazz == ELFCLASS32 \
? CAST(void *, &ph32) \
: CAST(void *, &ph64))
#define xph_sizeof (clazz == ELFCLASS32 \
? sizeof(ph32) \
: sizeof(ph64))
#define xph_type (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_type) \
: elf_getu32(swap, ph64.p_type))
#define xph_offset CAST(off_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_offset) \
: elf_getu64(swap, ph64.p_offset)))
#define xph_align CAST(size_t, (clazz == ELFCLASS32 \
? CAST(off_t, (ph32.p_align ? \
elf_getu32(swap, ph32.p_align) : 4))\
: CAST(off_t, (ph64.p_align ? \
elf_getu64(swap, ph64.p_align) : 4))))
#define xph_vaddr CAST(size_t, (clazz == ELFCLASS32 \
? CAST(off_t, (ph32.p_vaddr ? \
elf_getu32(swap, ph32.p_vaddr) : 4))\
: CAST(off_t, (ph64.p_vaddr ? \
elf_getu64(swap, ph64.p_vaddr) : 4))))
#define xph_filesz CAST(size_t, (clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_filesz) \
: elf_getu64(swap, ph64.p_filesz)))
#define xph_memsz CAST(size_t, ((clazz == ELFCLASS32 \
? elf_getu32(swap, ph32.p_memsz) \
: elf_getu64(swap, ph64.p_memsz))))
#define xnh_addr (clazz == ELFCLASS32 \
? CAST(void *, &nh32) \
: CAST(void *, &nh64))
#define xnh_sizeof (clazz == ELFCLASS32 \
? sizeof(nh32) \
: sizeof(nh64))
#define xnh_type (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_type) \
: elf_getu32(swap, nh64.n_type))
#define xnh_namesz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_namesz) \
: elf_getu32(swap, nh64.n_namesz))
#define xnh_descsz (clazz == ELFCLASS32 \
? elf_getu32(swap, nh32.n_descsz) \
: elf_getu32(swap, nh64.n_descsz))
#define xdh_addr (clazz == ELFCLASS32 \
? CAST(void *, &dh32) \
: CAST(void *, &dh64))
#define xdh_sizeof (clazz == ELFCLASS32 \
? sizeof(dh32) \
: sizeof(dh64))
#define xdh_tag (clazz == ELFCLASS32 \
? elf_getu32(swap, dh32.d_tag) \
: elf_getu64(swap, dh64.d_tag))
#define xdh_val (clazz == ELFCLASS32 \
? elf_getu32(swap, dh32.d_un.d_val) \
: elf_getu64(swap, dh64.d_un.d_val))
#define xcap_addr (clazz == ELFCLASS32 \
? CAST(void *, &cap32) \
: CAST(void *, &cap64))
#define xcap_sizeof (clazz == ELFCLASS32 \
? sizeof(cap32) \
: sizeof(cap64))
#define xcap_tag (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_tag) \
: elf_getu64(swap, cap64.c_tag))
#define xcap_val (clazz == ELFCLASS32 \
? elf_getu32(swap, cap32.c_un.c_val) \
: elf_getu64(swap, cap64.c_un.c_val))
#define xauxv_addr (clazz == ELFCLASS32 \
? CAST(void *, &auxv32) \
: CAST(void *, &auxv64))
#define xauxv_sizeof (clazz == ELFCLASS32 \
? sizeof(auxv32) \
: sizeof(auxv64))
#define xauxv_type (clazz == ELFCLASS32 \
? elf_getu32(swap, auxv32.a_type) \
: elf_getu64(swap, auxv64.a_type))
#define xauxv_val (clazz == ELFCLASS32 \
? elf_getu32(swap, auxv32.a_v) \
: elf_getu64(swap, auxv64.a_v))
#define prpsoffsets(i) (clazz == ELFCLASS32 \
? prpsoffsets32[i] \
: prpsoffsets64[i])
#ifdef ELFCORE
/*
* Try larger offsets first to avoid false matches
* from earlier data that happen to look like strings.
*/
static const size_t prpsoffsets32[] = {
#ifdef USE_NT_PSINFO
104, /* SunOS 5.x (command line) */
88, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
100, /* SunOS 5.x (command line) */
84, /* SunOS 5.x (short name) */
44, /* Linux (command line) */
28, /* Linux 2.0.36 (short name) */
8, /* FreeBSD */
};
static const size_t prpsoffsets64[] = {
#ifdef USE_NT_PSINFO
152, /* SunOS 5.x (command line) */
136, /* SunOS 5.x (short name) */
#endif /* USE_NT_PSINFO */
136, /* SunOS 5.x, 64-bit (command line) */
120, /* SunOS 5.x, 64-bit (short name) */
56, /* Linux (command line) */
40, /* Linux (tested on core from 2.4.x, short name) */
16, /* FreeBSD, 64-bit */
};
#define NOFFSETS32 (sizeof(prpsoffsets32) / sizeof(prpsoffsets32[0]))
#define NOFFSETS64 (sizeof(prpsoffsets64) / sizeof(prpsoffsets64[0]))
#define NOFFSETS (clazz == ELFCLASS32 ? NOFFSETS32 : NOFFSETS64)
/*
* Look through the program headers of an executable image, searching
* for a PT_NOTE section of type NT_PRPSINFO, with a name "CORE" or
* "FreeBSD"; if one is found, try looking in various places in its
* contents for a 16-character string containing only printable
* characters - if found, that string should be the name of the program
* that dropped core. Note: right after that 16-character string is,
* at least in SunOS 5.x (and possibly other SVR4-flavored systems) and
* Linux, a longer string (80 characters, in 5.x, probably other
* SVR4-flavored systems, and Linux) containing the start of the
* command line for that program.
*
* SunOS 5.x core files contain two PT_NOTE sections, with the types
* NT_PRPSINFO (old) and NT_PSINFO (new). These structs contain the
* same info about the command name and command line, so it probably
* isn't worthwhile to look for NT_PSINFO, but the offsets are provided
* above (see USE_NT_PSINFO), in case we ever decide to do so. The
* NT_PRPSINFO and NT_PSINFO sections are always in order and adjacent;
* the SunOS 5.x file command relies on this (and prefers the latter).
*
* The signal number probably appears in a section of type NT_PRSTATUS,
* but that's also rather OS-dependent, in ways that are harder to
* dissect with heuristics, so I'm not bothering with the signal number.
* (I suppose the signal number could be of interest in situations where
* you don't have the binary of the program that dropped core; if you
* *do* have that binary, the debugger will probably tell you what
* signal it was.)
*/
#define OS_STYLE_SVR4 0
#define OS_STYLE_FREEBSD 1
#define OS_STYLE_NETBSD 2
private const char os_style_names[][8] = {
"SVR4",
"FreeBSD",
"NetBSD",
};
#define FLAGS_CORE_STYLE 0x0003
#define FLAGS_DID_CORE 0x0004
#define FLAGS_DID_OS_NOTE 0x0008
#define FLAGS_DID_BUILD_ID 0x0010
#define FLAGS_DID_CORE_STYLE 0x0020
#define FLAGS_DID_NETBSD_PAX 0x0040
#define FLAGS_DID_NETBSD_MARCH 0x0080
#define FLAGS_DID_NETBSD_CMODEL 0x0100
#define FLAGS_DID_NETBSD_EMULATION 0x0200
#define FLAGS_DID_NETBSD_UNKNOWN 0x0400
#define FLAGS_IS_CORE 0x0800
#define FLAGS_DID_AUXV 0x1000
private int
dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int *flags, uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
size_t offset, len;
unsigned char nbuf[BUFSIZ];
ssize_t bufsize;
off_t ph_off = off;
int ph_num = num;
if (num == 0) {
if (file_printf(ms, ", no program header") == -1)
return -1;
return 0;
}
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
/*
* Loop through all the program headers.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) <
CAST(ssize_t, xph_sizeof)) {
file_badread(ms);
return -1;
}
off += size;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (xph_type != PT_NOTE)
continue;
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
len = xph_filesz < sizeof(nbuf) ? xph_filesz : sizeof(nbuf);
if ((bufsize = pread(fd, nbuf, len, xph_offset)) == -1) {
file_badread(ms);
return -1;
}
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset, (size_t)bufsize,
clazz, swap, 4, flags, notecount, fd, ph_off,
ph_num, fsize);
if (offset == 0)
break;
}
}
return 0;
}
#endif
static void
do_note_netbsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for NetBSD") == -1)
return;
/*
* The version number used to be stuck as 199905, and was thus
* basically content-free. Newer versions of NetBSD have fixed
* this and now use the encoding of __NetBSD_Version__:
*
* MMmmrrpp00
*
* M = major version
* m = minor version
* r = release ["",A-Z,Z[A-Z] but numeric]
* p = patchlevel
*/
if (desc > 100000000U) {
uint32_t ver_patch = (desc / 100) % 100;
uint32_t ver_rel = (desc / 10000) % 100;
uint32_t ver_min = (desc / 1000000) % 100;
uint32_t ver_maj = desc / 100000000;
if (file_printf(ms, " %u.%u", ver_maj, ver_min) == -1)
return;
if (ver_rel == 0 && ver_patch != 0) {
if (file_printf(ms, ".%u", ver_patch) == -1)
return;
} else if (ver_rel != 0) {
while (ver_rel > 26) {
if (file_printf(ms, "Z") == -1)
return;
ver_rel -= 26;
}
if (file_printf(ms, "%c", 'A' + ver_rel - 1)
== -1)
return;
}
}
}
static void
do_note_freebsd_version(struct magic_set *ms, int swap, void *v)
{
uint32_t desc;
memcpy(&desc, v, sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, ", for FreeBSD") == -1)
return;
/*
* Contents is __FreeBSD_version, whose relation to OS
* versions is defined by a huge table in the Porter's
* Handbook. This is the general scheme:
*
* Releases:
* Mmp000 (before 4.10)
* Mmi0p0 (before 5.0)
* Mmm0p0
*
* Development branches:
* Mmpxxx (before 4.6)
* Mmp1xx (before 4.10)
* Mmi1xx (before 5.0)
* M000xx (pre-M.0)
* Mmm1xx
*
* M = major version
* m = minor version
* i = minor version increment (491000 -> 4.10)
* p = patchlevel
* x = revision
*
* The first release of FreeBSD to use ELF by default
* was version 3.0.
*/
if (desc == 460002) {
if (file_printf(ms, " 4.6.2") == -1)
return;
} else if (desc < 460100) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10) == -1)
return;
if (desc / 1000 % 10 > 0)
if (file_printf(ms, ".%d", desc / 1000 % 10) == -1)
return;
if ((desc % 1000 > 0) || (desc % 100000 == 0))
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc < 500000) {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 10000 % 10 + desc / 1000 % 10) == -1)
return;
if (desc / 100 % 10 > 0) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
} else {
if (file_printf(ms, " %d.%d", desc / 100000,
desc / 1000 % 100) == -1)
return;
if ((desc / 100 % 10 > 0) ||
(desc % 100000 / 100 == 0)) {
if (file_printf(ms, " (%d)", desc) == -1)
return;
} else if (desc / 10 % 10 > 0) {
if (file_printf(ms, ".%d", desc / 10 % 10) == -1)
return;
}
}
}
private int
/*ARGSUSED*/
do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_BUILD_ID && (descsz >= 4 && descsz <= 20)) {
uint8_t desc[20];
const char *btype;
uint32_t i;
*flags |= FLAGS_DID_BUILD_ID;
switch (descsz) {
case 8:
btype = "xxHash";
break;
case 16:
btype = "md5/uuid";
break;
case 20:
btype = "sha1";
break;
default:
btype = "unknown";
break;
}
if (file_printf(ms, ", BuildID[%s]=", btype) == -1)
return 1;
memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return 1;
return 1;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "Go") == 0 &&
type == NT_GO_BUILD_ID && descsz < 128) {
if (file_printf(ms, ", Go BuildID=%s",
(char *)&nbuf[doff]) == -1)
return -1;
return 1;
}
return 0;
}
private int
do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
type == NT_GNU_VERSION && descsz == 2) {
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for SuSE %d.%d", nbuf[doff],
nbuf[doff + 1]) == -1)
return -1;
return 1;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
memcpy(desc, &nbuf[doff], sizeof(desc));
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for GNU/") == -1)
return 1;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return 1;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return 1;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return 1;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return 1;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return 1;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return 1;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return 1;
return 1;
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
if (type == NT_NETBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
do_note_netbsd_version(ms, swap, &nbuf[doff]);
return 1;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (type == NT_FREEBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
do_note_freebsd_version(ms, swap, &nbuf[doff]);
return 1;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
type == NT_OPENBSD_VERSION && descsz == 4) {
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for OpenBSD") == -1)
return 1;
/* Content of note is always 0 */
return 1;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
*flags |= FLAGS_DID_OS_NOTE;
if (file_printf(ms, ", for DragonFly") == -1)
return 1;
memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return 1;
return 1;
}
return 0;
}
private int
do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags)
{
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
*flags |= FLAGS_DID_NETBSD_PAX;
memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return 1;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << (int)i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return 1;
}
return 1;
}
return 0;
}
private int
do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz, uint32_t descsz,
size_t noff, size_t doff, int *flags, size_t size, int clazz)
{
#ifdef ELFCORE
int os_style = -1;
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return 1;
*flags |= FLAGS_DID_CORE_STYLE;
*flags |= os_style;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (type == NT_NETBSD_CORE_PROCINFO) {
char sbuf[512];
struct NetBSD_elfcore_procinfo pi;
memset(&pi, 0, sizeof(pi));
memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi)));
if (file_printf(ms, ", from '%.31s', pid=%u, uid=%u, "
"gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)",
file_printable(sbuf, sizeof(sbuf),
RCAST(char *, pi.cpi_name)),
elf_getu32(swap, (uint32_t)pi.cpi_pid),
elf_getu32(swap, pi.cpi_euid),
elf_getu32(swap, pi.cpi_egid),
elf_getu32(swap, pi.cpi_nlwps),
elf_getu32(swap, (uint32_t)pi.cpi_siglwp),
elf_getu32(swap, pi.cpi_signo),
elf_getu32(swap, pi.cpi_sigcode)) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
}
break;
case OS_STYLE_FREEBSD:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t argoff, pidoff;
if (clazz == ELFCLASS32)
argoff = 4 + 4 + 17;
else
argoff = 4 + 4 + 8 + 17;
if (file_printf(ms, ", from '%.80s'", nbuf + doff +
argoff) == -1)
return 1;
pidoff = argoff + 81 + 2;
if (doff + pidoff + 4 <= size) {
if (file_printf(ms, ", pid=%u",
elf_getu32(swap, *RCAST(uint32_t *, (nbuf +
doff + pidoff)))) == -1)
return 1;
}
*flags |= FLAGS_DID_CORE;
}
break;
default:
if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; cp < nbuf + size && *cp
&& isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return 1;
*flags |= FLAGS_DID_CORE;
return 1;
tryanother:
;
}
}
break;
}
#endif
return 0;
}
private off_t
get_offset_from_virtaddr(struct magic_set *ms, int swap, int clazz, int fd,
off_t off, int num, off_t fsize, uint64_t virtaddr)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
/*
* Loop through all the program headers and find the header with
* virtual address in which the "virtaddr" belongs to.
*/
for ( ; num; num--) {
if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) {
file_badread(ms);
return -1;
}
off += xph_sizeof;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Perhaps warn here */
continue;
}
if (virtaddr >= xph_vaddr && virtaddr < xph_vaddr + xph_filesz)
return xph_offset + (virtaddr - xph_vaddr);
}
return 0;
}
private size_t
get_string_on_virtaddr(struct magic_set *ms,
int swap, int clazz, int fd, off_t ph_off, int ph_num,
off_t fsize, uint64_t virtaddr, char *buf, ssize_t buflen)
{
char *bptr;
off_t offset;
if (buflen == 0)
return 0;
offset = get_offset_from_virtaddr(ms, swap, clazz, fd, ph_off, ph_num,
fsize, virtaddr);
if (offset < 0 ||
(buflen = pread(fd, buf, CAST(size_t, buflen), offset)) <= 0) {
file_badread(ms);
return 0;
}
buf[buflen - 1] = '\0';
/* We expect only printable characters, so return if buffer contains
* non-printable character before the '\0' or just '\0'. */
for (bptr = buf; *bptr && isprint((unsigned char)*bptr); bptr++)
continue;
if (*bptr != '\0')
return 0;
return bptr - buf;
}
/*ARGSUSED*/
private int
do_auxv_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,
int swap, uint32_t namesz __attribute__((__unused__)),
uint32_t descsz __attribute__((__unused__)),
size_t noff __attribute__((__unused__)), size_t doff,
int *flags, size_t size __attribute__((__unused__)), int clazz,
int fd, off_t ph_off, int ph_num, off_t fsize)
{
#ifdef ELFCORE
Aux32Info auxv32;
Aux64Info auxv64;
size_t elsize = xauxv_sizeof;
const char *tag;
int is_string;
size_t nval;
if ((*flags & (FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE)) !=
(FLAGS_IS_CORE|FLAGS_DID_CORE_STYLE))
return 0;
switch (*flags & FLAGS_CORE_STYLE) {
case OS_STYLE_SVR4:
if (type != NT_AUXV)
return 0;
break;
#ifdef notyet
case OS_STYLE_NETBSD:
if (type != NT_NETBSD_CORE_AUXV)
return 0;
break;
case OS_STYLE_FREEBSD:
if (type != NT_FREEBSD_PROCSTAT_AUXV)
return 0;
break;
#endif
default:
return 0;
}
*flags |= FLAGS_DID_AUXV;
nval = 0;
for (size_t off = 0; off + elsize <= descsz; off += elsize) {
memcpy(xauxv_addr, &nbuf[doff + off], xauxv_sizeof);
/* Limit processing to 50 vector entries to prevent DoS */
if (nval++ >= 50) {
file_error(ms, 0, "Too many ELF Auxv elements");
return 1;
}
switch(xauxv_type) {
case AT_LINUX_EXECFN:
is_string = 1;
tag = "execfn";
break;
case AT_LINUX_PLATFORM:
is_string = 1;
tag = "platform";
break;
case AT_LINUX_UID:
is_string = 0;
tag = "real uid";
break;
case AT_LINUX_GID:
is_string = 0;
tag = "real gid";
break;
case AT_LINUX_EUID:
is_string = 0;
tag = "effective uid";
break;
case AT_LINUX_EGID:
is_string = 0;
tag = "effective gid";
break;
default:
is_string = 0;
tag = NULL;
break;
}
if (tag == NULL)
continue;
if (is_string) {
char buf[256];
ssize_t buflen;
buflen = get_string_on_virtaddr(ms, swap, clazz, fd,
ph_off, ph_num, fsize, xauxv_val, buf, sizeof(buf));
if (buflen == 0)
continue;
if (file_printf(ms, ", %s: '%s'", tag, buf) == -1)
return 0;
} else {
if (file_printf(ms, ", %s: %d", tag, (int) xauxv_val)
== -1)
return 0;
}
}
return 1;
#else
return 0;
#endif
}
private size_t
dodynamic(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap)
{
Elf32_Dyn dh32;
Elf64_Dyn dh64;
unsigned char *dbuf = CAST(unsigned char *, vbuf);
if (xdh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xdh_sizeof + offset;
}
memcpy(xdh_addr, &dbuf[offset], xdh_sizeof);
offset += xdh_sizeof;
switch (xdh_tag) {
case DT_FLAGS_1:
if (xdh_val == DF_1_PIE)
ms->mode |= 0111;
else
ms->mode &= ~0111;
break;
default:
break;
}
return offset;
}
private size_t
donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags, uint16_t *notecount,
int fd, off_t ph_off, int ph_num, off_t fsize)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (*notecount == 0)
return 0;
--*notecount;
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
if (file_printf(ms, ", bad note name size %#lx",
CAST(unsigned long, namesz)) == -1)
return 0;
return 0;
}
if (descsz & 0x80000000) {
if (file_printf(ms, ", bad note description size %#lx",
CAST(unsigned long, descsz)) == -1)
return 0;
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & FLAGS_DID_OS_NOTE) == 0) {
if (do_os_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return offset;
}
if ((*flags & FLAGS_DID_BUILD_ID) == 0) {
if (do_bid_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return offset;
}
if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) {
if (do_pax_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags))
return offset;
}
if ((*flags & FLAGS_DID_CORE) == 0) {
if (do_core_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz))
return offset;
}
if ((*flags & FLAGS_DID_AUXV) == 0) {
if (do_auxv_note(ms, nbuf, xnh_type, swap,
namesz, descsz, noff, doff, flags, size, clazz,
fd, ph_off, ph_num, fsize))
return offset;
}
if (namesz == 7 && strcmp(RCAST(char *, &nbuf[noff]), "NetBSD") == 0) {
int descw, flag;
const char *str, *tag;
if (descsz > 100)
descsz = 100;
switch (xnh_type) {
case NT_NETBSD_VERSION:
return offset;
case NT_NETBSD_MARCH:
flag = FLAGS_DID_NETBSD_MARCH;
tag = "compiled for";
break;
case NT_NETBSD_CMODEL:
flag = FLAGS_DID_NETBSD_CMODEL;
tag = "compiler model";
break;
case NT_NETBSD_EMULATION:
flag = FLAGS_DID_NETBSD_EMULATION;
tag = "emulation:";
break;
default:
if (*flags & FLAGS_DID_NETBSD_UNKNOWN)
return offset;
*flags |= FLAGS_DID_NETBSD_UNKNOWN;
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return offset;
return offset;
}
if (*flags & flag)
return offset;
str = RCAST(const char *, &nbuf[doff]);
descw = CAST(int, descsz);
*flags |= flag;
file_printf(ms, ", %s: %.*s", tag, descw, str);
return offset;
}
return offset;
}
/* SunOS 5.x hardware capability descriptions */
typedef struct cap_desc {
uint64_t cd_mask;
const char *cd_name;
} cap_desc_t;
static const cap_desc_t cap_desc_sparc[] = {
{ AV_SPARC_MUL32, "MUL32" },
{ AV_SPARC_DIV32, "DIV32" },
{ AV_SPARC_FSMULD, "FSMULD" },
{ AV_SPARC_V8PLUS, "V8PLUS" },
{ AV_SPARC_POPC, "POPC" },
{ AV_SPARC_VIS, "VIS" },
{ AV_SPARC_VIS2, "VIS2" },
{ AV_SPARC_ASI_BLK_INIT, "ASI_BLK_INIT" },
{ AV_SPARC_FMAF, "FMAF" },
{ AV_SPARC_FJFMAU, "FJFMAU" },
{ AV_SPARC_IMA, "IMA" },
{ 0, NULL }
};
static const cap_desc_t cap_desc_386[] = {
{ AV_386_FPU, "FPU" },
{ AV_386_TSC, "TSC" },
{ AV_386_CX8, "CX8" },
{ AV_386_SEP, "SEP" },
{ AV_386_AMD_SYSC, "AMD_SYSC" },
{ AV_386_CMOV, "CMOV" },
{ AV_386_MMX, "MMX" },
{ AV_386_AMD_MMX, "AMD_MMX" },
{ AV_386_AMD_3DNow, "AMD_3DNow" },
{ AV_386_AMD_3DNowx, "AMD_3DNowx" },
{ AV_386_FXSR, "FXSR" },
{ AV_386_SSE, "SSE" },
{ AV_386_SSE2, "SSE2" },
{ AV_386_PAUSE, "PAUSE" },
{ AV_386_SSE3, "SSE3" },
{ AV_386_MON, "MON" },
{ AV_386_CX16, "CX16" },
{ AV_386_AHF, "AHF" },
{ AV_386_TSCP, "TSCP" },
{ AV_386_AMD_SSE4A, "AMD_SSE4A" },
{ AV_386_POPCNT, "POPCNT" },
{ AV_386_AMD_LZCNT, "AMD_LZCNT" },
{ AV_386_SSSE3, "SSSE3" },
{ AV_386_SSE4_1, "SSE4.1" },
{ AV_386_SSE4_2, "SSE4.2" },
{ 0, NULL }
};
private int
doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num,
size_t size, off_t fsize, int mach, int strtab, int *flags,
uint16_t *notecount)
{
Elf32_Shdr sh32;
Elf64_Shdr sh64;
int stripped = 1, has_debug_info = 0;
size_t nbadcap = 0;
void *nbuf;
off_t noff, coff, name_off;
uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */
uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */
char name[50];
ssize_t namesize;
if (num == 0) {
if (file_printf(ms, ", no section header") == -1)
return -1;
return 0;
}
if (size != xsh_sizeof) {
if (file_printf(ms, ", corrupted section header size") == -1)
return -1;
return 0;
}
/* Read offset of name section to be able to read section names later */
if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab)))
< CAST(ssize_t, xsh_sizeof)) {
if (file_printf(ms, ", missing section headers") == -1)
return -1;
return 0;
}
name_off = xsh_offset;
for ( ; num; num--) {
/* Read the name of this section. */
if ((namesize = pread(fd, name, sizeof(name) - 1,
name_off + xsh_name)) == -1) {
file_badread(ms);
return -1;
}
name[namesize] = '\0';
if (strcmp(name, ".debug_info") == 0) {
has_debug_info = 1;
stripped = 0;
}
if (pread(fd, xsh_addr, xsh_sizeof, off) <
CAST(ssize_t, xsh_sizeof)) {
file_badread(ms);
return -1;
}
off += size;
/* Things we can determine before we seek */
switch (xsh_type) {
case SHT_SYMTAB:
#if 0
case SHT_DYNSYM:
#endif
stripped = 0;
break;
default:
if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) {
/* Perhaps warn here */
continue;
}
break;
}
/* Things we can determine when we seek */
switch (xsh_type) {
case SHT_NOTE:
if (CAST(uintmax_t, (xsh_size + xsh_offset)) >
CAST(uintmax_t, fsize)) {
if (file_printf(ms,
", note offset/size %#" INTMAX_T_FORMAT
"x+%#" INTMAX_T_FORMAT "x exceeds"
" file size %#" INTMAX_T_FORMAT "x",
CAST(uintmax_t, xsh_offset),
CAST(uintmax_t, xsh_size),
CAST(uintmax_t, fsize)) == -1)
return -1;
return 0;
}
if ((nbuf = malloc(xsh_size)) == NULL) {
file_error(ms, errno, "Cannot allocate memory"
" for note");
return -1;
}
if (pread(fd, nbuf, xsh_size, xsh_offset) <
CAST(ssize_t, xsh_size)) {
file_badread(ms);
free(nbuf);
return -1;
}
noff = 0;
for (;;) {
if (noff >= CAST(off_t, xsh_size))
break;
noff = donote(ms, nbuf, CAST(size_t, noff),
xsh_size, clazz, swap, 4, flags, notecount,
fd, 0, 0, 0);
if (noff == 0)
break;
}
free(nbuf);
break;
case SHT_SUNW_cap:
switch (mach) {
case EM_SPARC:
case EM_SPARCV9:
case EM_IA_64:
case EM_386:
case EM_AMD64:
break;
default:
goto skip;
}
if (nbadcap > 5)
break;
if (lseek(fd, xsh_offset, SEEK_SET)
== CAST(off_t, -1)) {
file_badseek(ms);
return -1;
}
coff = 0;
for (;;) {
Elf32_Cap cap32;
Elf64_Cap cap64;
char cbuf[/*CONSTCOND*/
MAX(sizeof(cap32), sizeof(cap64))];
if ((coff += xcap_sizeof) >
CAST(off_t, xsh_size))
break;
if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) !=
CAST(ssize_t, xcap_sizeof)) {
file_badread(ms);
return -1;
}
if (cbuf[0] == 'A') {
#ifdef notyet
char *p = cbuf + 1;
uint32_t len, tag;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (memcmp("gnu", p, 3) != 0) {
if (file_printf(ms,
", unknown capability %.3s", p)
== -1)
return -1;
break;
}
p += strlen(p) + 1;
tag = *p++;
memcpy(&len, p, sizeof(len));
p += 4;
len = getu32(swap, len);
if (tag != 1) {
if (file_printf(ms, ", unknown gnu"
" capability tag %d", tag)
== -1)
return -1;
break;
}
// gnu attributes
#endif
break;
}
memcpy(xcap_addr, cbuf, xcap_sizeof);
switch (xcap_tag) {
case CA_SUNW_NULL:
break;
case CA_SUNW_HW_1:
cap_hw1 |= xcap_val;
break;
case CA_SUNW_SF_1:
cap_sf1 |= xcap_val;
break;
default:
if (file_printf(ms,
", with unknown capability "
"%#" INT64_T_FORMAT "x = %#"
INT64_T_FORMAT "x",
CAST(unsigned long long, xcap_tag),
CAST(unsigned long long, xcap_val))
== -1)
return -1;
if (nbadcap++ > 2)
coff = xsh_size;
break;
}
}
/*FALLTHROUGH*/
skip:
default:
break;
}
}
if (has_debug_info) {
if (file_printf(ms, ", with debug_info") == -1)
return -1;
}
if (file_printf(ms, ", %sstripped", stripped ? "" : "not ") == -1)
return -1;
if (cap_hw1) {
const cap_desc_t *cdp;
switch (mach) {
case EM_SPARC:
case EM_SPARC32PLUS:
case EM_SPARCV9:
cdp = cap_desc_sparc;
break;
case EM_386:
case EM_IA_64:
case EM_AMD64:
cdp = cap_desc_386;
break;
default:
cdp = NULL;
break;
}
if (file_printf(ms, ", uses") == -1)
return -1;
if (cdp) {
while (cdp->cd_name) {
if (cap_hw1 & cdp->cd_mask) {
if (file_printf(ms,
" %s", cdp->cd_name) == -1)
return -1;
cap_hw1 &= ~cdp->cd_mask;
}
++cdp;
}
if (cap_hw1)
if (file_printf(ms,
" unknown hardware capability %#"
INT64_T_FORMAT "x",
CAST(unsigned long long, cap_hw1)) == -1)
return -1;
} else {
if (file_printf(ms,
" hardware capability %#" INT64_T_FORMAT "x",
CAST(unsigned long long, cap_hw1)) == -1)
return -1;
}
}
if (cap_sf1) {
if (cap_sf1 & SF1_SUNW_FPUSED) {
if (file_printf(ms,
(cap_sf1 & SF1_SUNW_FPKNWN)
? ", uses frame pointer"
: ", not known to use frame pointer") == -1)
return -1;
}
cap_sf1 &= ~SF1_SUNW_MASK;
if (cap_sf1)
if (file_printf(ms,
", with unknown software capability %#"
INT64_T_FORMAT "x",
CAST(unsigned long long, cap_sf1)) == -1)
return -1;
}
return 0;
}
/*
* Look through the program headers of an executable image, searching
* for a PT_INTERP section; if one is found, it's dynamically linked,
* otherwise it's statically linked.
*/
private int
dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off,
int num, size_t size, off_t fsize, int sh_num, int *flags,
uint16_t *notecount)
{
Elf32_Phdr ph32;
Elf64_Phdr ph64;
const char *linking_style = "statically";
unsigned char nbuf[BUFSIZ];
char ibuf[BUFSIZ];
char interp[BUFSIZ];
ssize_t bufsize;
size_t offset, align, len;
if (num == 0) {
if (file_printf(ms, ", no program header") == -1)
return -1;
return 0;
}
if (size != xph_sizeof) {
if (file_printf(ms, ", corrupted program header size") == -1)
return -1;
return 0;
}
interp[0] = '\0';
for ( ; num; num--) {
int doread;
if (pread(fd, xph_addr, xph_sizeof, off) <
CAST(ssize_t, xph_sizeof)) {
file_badread(ms);
return -1;
}
off += size;
bufsize = 0;
align = 4;
/* Things we can determine before we seek */
switch (xph_type) {
case PT_DYNAMIC:
linking_style = "dynamically";
doread = 1;
break;
case PT_NOTE:
if (sh_num) /* Did this through section headers */
continue;
if (((align = xph_align) & 0x80000000UL) != 0 ||
align < 4) {
if (file_printf(ms,
", invalid note alignment %#lx",
CAST(unsigned long, align)) == -1)
return -1;
align = 4;
}
/*FALLTHROUGH*/
case PT_INTERP:
doread = 1;
break;
default:
doread = 0;
if (fsize != SIZE_UNKNOWN && xph_offset > fsize) {
/* Maybe warn here? */
continue;
}
break;
}
if (doread) {
len = xph_filesz < sizeof(nbuf) ? xph_filesz
: sizeof(nbuf);
bufsize = pread(fd, nbuf, len, xph_offset);
if (bufsize == -1) {
file_badread(ms);
return -1;
}
} else
len = 0;
/* Things we can determine when we seek */
switch (xph_type) {
case PT_DYNAMIC:
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = dodynamic(ms, nbuf, offset,
CAST(size_t, bufsize), clazz, swap);
if (offset == 0)
break;
}
break;
case PT_INTERP:
if (bufsize && nbuf[0]) {
nbuf[bufsize - 1] = '\0';
memcpy(interp, nbuf, (size_t)bufsize);
} else
strlcpy(interp, "*empty*", sizeof(interp));
break;
case PT_NOTE:
/*
* This is a PT_NOTE section; loop through all the notes
* in the section.
*/
offset = 0;
for (;;) {
if (offset >= (size_t)bufsize)
break;
offset = donote(ms, nbuf, offset,
CAST(size_t, bufsize), clazz, swap, align,
flags, notecount, fd, 0, 0, 0);
if (offset == 0)
break;
}
break;
default:
break;
}
}
if (file_printf(ms, ", %s linked", linking_style)
== -1)
return -1;
if (interp[0])
if (file_printf(ms, ", interpreter %s",
file_printable(ibuf, sizeof(ibuf), interp)) == -1)
return -1;
return 0;
}
protected int
file_tryelf(struct magic_set *ms, const struct buffer *b)
{
int fd = b->fd;
const unsigned char *buf = CAST(const unsigned char *, b->fbuf);
size_t nbytes = b->flen;
union {
int32_t l;
char c[sizeof(int32_t)];
} u;
int clazz;
int swap;
struct stat st;
off_t fsize;
int flags = 0;
Elf32_Ehdr elf32hdr;
Elf64_Ehdr elf64hdr;
uint16_t type, phnum, shnum, notecount;
if (ms->flags & (MAGIC_MIME|MAGIC_APPLE|MAGIC_EXTENSION))
return 0;
/*
* ELF executables have multiple section headers in arbitrary
* file locations and thus file(1) cannot determine it from easily.
* Instead we traverse thru all section headers until a symbol table
* one is found or else the binary is stripped.
* Return immediately if it's not ELF (so we avoid pipe2file unless
* needed).
*/
if (buf[EI_MAG0] != ELFMAG0
|| (buf[EI_MAG1] != ELFMAG1 && buf[EI_MAG1] != OLFMAG1)
|| buf[EI_MAG2] != ELFMAG2 || buf[EI_MAG3] != ELFMAG3)
return 0;
/*
* If we cannot seek, it must be a pipe, socket or fifo.
*/
if((lseek(fd, CAST(off_t, 0), SEEK_SET) == CAST(off_t, -1))
&& (errno == ESPIPE))
fd = file_pipe2file(ms, fd, buf, nbytes);
if (fd == -1 || fstat(fd, &st) == -1) {
file_badread(ms);
return -1;
}
if (S_ISREG(st.st_mode) || st.st_size != 0)
fsize = st.st_size;
else
fsize = SIZE_UNKNOWN;
clazz = buf[EI_CLASS];
switch (clazz) {
case ELFCLASS32:
#undef elf_getu
#define elf_getu(a, b) elf_getu32(a, b)
#undef elfhdr
#define elfhdr elf32hdr
#include "elfclass.h"
case ELFCLASS64:
#undef elf_getu
#define elf_getu(a, b) elf_getu64(a, b)
#undef elfhdr
#define elfhdr elf64hdr
#include "elfclass.h"
default:
if (file_printf(ms, ", unknown class %d", clazz) == -1)
return -1;
break;
}
return 0;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1423_0 |
crossvul-cpp_data_bad_3954_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Glyph Cache
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 <winpr/crt.h>
#include <freerdp/freerdp.h>
#include <winpr/stream.h>
#include <freerdp/log.h>
#include <freerdp/cache/glyph.h>
#include "glyph.h"
#define TAG FREERDP_TAG("cache.glyph")
static rdpGlyph* glyph_cache_get(rdpGlyphCache* glyph_cache, UINT32 id, UINT32 index);
static BOOL glyph_cache_put(rdpGlyphCache* glyph_cache, UINT32 id, UINT32 index, rdpGlyph* entry);
static const void* glyph_cache_fragment_get(rdpGlyphCache* glyph, UINT32 index, UINT32* count);
static BOOL glyph_cache_fragment_put(rdpGlyphCache* glyph, UINT32 index, UINT32 count,
const void* entry);
static UINT32 update_glyph_offset(const BYTE* data, size_t length, UINT32 index, INT32* x, INT32* y,
UINT32 ulCharInc, UINT32 flAccel)
{
if ((ulCharInc == 0) && (!(flAccel & SO_CHAR_INC_EQUAL_BM_BASE)))
{
UINT32 offset = data[index++];
if (offset & 0x80)
{
if (index + 1 < length)
{
offset = data[index++];
offset |= ((UINT32)data[index++]) << 8;
}
else
WLog_WARN(TAG, "[%s] glyph index out of bound %" PRIu32 " [max %" PRIuz "]", index,
length);
}
if (flAccel & SO_VERTICAL)
*y += offset;
if (flAccel & SO_HORIZONTAL)
*x += offset;
}
return index;
}
static BOOL update_process_glyph(rdpContext* context, const BYTE* data, UINT32 cacheIndex, INT32* x,
INT32* y, UINT32 cacheId, UINT32 flAccel, BOOL fOpRedundant,
const RDP_RECT* bound)
{
INT32 sx = 0, sy = 0;
INT32 dx, dy;
rdpGlyph* glyph;
rdpGlyphCache* glyph_cache;
if (!context || !data || !x || !y || !context->graphics || !context->cache ||
!context->cache->glyph)
return FALSE;
glyph_cache = context->cache->glyph;
glyph = glyph_cache_get(glyph_cache, cacheId, cacheIndex);
if (!glyph)
return FALSE;
dx = glyph->x + *x;
dy = glyph->y + *y;
if (dx < bound->x)
{
sx = bound->x - dx;
dx = bound->x;
}
if (dy < bound->y)
{
sy = bound->y - dy;
dy = bound->y;
}
if ((dx <= (bound->x + bound->width)) && (dy <= (bound->y + bound->height)))
{
INT32 dw = glyph->cx - sx;
INT32 dh = glyph->cy - sy;
if ((dw + dx) > (bound->x + bound->width))
dw = (bound->x + bound->width) - (dw + dx);
if ((dh + dy) > (bound->y + bound->height))
dh = (bound->y + bound->height) - (dh + dy);
if ((dh > 0) && (dw > 0))
{
if (!glyph->Draw(context, glyph, dx, dy, dw, dh, sx, sy, fOpRedundant))
return FALSE;
}
}
if (flAccel & SO_CHAR_INC_EQUAL_BM_BASE)
*x += glyph->cx;
return TRUE;
}
static BOOL update_process_glyph_fragments(rdpContext* context, const BYTE* data, UINT32 length,
UINT32 cacheId, UINT32 ulCharInc, UINT32 flAccel,
UINT32 bgcolor, UINT32 fgcolor, INT32 x, INT32 y,
INT32 bkX, INT32 bkY, INT32 bkWidth, INT32 bkHeight,
INT32 opX, INT32 opY, INT32 opWidth, INT32 opHeight,
BOOL fOpRedundant)
{
UINT32 n;
UINT32 id;
UINT32 size;
UINT32 index = 0;
BYTE* fragments;
rdpGraphics* graphics;
rdpGlyphCache* glyph_cache;
rdpGlyph* glyph;
RDP_RECT bound;
if (!context || !data || !context->graphics || !context->cache || !context->cache->glyph)
return FALSE;
graphics = context->graphics;
glyph_cache = context->cache->glyph;
glyph = graphics->Glyph_Prototype;
if (!glyph)
return FALSE;
/* Limit op rectangle to visible screen. */
if (opX < 0)
{
opWidth += opX;
opX = 0;
}
if (opY < 0)
{
opHeight += opY;
opY = 0;
}
if (opWidth < 0)
opWidth = 0;
if (opHeight < 0)
opHeight = 0;
/* Limit bk rectangle to visible screen. */
if (bkX < 0)
{
bkWidth += bkX;
bkX = 0;
}
if (bkY < 0)
{
bkHeight += bkY;
bkY = 0;
}
if (bkWidth < 0)
bkWidth = 0;
if (bkHeight < 0)
bkHeight = 0;
if (opX + opWidth > (INT64)context->settings->DesktopWidth)
{
/**
* Some Microsoft servers send erroneous high values close to the
* sint16 maximum in the OpRight field of the GlyphIndex, FastIndex and
* FastGlyph drawing orders, probably a result of applications trying to
* clear the text line to the very right end.
* One example where this can be seen is typing in notepad.exe within
* a RDP session to Windows XP Professional SP3.
* This workaround prevents resulting problems in the UI callbacks.
*/
opWidth = context->settings->DesktopWidth - opX;
}
if (bkX + bkWidth > (INT64)context->settings->DesktopWidth)
{
/**
* Some Microsoft servers send erroneous high values close to the
* sint16 maximum in the OpRight field of the GlyphIndex, FastIndex and
* FastGlyph drawing orders, probably a result of applications trying to
* clear the text line to the very right end.
* One example where this can be seen is typing in notepad.exe within
* a RDP session to Windows XP Professional SP3.
* This workaround prevents resulting problems in the UI callbacks.
*/
bkWidth = context->settings->DesktopWidth - bkX;
}
bound.x = bkX;
bound.y = bkY;
bound.width = bkWidth;
bound.height = bkHeight;
if (!glyph->BeginDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor, fOpRedundant))
return FALSE;
if (!IFCALLRESULT(TRUE, glyph->SetBounds, context, bkX, bkY, bkWidth, bkHeight))
return FALSE;
while (index < length)
{
const UINT32 op = data[index++];
switch (op)
{
case GLYPH_FRAGMENT_USE:
if (index + 1 >= length)
return FALSE;
id = data[index++];
fragments = (BYTE*)glyph_cache_fragment_get(glyph_cache, id, &size);
if (fragments == NULL)
return FALSE;
for (n = 0; n < size;)
{
const UINT32 fop = fragments[n++];
n = update_glyph_offset(fragments, size, n, &x, &y, ulCharInc, flAccel);
if (!update_process_glyph(context, fragments, fop, &x, &y, cacheId, flAccel,
fOpRedundant, &bound))
return FALSE;
}
break;
case GLYPH_FRAGMENT_ADD:
if (index + 2 > length)
return FALSE;
id = data[index++];
size = data[index++];
glyph_cache_fragment_put(glyph_cache, id, size, data);
break;
default:
index = update_glyph_offset(data, length, index, &x, &y, ulCharInc, flAccel);
if (!update_process_glyph(context, data, op, &x, &y, cacheId, flAccel, fOpRedundant,
&bound))
return FALSE;
break;
}
}
return glyph->EndDraw(context, opX, opY, opWidth, opHeight, bgcolor, fgcolor);
}
static BOOL update_gdi_glyph_index(rdpContext* context, GLYPH_INDEX_ORDER* glyphIndex)
{
INT32 bkWidth = 0, bkHeight = 0, opWidth = 0, opHeight = 0;
if (!context || !glyphIndex || !context->cache)
return FALSE;
if (glyphIndex->bkRight > glyphIndex->bkLeft)
bkWidth = glyphIndex->bkRight - glyphIndex->bkLeft + 1;
if (glyphIndex->opRight > glyphIndex->opLeft)
opWidth = glyphIndex->opRight - glyphIndex->opLeft + 1;
if (glyphIndex->bkBottom > glyphIndex->bkTop)
bkHeight = glyphIndex->bkBottom - glyphIndex->bkTop + 1;
if (glyphIndex->opBottom > glyphIndex->opTop)
opHeight = glyphIndex->opBottom - glyphIndex->opTop + 1;
return update_process_glyph_fragments(
context, glyphIndex->data, glyphIndex->cbData, glyphIndex->cacheId, glyphIndex->ulCharInc,
glyphIndex->flAccel, glyphIndex->backColor, glyphIndex->foreColor, glyphIndex->x,
glyphIndex->y, glyphIndex->bkLeft, glyphIndex->bkTop, bkWidth, bkHeight, glyphIndex->opLeft,
glyphIndex->opTop, opWidth, opHeight, glyphIndex->fOpRedundant);
}
static BOOL update_gdi_fast_index(rdpContext* context, const FAST_INDEX_ORDER* fastIndex)
{
INT32 x, y;
INT32 opLeft, opTop;
INT32 opRight, opBottom;
INT32 opWidth = 0, opHeight = 0;
INT32 bkWidth = 0, bkHeight = 0;
if (!context || !fastIndex || !context->cache)
return FALSE;
opLeft = fastIndex->opLeft;
opTop = fastIndex->opTop;
opRight = fastIndex->opRight;
opBottom = fastIndex->opBottom;
x = fastIndex->x;
y = fastIndex->y;
if (opBottom == -32768)
{
BYTE flags = (BYTE)(opTop & 0x0F);
if (flags & 0x01)
opBottom = fastIndex->bkBottom;
if (flags & 0x02)
opRight = fastIndex->bkRight;
if (flags & 0x04)
opTop = fastIndex->bkTop;
if (flags & 0x08)
opLeft = fastIndex->bkLeft;
}
if (opLeft == 0)
opLeft = fastIndex->bkLeft;
if (opRight == 0)
opRight = fastIndex->bkRight;
/* Server can send a massive number (32766) which appears to be
* undocumented special behavior for "Erase all the way right".
* X11 has nondeterministic results asking for a draw that wide. */
if (opRight > (INT64)context->instance->settings->DesktopWidth)
opRight = (int)context->instance->settings->DesktopWidth;
if (x == -32768)
x = fastIndex->bkLeft;
if (y == -32768)
y = fastIndex->bkTop;
if (fastIndex->bkRight > fastIndex->bkLeft)
bkWidth = fastIndex->bkRight - fastIndex->bkLeft + 1;
if (fastIndex->bkBottom > fastIndex->bkTop)
bkHeight = fastIndex->bkBottom - fastIndex->bkTop + 1;
if (opRight > opLeft)
opWidth = opRight - opLeft + 1;
if (opBottom > opTop)
opHeight = opBottom - opTop + 1;
return update_process_glyph_fragments(
context, fastIndex->data, fastIndex->cbData, fastIndex->cacheId, fastIndex->ulCharInc,
fastIndex->flAccel, fastIndex->backColor, fastIndex->foreColor, x, y, fastIndex->bkLeft,
fastIndex->bkTop, bkWidth, bkHeight, opLeft, opTop, opWidth, opHeight, FALSE);
}
static BOOL update_gdi_fast_glyph(rdpContext* context, const FAST_GLYPH_ORDER* fastGlyph)
{
INT32 x, y;
BYTE text_data[4] = { 0 };
INT32 opLeft, opTop;
INT32 opRight, opBottom;
INT32 opWidth = 0, opHeight = 0;
INT32 bkWidth = 0, bkHeight = 0;
rdpCache* cache;
if (!context || !fastGlyph || !context->cache)
return FALSE;
cache = context->cache;
opLeft = fastGlyph->opLeft;
opTop = fastGlyph->opTop;
opRight = fastGlyph->opRight;
opBottom = fastGlyph->opBottom;
x = fastGlyph->x;
y = fastGlyph->y;
if (opBottom == -32768)
{
BYTE flags = (BYTE)(opTop & 0x0F);
if (flags & 0x01)
opBottom = fastGlyph->bkBottom;
if (flags & 0x02)
opRight = fastGlyph->bkRight;
if (flags & 0x04)
opTop = fastGlyph->bkTop;
if (flags & 0x08)
opLeft = fastGlyph->bkLeft;
}
if (opLeft == 0)
opLeft = fastGlyph->bkLeft;
if (opRight == 0)
opRight = fastGlyph->bkRight;
/* See update_gdi_fast_index opRight comment. */
if (opRight > (INT64)context->instance->settings->DesktopWidth)
opRight = (int)context->instance->settings->DesktopWidth;
if (x == -32768)
x = fastGlyph->bkLeft;
if (y == -32768)
y = fastGlyph->bkTop;
if ((fastGlyph->cbData > 1) && (fastGlyph->glyphData.aj))
{
/* got option font that needs to go into cache */
rdpGlyph* glyph;
const GLYPH_DATA_V2* glyphData = &fastGlyph->glyphData;
glyph = Glyph_Alloc(context, glyphData->x, glyphData->y, glyphData->cx, glyphData->cy,
glyphData->cb, glyphData->aj);
if (!glyph)
return FALSE;
if (!glyph_cache_put(cache->glyph, fastGlyph->cacheId, fastGlyph->data[0], glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
text_data[0] = fastGlyph->data[0];
text_data[1] = 0;
if (fastGlyph->bkRight > fastGlyph->bkLeft)
bkWidth = fastGlyph->bkRight - fastGlyph->bkLeft + 1;
if (fastGlyph->bkBottom > fastGlyph->bkTop)
bkHeight = fastGlyph->bkBottom - fastGlyph->bkTop + 1;
if (opRight > opLeft)
opWidth = opRight - opLeft + 1;
if (opBottom > opTop)
opHeight = opBottom - opTop + 1;
return update_process_glyph_fragments(
context, text_data, sizeof(text_data), fastGlyph->cacheId, fastGlyph->ulCharInc,
fastGlyph->flAccel, fastGlyph->backColor, fastGlyph->foreColor, x, y, fastGlyph->bkLeft,
fastGlyph->bkTop, bkWidth, bkHeight, opLeft, opTop, opWidth, opHeight, FALSE);
}
static BOOL update_gdi_cache_glyph(rdpContext* context, const CACHE_GLYPH_ORDER* cacheGlyph)
{
UINT32 i;
rdpCache* cache;
if (!context || !cacheGlyph || !context->cache)
return FALSE;
cache = context->cache;
for (i = 0; i < cacheGlyph->cGlyphs; i++)
{
const GLYPH_DATA* glyph_data = &cacheGlyph->glyphData[i];
rdpGlyph* glyph;
if (!glyph_data)
return FALSE;
if (!(glyph = Glyph_Alloc(context, glyph_data->x, glyph_data->y, glyph_data->cx,
glyph_data->cy, glyph_data->cb, glyph_data->aj)))
return FALSE;
if (!glyph_cache_put(cache->glyph, cacheGlyph->cacheId, glyph_data->cacheIndex, glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
return TRUE;
}
static BOOL update_gdi_cache_glyph_v2(rdpContext* context, const CACHE_GLYPH_V2_ORDER* cacheGlyphV2)
{
UINT32 i;
rdpCache* cache;
if (!context || !cacheGlyphV2 || !context->cache)
return FALSE;
cache = context->cache;
for (i = 0; i < cacheGlyphV2->cGlyphs; i++)
{
const GLYPH_DATA_V2* glyphData = &cacheGlyphV2->glyphData[i];
rdpGlyph* glyph;
if (!glyphData)
return FALSE;
glyph = Glyph_Alloc(context, glyphData->x, glyphData->y, glyphData->cx, glyphData->cy,
glyphData->cb, glyphData->aj);
if (!glyph)
return FALSE;
if (!glyph_cache_put(cache->glyph, cacheGlyphV2->cacheId, glyphData->cacheIndex, glyph))
{
glyph->Free(context, glyph);
return FALSE;
}
}
return TRUE;
}
rdpGlyph* glyph_cache_get(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index)
{
rdpGlyph* glyph;
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCacheGet: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return NULL;
}
if (index > glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "index %" PRIu32 " out of range for cache id: %" PRIu32 "", index, id);
return NULL;
}
glyph = glyphCache->glyphCache[id].entries[index];
if (!glyph)
WLog_ERR(TAG, "no glyph found at cache index: %" PRIu32 " in cache id: %" PRIu32 "", index,
id);
return glyph;
}
BOOL glyph_cache_put(rdpGlyphCache* glyphCache, UINT32 id, UINT32 index, rdpGlyph* glyph)
{
rdpGlyph* prevGlyph;
if (id > 9)
{
WLog_ERR(TAG, "invalid glyph cache id: %" PRIu32 "", id);
return FALSE;
}
if (index > glyphCache->glyphCache[id].number)
{
WLog_ERR(TAG, "invalid glyph cache index: %" PRIu32 " in cache id: %" PRIu32 "", index, id);
return FALSE;
}
WLog_Print(glyphCache->log, WLOG_DEBUG, "GlyphCachePut: id: %" PRIu32 " index: %" PRIu32 "", id,
index);
prevGlyph = glyphCache->glyphCache[id].entries[index];
if (prevGlyph)
prevGlyph->Free(glyphCache->context, prevGlyph);
glyphCache->glyphCache[id].entries[index] = glyph;
return TRUE;
}
const void* glyph_cache_fragment_get(rdpGlyphCache* glyphCache, UINT32 index, UINT32* size)
{
void* fragment;
if (index > 255)
{
WLog_ERR(TAG, "invalid glyph cache fragment index: %" PRIu32 "", index);
return NULL;
}
fragment = glyphCache->fragCache.entries[index].fragment;
*size = (BYTE)glyphCache->fragCache.entries[index].size;
WLog_Print(glyphCache->log, WLOG_DEBUG,
"GlyphCacheFragmentGet: index: %" PRIu32 " size: %" PRIu32 "", index, *size);
if (!fragment)
WLog_ERR(TAG, "invalid glyph fragment at index:%" PRIu32 "", index);
return fragment;
}
BOOL glyph_cache_fragment_put(rdpGlyphCache* glyphCache, UINT32 index, UINT32 size,
const void* fragment)
{
void* prevFragment;
void* copy;
if (index > 255)
{
WLog_ERR(TAG, "invalid glyph cache fragment index: %" PRIu32 "", index);
return FALSE;
}
copy = malloc(size);
if (!copy)
return FALSE;
WLog_Print(glyphCache->log, WLOG_DEBUG,
"GlyphCacheFragmentPut: index: %" PRIu32 " size: %" PRIu32 "", index, size);
CopyMemory(copy, fragment, size);
prevFragment = glyphCache->fragCache.entries[index].fragment;
glyphCache->fragCache.entries[index].fragment = copy;
glyphCache->fragCache.entries[index].size = size;
free(prevFragment);
return TRUE;
}
void glyph_cache_register_callbacks(rdpUpdate* update)
{
update->primary->GlyphIndex = update_gdi_glyph_index;
update->primary->FastIndex = update_gdi_fast_index;
update->primary->FastGlyph = update_gdi_fast_glyph;
update->secondary->CacheGlyph = update_gdi_cache_glyph;
update->secondary->CacheGlyphV2 = update_gdi_cache_glyph_v2;
}
rdpGlyphCache* glyph_cache_new(rdpSettings* settings)
{
int i;
rdpGlyphCache* glyphCache;
glyphCache = (rdpGlyphCache*)calloc(1, sizeof(rdpGlyphCache));
if (!glyphCache)
return NULL;
glyphCache->log = WLog_Get("com.freerdp.cache.glyph");
glyphCache->settings = settings;
glyphCache->context = ((freerdp*)settings->instance)->update->context;
for (i = 0; i < 10; i++)
{
glyphCache->glyphCache[i].number = settings->GlyphCache[i].cacheEntries;
glyphCache->glyphCache[i].maxCellSize = settings->GlyphCache[i].cacheMaximumCellSize;
glyphCache->glyphCache[i].entries =
(rdpGlyph**)calloc(glyphCache->glyphCache[i].number, sizeof(rdpGlyph*));
if (!glyphCache->glyphCache[i].entries)
goto fail;
}
glyphCache->fragCache.entries = calloc(256, sizeof(FRAGMENT_CACHE_ENTRY));
if (!glyphCache->fragCache.entries)
goto fail;
return glyphCache;
fail:
glyph_cache_free(glyphCache);
return NULL;
}
void glyph_cache_free(rdpGlyphCache* glyphCache)
{
if (glyphCache)
{
int i;
GLYPH_CACHE* cache = glyphCache->glyphCache;
for (i = 0; i < 10; i++)
{
UINT32 j;
rdpGlyph** entries = cache[i].entries;
if (!entries)
continue;
for (j = 0; j < cache[i].number; j++)
{
rdpGlyph* glyph = entries[j];
if (glyph)
{
glyph->Free(glyphCache->context, glyph);
entries[j] = NULL;
}
}
free(entries);
cache[i].entries = NULL;
}
if (glyphCache->fragCache.entries)
{
for (i = 0; i < 256; i++)
{
free(glyphCache->fragCache.entries[i].fragment);
glyphCache->fragCache.entries[i].fragment = NULL;
}
}
free(glyphCache->fragCache.entries);
free(glyphCache);
}
}
CACHE_GLYPH_ORDER* copy_cache_glyph_order(rdpContext* context, const CACHE_GLYPH_ORDER* glyph)
{
size_t x;
CACHE_GLYPH_ORDER* dst = calloc(1, sizeof(CACHE_GLYPH_ORDER));
if (!dst || !glyph)
goto fail;
*dst = *glyph;
for (x = 0; x < glyph->cGlyphs; x++)
{
const GLYPH_DATA* src = &glyph->glyphData[x];
GLYPH_DATA* data = &dst->glyphData[x];
if (src->aj)
{
const size_t size = src->cb;
data->aj = malloc(size);
if (!data->aj)
goto fail;
memcpy(data->aj, src->aj, size);
}
}
if (glyph->unicodeCharacters)
{
if (glyph->cGlyphs == 0)
goto fail;
dst->unicodeCharacters = calloc(glyph->cGlyphs, sizeof(WCHAR));
if (!dst->unicodeCharacters)
goto fail;
memcpy(dst->unicodeCharacters, glyph->unicodeCharacters, sizeof(WCHAR) * glyph->cGlyphs);
}
return dst;
fail:
free_cache_glyph_order(context, dst);
return NULL;
}
void free_cache_glyph_order(rdpContext* context, CACHE_GLYPH_ORDER* glyph)
{
if (glyph)
{
size_t x;
for (x = 0; x < ARRAYSIZE(glyph->glyphData); x++)
free(glyph->glyphData[x].aj);
free(glyph->unicodeCharacters);
}
free(glyph);
}
CACHE_GLYPH_V2_ORDER* copy_cache_glyph_v2_order(rdpContext* context,
const CACHE_GLYPH_V2_ORDER* glyph)
{
size_t x;
CACHE_GLYPH_V2_ORDER* dst = calloc(1, sizeof(CACHE_GLYPH_V2_ORDER));
if (!dst || !glyph)
goto fail;
*dst = *glyph;
for (x = 0; x < glyph->cGlyphs; x++)
{
const GLYPH_DATA_V2* src = &glyph->glyphData[x];
GLYPH_DATA_V2* data = &dst->glyphData[x];
if (src->aj)
{
const size_t size = src->cb;
data->aj = malloc(size);
if (!data->aj)
goto fail;
memcpy(data->aj, src->aj, size);
}
}
if (glyph->unicodeCharacters)
{
if (glyph->cGlyphs == 0)
goto fail;
dst->unicodeCharacters = calloc(glyph->cGlyphs, sizeof(WCHAR));
if (!dst->unicodeCharacters)
goto fail;
memcpy(dst->unicodeCharacters, glyph->unicodeCharacters, sizeof(WCHAR) * glyph->cGlyphs);
}
return dst;
fail:
free_cache_glyph_v2_order(context, dst);
return NULL;
}
void free_cache_glyph_v2_order(rdpContext* context, CACHE_GLYPH_V2_ORDER* glyph)
{
if (glyph)
{
size_t x;
for (x = 0; x < ARRAYSIZE(glyph->glyphData); x++)
free(glyph->glyphData[x].aj);
free(glyph->unicodeCharacters);
}
free(glyph);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3954_0 |
crossvul-cpp_data_good_1019_0 | /*! @file GPMF_parser.c
*
* @brief GPMF Parser library
*
* @version 1.2.2
*
* (C) Copyright 2017 GoPro Inc (http://gopro.com/).
*
* Licensed under either:
* - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0
* - MIT license, http://opensource.org/licenses/MIT
* at your option.
*
* 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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "GPMF_parser.h"
#ifdef DBG
#if _WINDOWS
#define DBG_MSG printf
#else
#define DBG_MSG(...)
#endif
#else
#define DBG_MSG(...)
#endif
GPMF_ERR IsValidSize(GPMF_stream *ms, uint32_t size) // size is in longs not bytes.
{
if (ms)
{
uint32_t nestsize = (uint32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
if (size + 2 <= nestsize) return GPMF_OK;
}
return GPMF_ERROR_BAD_STRUCTURE;
}
GPMF_ERR GPMF_Validate(GPMF_stream *ms, GPMF_LEVELS recurse)
{
if (ms)
{
uint32_t currpos = ms->pos;
int32_t nestsize = (int32_t)ms->nest_size[ms->nest_level];
if (nestsize == 0 && ms->nest_level == 0)
nestsize = ms->buffer_size_longs;
while (ms->pos+1 < ms->buffer_size_longs && nestsize > 0)
{
uint32_t key = ms->buffer[ms->pos];
if (ms->nest_level == 0 && key != GPMF_KEY_DEVICE && ms->device_count == 0 && ms->pos == 0)
{
DBG_MSG("ERROR: uninitized -- GPMF_ERROR_BAD_STRUCTURE\n");
return GPMF_ERROR_BAD_STRUCTURE;
}
if (GPMF_VALID_FOURCC(key))
{
uint32_t type_size_repeat = ms->buffer[ms->pos + 1];
int32_t size = GPMF_DATA_SIZE(type_size_repeat) >> 2;
uint8_t type = GPMF_SAMPLE_TYPE(type_size_repeat);
if (size + 2 > nestsize)
{
DBG_MSG("ERROR: nest size too small within %c%c%c%c-- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key));
return GPMF_ERROR_BAD_STRUCTURE;
}
if (!GPMF_VALID_FOURCC(key))
{
DBG_MSG("ERROR: invalid 4CC -- GPMF_ERROR_BAD_STRUCTURE\n");
return GPMF_ERROR_BAD_STRUCTURE;
}
if (type == GPMF_TYPE_NEST && recurse == GPMF_RECURSE_LEVELS)
{
uint32_t validnest;
ms->pos += 2;
ms->nest_level++;
if (ms->nest_level > GPMF_NEST_LIMIT)
{
DBG_MSG("ERROR: nest level within %c%c%c%c too deep -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key));
return GPMF_ERROR_BAD_STRUCTURE;
}
ms->nest_size[ms->nest_level] = size;
validnest = GPMF_Validate(ms, recurse);
ms->nest_level--;
if (GPMF_OK != validnest)
{
DBG_MSG("ERROR: invalid nest within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key));
return GPMF_ERROR_BAD_STRUCTURE;
}
else
{
if (ms->nest_level == 0)
ms->device_count++;
}
ms->pos += size;
nestsize -= 2 + size;
while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)
{
ms->pos++;
nestsize--;
}
}
else
{
ms->pos += 2 + size;
nestsize -= 2 + size;
}
if (ms->pos == ms->buffer_size_longs)
{
ms->pos = currpos;
return GPMF_OK;
}
}
else
{
if (key == GPMF_KEY_END)
{
do
{
ms->pos++;
nestsize--;
} while (ms->pos < ms->buffer_size_longs && nestsize > 0 && ms->buffer[ms->pos] == 0);
}
else if (ms->nest_level == 0 && ms->device_count > 0)
{
ms->pos = currpos;
return GPMF_OK;
}
else
{
DBG_MSG("ERROR: bad struct within %c%c%c%c -- GPMF_ERROR_BAD_STRUCTURE\n", PRINTF_4CC(key));
return GPMF_ERROR_BAD_STRUCTURE;
}
}
}
ms->pos = currpos;
return GPMF_OK;
}
else
{
DBG_MSG("ERROR: Invalid handle -- GPMF_ERROR_MEMORY\n");
return GPMF_ERROR_MEMORY;
}
}
GPMF_ERR GPMF_ResetState(GPMF_stream *ms)
{
if (ms)
{
ms->pos = 0;
ms->nest_level = 0;
ms->device_count = 0;
ms->nest_size[ms->nest_level] = 0;
ms->last_level_pos[ms->nest_level] = 0;
ms->last_seek[ms->nest_level] = 0;
ms->device_id = 0;
ms->device_name[0] = 0;
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
GPMF_ERR GPMF_Init(GPMF_stream *ms, uint32_t *buffer, int datasize)
{
if(ms)
{
ms->buffer = buffer;
ms->buffer_size_longs = datasize >>2;
GPMF_ResetState(ms);
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
GPMF_ERR GPMF_CopyState(GPMF_stream *msrc, GPMF_stream *mdst)
{
if (msrc && mdst)
{
memcpy(mdst, msrc, sizeof(GPMF_stream));
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
GPMF_ERR GPMF_Next(GPMF_stream *ms, GPMF_LEVELS recurse)
{
if (ms)
{
if (ms->pos+1 < ms->buffer_size_longs)
{
uint32_t key, type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);
if (GPMF_OK != IsValidSize(ms, size)) return GPMF_ERROR_BAD_STRUCTURE;
if (GPMF_TYPE_NEST == type && GPMF_KEY_DEVICE == ms->buffer[ms->pos] && ms->nest_level == 0)
{
ms->last_level_pos[ms->nest_level] = ms->pos;
ms->nest_size[ms->nest_level] = size;
if (recurse)
ms->pos += 2;
else
ms->pos += 2 + size;
}
else
{
if (size + 2 > ms->nest_size[ms->nest_level])
return GPMF_ERROR_BAD_STRUCTURE;
if (recurse && type == GPMF_TYPE_NEST)
{
ms->last_level_pos[ms->nest_level] = ms->pos;
ms->pos += 2;
ms->nest_size[ms->nest_level] -= size + 2;
ms->nest_level++;
if (ms->nest_level > GPMF_NEST_LIMIT)
return GPMF_ERROR_BAD_STRUCTURE;
ms->nest_size[ms->nest_level] = size;
}
else
{
if (recurse)
{
ms->pos += size + 2;
ms->nest_size[ms->nest_level] -= size + 2;
}
else
{
if (ms->nest_size[ms->nest_level] - (size + 2) > 0)
{
ms->pos += size + 2;
ms->nest_size[ms->nest_level] -= size + 2;
}
else
{
return GPMF_ERROR_LAST;
}
}
}
}
while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)
{
ms->pos++;
ms->nest_size[ms->nest_level]--;
}
while (ms->nest_level > 0 && ms->nest_size[ms->nest_level] == 0)
{
ms->nest_level--;
//if (ms->nest_level == 0)
//{
// ms->device_count++;
//}
}
if (ms->pos < ms->buffer_size_longs)
{
while (ms->pos < ms->buffer_size_longs && ms->nest_size[ms->nest_level] > 0 && ms->buffer[ms->pos] == GPMF_KEY_END)
{
ms->pos++;
ms->nest_size[ms->nest_level]--;
}
key = ms->buffer[ms->pos];
if (!GPMF_VALID_FOURCC(key))
return GPMF_ERROR_BAD_STRUCTURE;
if (key == GPMF_KEY_DEVICE_ID)
ms->device_id = BYTESWAP32(ms->buffer[ms->pos + 2]);
if (key == GPMF_KEY_DEVICE_NAME)
{
size = GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]); // in bytes
if (size > sizeof(ms->device_name) - 1)
size = sizeof(ms->device_name) - 1;
memcpy(ms->device_name, &ms->buffer[ms->pos + 2], size);
ms->device_name[size] = 0;
}
}
else
{
// end of buffer
return GPMF_ERROR_BUFFER_END;
}
return GPMF_OK;
}
else
{
// end of buffer
return GPMF_ERROR_BUFFER_END;
}
}
return GPMF_ERROR_MEMORY;
}
GPMF_ERR GPMF_FindNext(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)
{
GPMF_stream prevstate;
if (ms)
{
memcpy(&prevstate, ms, sizeof(GPMF_stream));
if (ms->pos < ms->buffer_size_longs)
{
while (0 == GPMF_Next(ms, recurse))
{
if (ms->buffer[ms->pos] == fourcc)
{
return GPMF_OK; //found match
}
}
// restore read position
memcpy(ms, &prevstate, sizeof(GPMF_stream));
return GPMF_ERROR_FIND;
}
}
return GPMF_ERROR_FIND;
}
GPMF_ERR GPMF_Reserved(uint32_t key)
{
if(key == GPMF_KEY_DEVICE)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_DEVICE_ID)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_DEVICE_NAME)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_STREAM)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_STREAM_NAME)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_SI_UNITS)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_UNITS)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_SCALE)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_TYPE)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_TOTAL_SAMPLES)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_TICK)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_TOCK)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_EMPTY_PAYLOADS)
return GPMF_ERROR_RESERVED;
if(key == GPMF_KEY_REMARK)
return GPMF_ERROR_RESERVED;
return GPMF_OK;
}
uint32_t GPMF_PayloadSampleCount(GPMF_stream *ms)
{
uint32_t count = 0;
if (ms)
{
uint32_t fourcc = GPMF_Key(ms);
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats
{
count=2;
while (GPMF_OK == GPMF_FindNext(&find_stream, fourcc, GPMF_CURRENT_LEVEL))
{
count++;
}
}
else
{
count = GPMF_Repeat(ms);
}
}
return count;
}
GPMF_ERR GPMF_SeekToSamples(GPMF_stream *ms)
{
GPMF_stream prevstate;
if (ms)
{
if (ms->pos+1 < ms->buffer_size_longs)
{
uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
memcpy(&prevstate, ms, sizeof(GPMF_stream));
if (type == GPMF_TYPE_NEST)
GPMF_Next(ms, GPMF_RECURSE_LEVELS); // open STRM and recurse in
while (0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL))
{
uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);
if (GPMF_OK != IsValidSize(ms, size))
{
memcpy(ms, &prevstate, sizeof(GPMF_stream));
return GPMF_ERROR_BAD_STRUCTURE;
}
type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
if (type == GPMF_TYPE_NEST) // Nest with-in nest
{
return GPMF_OK; //found match
}
if (size + 2 == ms->nest_size[ms->nest_level])
{
uint32_t key = GPMF_Key(ms);
if (GPMF_ERROR_RESERVED == GPMF_Reserved(key))
return GPMF_ERROR_FIND;
return GPMF_OK; //found match
}
if (ms->buffer[ms->pos] == ms->buffer[ms->pos + size + 2]) // Matching tags
{
return GPMF_OK; //found match
}
}
// restore read position
memcpy(ms, &prevstate, sizeof(GPMF_stream));
return GPMF_ERROR_FIND;
}
}
return GPMF_ERROR_FIND;
}
GPMF_ERR GPMF_FindPrev(GPMF_stream *ms, uint32_t fourcc, GPMF_LEVELS recurse)
{
GPMF_stream prevstate;
if (ms)
{
uint32_t curr_level = ms->nest_level;
memcpy(&prevstate, ms, sizeof(GPMF_stream));
if (ms->pos < ms->buffer_size_longs && curr_level > 0)
{
do
{
ms->last_seek[curr_level] = ms->pos;
ms->pos = ms->last_level_pos[curr_level - 1] + 2;
ms->nest_size[curr_level] += ms->last_seek[curr_level] - ms->pos;
do
{
if (ms->last_seek[curr_level] > ms->pos && ms->buffer[ms->pos] == fourcc)
{
return GPMF_OK; //found match
}
} while (ms->last_seek[curr_level] > ms->pos && 0 == GPMF_Next(ms, GPMF_CURRENT_LEVEL));
curr_level--;
} while (recurse == GPMF_RECURSE_LEVELS && curr_level > 0);
// restore read position
memcpy(ms, &prevstate, sizeof(GPMF_stream));
return GPMF_ERROR_FIND;
}
}
return GPMF_ERROR_FIND;
}
uint32_t GPMF_Key(GPMF_stream *ms)
{
if (ms)
{
uint32_t key = ms->buffer[ms->pos];
return key;
}
return 0;
}
uint32_t GPMF_Type(GPMF_stream *ms)
{
if (ms && ms->pos+1 < ms->buffer_size_longs)
{
uint32_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos+1]);
return type;
}
return 0;
}
uint32_t GPMF_StructSize(GPMF_stream *ms)
{
if (ms && ms->pos+1 < ms->buffer_size_longs)
{
uint32_t ssize = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);
uint32_t size = (GPMF_DATA_SIZE(ms->buffer[ms->pos + 1]) >> 2);
if (GPMF_OK != IsValidSize(ms, size)) return 0; // as the structure is corrupted. i.e. GPMF_ERROR_BAD_STRUCTURE;
return ssize;
}
return 0;
}
uint32_t GPMF_ElementsInStruct(GPMF_stream *ms)
{
if (ms && ms->pos+1 < ms->buffer_size_longs)
{
uint32_t ssize = GPMF_StructSize(ms);
GPMF_SampleType type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
if (type != GPMF_TYPE_NEST && type != GPMF_TYPE_COMPLEX)
{
int32_t tsize = GPMF_SizeofType(type);
if (tsize > 0)
return ssize / tsize;
else
return 0;
}
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_CURRENT_LEVEL))
{
char tmp[64] = "";
uint32_t tmpsize = sizeof(tmp);
char *data = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
if (GPMF_OK == GPMF_ExpandComplexTYPE(data, size, tmp, &tmpsize))
return tmpsize;
}
}
}
return 0;
}
uint32_t GPMF_Repeat(GPMF_stream *ms)
{
if (ms && ms->pos+1 < ms->buffer_size_longs)
{
uint32_t repeat = GPMF_SAMPLES(ms->buffer[ms->pos + 1]);
return repeat;
}
return 0;
}
uint32_t GPMF_RawDataSize(GPMF_stream *ms)
{
if (ms && ms->pos+1 < ms->buffer_size_longs)
{
uint32_t size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);
if (GPMF_OK != IsValidSize(ms, size >> 2)) return 0;
return size;
}
return 0;
}
uint32_t GPMF_NestLevel(GPMF_stream *ms)
{
if (ms)
{
return ms->nest_level;
}
return 0;
}
uint32_t GPMF_DeviceID(GPMF_stream *ms)
{
if (ms)
{
return ms->device_id;
}
return 0;
}
GPMF_ERR GPMF_DeviceName(GPMF_stream *ms, char *devicenamebuf, uint32_t devicename_buf_size)
{
if (ms && devicenamebuf)
{
uint32_t len = (uint32_t)strlen(ms->device_name);
if (len >= devicename_buf_size)
return GPMF_ERROR_MEMORY;
memcpy(devicenamebuf, ms->device_name, len);
devicenamebuf[len] = 0;
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
void *GPMF_RawData(GPMF_stream *ms)
{
if (ms)
{
return (void *)&ms->buffer[ms->pos + 2];
}
return NULL;
}
uint32_t GPMF_SizeofType(GPMF_SampleType type)
{
uint32_t ssize = 0;
switch ((int)type)
{
case GPMF_TYPE_STRING_ASCII: ssize = 1; break;
case GPMF_TYPE_SIGNED_BYTE: ssize = 1; break;
case GPMF_TYPE_UNSIGNED_BYTE: ssize = 1; break;
// These datatypes are always be stored in Big-Endian
case GPMF_TYPE_SIGNED_SHORT: ssize = 2; break;
case GPMF_TYPE_UNSIGNED_SHORT: ssize = 2; break;
case GPMF_TYPE_FLOAT: ssize = 4; break;
case GPMF_TYPE_FOURCC: ssize = 4; break;
case GPMF_TYPE_SIGNED_LONG: ssize = 4; break;
case GPMF_TYPE_UNSIGNED_LONG: ssize = 4; break;
case GPMF_TYPE_Q15_16_FIXED_POINT: ssize = 4; break;
case GPMF_TYPE_Q31_32_FIXED_POINT: ssize = 8; break;
case GPMF_TYPE_DOUBLE: ssize = 8; break;
case GPMF_TYPE_SIGNED_64BIT_INT: ssize = 8; break;
case GPMF_TYPE_UNSIGNED_64BIT_INT: ssize = 8; break;
//All unknown or larger than 8-bytes stored as is:
case GPMF_TYPE_GUID: ssize = 16; break;
case GPMF_TYPE_UTC_DATE_TIME: ssize = 16; break;
}
return ssize;
}
uint32_t GPMF_ExpandComplexTYPE(char *src, uint32_t srcsize, char *dst, uint32_t *dstsize)
{
uint32_t i = 0, k = 0, count = 0;
while (i<srcsize && k<*dstsize)
{
if (src[i] == '[' && i>0)
{
int j = 1;
count = 0;
while (src[i + j] >= '0' && src[i + j] <= '9')
{
count *= 10;
count += src[i + j] - '0';
j++;
}
if (count > 1)
{
uint32_t l;
for (l = 1; l<count; l++)
{
dst[k] = src[i - 1];
k++;
}
}
i += j;
if (src[i] == ']') i++;
}
else
{
dst[k] = src[i];
if (dst[k] == 0) break;
i++, k++;
}
}
if (k >= *dstsize)
return GPMF_ERROR_MEMORY; // bad structure formed
dst[k] = 0;
*dstsize = k;
return GPMF_OK;
}
uint32_t GPMF_SizeOfComplexTYPE(char *type, uint32_t typestringlength)
{
char *typearray = type;
uint32_t size = 0, expand = 0;
uint32_t i, len = typestringlength;
for (i = 0; i < len; i++)
if (typearray[i] == '[')
expand = 1;
if (expand)
{
char exptypearray[64];
uint32_t dstsize = sizeof(exptypearray);
if (GPMF_OK == GPMF_ExpandComplexTYPE(typearray, len, exptypearray, &dstsize))
{
typearray = exptypearray;
len = dstsize;
}
else
return 0;
}
for (i = 0; i < len; i++)
{
uint32_t typesize = GPMF_SizeofType((GPMF_SampleType)typearray[i]);
if (typesize < 1) return 0;
size += typesize;
}
return size;
}
GPMF_ERR GPMF_FormattedData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples)
{
if (ms && buffer)
{
uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];
uint8_t *output = (uint8_t *)buffer;
uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);
uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);
uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
uint32_t typesize = 1;
uint32_t elements = 0;
uint32_t typestringlength = 1;
char complextype[64] = "L";
if (type == GPMF_TYPE_NEST)
return GPMF_ERROR_BAD_STRUCTURE;
if (GPMF_OK != IsValidSize(ms, remaining_sample_size>>2))
return GPMF_ERROR_BAD_STRUCTURE;
if (sample_size * read_samples > buffersize)
return GPMF_ERROR_MEMORY;
remaining_sample_size -= sample_offset * sample_size; // skip samples
data += sample_offset * sample_size;
if (remaining_sample_size < sample_size * read_samples)
return GPMF_ERROR_MEMORY;
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))
{
char *data1 = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
typestringlength = sizeof(complextype);
if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))
{
elements = (uint32_t)strlen(complextype);
if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
{
typesize = GPMF_SizeofType((GPMF_SampleType)type);
if (type == GPMF_TYPE_FOURCC)
typesize = 1; // Do not ByteSWAP
if (typesize == 0)
return GPMF_ERROR_MEMORY;
elements = sample_size / typesize;
}
while (read_samples--)
{
uint32_t i,j;
for (i = 0; i < elements; i++)
{
if (type == GPMF_TYPE_COMPLEX)
{
if (complextype[i] == GPMF_TYPE_FOURCC)
{
*output++ = *data++;
*output++ = *data++;
*output++ = *data++;
*output++ = *data++;
typesize = 0;
}
else
typesize = GPMF_SizeofType(complextype[i]);
}
switch (typesize)
{
case 2:
{
uint16_t *data16 = (uint16_t *)data;
uint16_t *output16 = (uint16_t *)output;
*output16 = BYTESWAP16(*data16);
output16++;
data16++;
data = (uint8_t *)data16;
output = (uint8_t *)output16;
}
break;
case 4:
{
uint32_t *data32 = (uint32_t *)data;
uint32_t *output32 = (uint32_t *)output;
*output32 = BYTESWAP32(*data32);
output32++;
data32++;
data = (uint8_t *)data32;
output = (uint8_t *)output32;
}
break;
case 8:
{
uint32_t *data32 = (uint32_t *)data;
uint32_t *output32 = (uint32_t *)output;
*(output32+1) = BYTESWAP32(*data32);
*(output32) = BYTESWAP32(*(data32+1));
data32 += 2;
output32 += 2;
data = (uint8_t *)data32;
output = (uint8_t *)output32;
}
break;
default: //1, 16 or more not byteswapped
for (j = 0; j < typesize; j++)
*output++ = *data++;
break;
}
}
}
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
#define MACRO_CAST_SCALE_UNSIGNED_TYPE(casttype) \
{ \
casttype *tmp = (casttype *)output; \
switch (scaletype) \
{ \
case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int8_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint8_t *)scaledata8); break; \
case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int16_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint16_t *)scaledata8); break; \
case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((int32_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((uint32_t *)scaledata8); break; \
case GPMF_TYPE_FLOAT: *tmp++ = (casttype)(*val < 0 ? 0 : *val) / (casttype)*((float *)scaledata8); break; \
default: break; \
} \
output = (uint8_t *)tmp; \
}
#define MACRO_CAST_SCALE_SIGNED_TYPE(casttype) \
{ \
casttype *tmp = (casttype *)output; \
switch (scaletype) \
{ \
case GPMF_TYPE_SIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((int8_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_BYTE: *tmp++ = (casttype)*val / (casttype)*((uint8_t *)scaledata8); break; \
case GPMF_TYPE_SIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((int16_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_SHORT: *tmp++ = (casttype)*val / (casttype)*((uint16_t *)scaledata8); break; \
case GPMF_TYPE_SIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((int32_t *)scaledata8); break; \
case GPMF_TYPE_UNSIGNED_LONG: *tmp++ = (casttype)*val / (casttype)*((uint32_t *)scaledata8); break; \
case GPMF_TYPE_FLOAT: *tmp++ = (casttype)*val / (casttype)*((float *)scaledata8); break; \
default: break; \
} \
output = (uint8_t *)tmp; \
}
#define MACRO_CAST_SCALE \
switch (outputType) { \
case GPMF_TYPE_SIGNED_BYTE: MACRO_CAST_SCALE_SIGNED_TYPE(int8_t) break; \
case GPMF_TYPE_UNSIGNED_BYTE: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint8_t) break; \
case GPMF_TYPE_SIGNED_SHORT: MACRO_CAST_SCALE_SIGNED_TYPE(int16_t) break; \
case GPMF_TYPE_UNSIGNED_SHORT: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint16_t) break; \
case GPMF_TYPE_FLOAT: MACRO_CAST_SCALE_SIGNED_TYPE(float) break; \
case GPMF_TYPE_SIGNED_LONG: MACRO_CAST_SCALE_SIGNED_TYPE(int32_t) break; \
case GPMF_TYPE_UNSIGNED_LONG: MACRO_CAST_SCALE_UNSIGNED_TYPE(uint32_t) break; \
case GPMF_TYPE_DOUBLE: MACRO_CAST_SCALE_SIGNED_TYPE(double) break; \
default: break; \
}
#define MACRO_BSWAP_CAST_SCALE(swap, inputcast, tempcast) \
{ \
inputcast *val; \
tempcast temp, *datatemp = (tempcast *)data; \
temp = swap(*datatemp); \
val = (inputcast *)&temp; \
MACRO_CAST_SCALE \
datatemp++; \
data = (uint8_t *)datatemp; \
}
GPMF_ERR GPMF_ScaledData(GPMF_stream *ms, void *buffer, uint32_t buffersize, uint32_t sample_offset, uint32_t read_samples, GPMF_SampleType outputType)
{
if (ms && buffer)
{
uint8_t *data = (uint8_t *)&ms->buffer[ms->pos + 2];
uint8_t *output = (uint8_t *)buffer;
uint32_t sample_size = GPMF_SAMPLE_SIZE(ms->buffer[ms->pos + 1]);
uint32_t output_sample_size = GPMF_SizeofType(outputType);
uint32_t remaining_sample_size = GPMF_DATA_PACKEDSIZE(ms->buffer[ms->pos + 1]);
uint8_t type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
char complextype[64] = "L";
uint32_t inputtypesize = 0;
uint32_t inputtypeelements = 0;
uint8_t scaletype = 0;
uint8_t scalecount = 0;
uint32_t scaletypesize = 0;
uint32_t *scaledata = NULL;
uint32_t tmpbuffer[64];
uint32_t tmpbuffersize = sizeof(tmpbuffer);
uint32_t elements = 1;
type = GPMF_SAMPLE_TYPE(ms->buffer[ms->pos + 1]);
if (type == GPMF_TYPE_NEST)
return GPMF_ERROR_MEMORY;
if (GPMF_OK != IsValidSize(ms, remaining_sample_size >> 2))
return GPMF_ERROR_BAD_STRUCTURE;
remaining_sample_size -= sample_offset * sample_size; // skip samples
data += sample_offset * sample_size;
if (remaining_sample_size < sample_size * read_samples)
return GPMF_ERROR_MEMORY;
if (type == GPMF_TYPE_COMPLEX)
{
GPMF_stream find_stream;
GPMF_CopyState(ms, &find_stream);
if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TYPE, GPMF_RECURSE_LEVELS))
{
char *data1 = (char *)GPMF_RawData(&find_stream);
int size = GPMF_RawDataSize(&find_stream);
uint32_t typestringlength = sizeof(complextype);
if (GPMF_OK == GPMF_ExpandComplexTYPE(data1, size, complextype, &typestringlength))
{
inputtypeelements = elements = typestringlength;
if (sample_size != GPMF_SizeOfComplexTYPE(complextype, typestringlength))
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
}
else
{
complextype[0] = type;
inputtypesize = GPMF_SizeofType(type);
if (inputtypesize == 0)
return GPMF_ERROR_MEMORY;
inputtypeelements = 1;
elements = sample_size / inputtypesize;
}
if (output_sample_size * elements * read_samples > buffersize)
return GPMF_ERROR_MEMORY;
switch (outputType) {
case GPMF_TYPE_SIGNED_BYTE:
case GPMF_TYPE_UNSIGNED_BYTE:
case GPMF_TYPE_SIGNED_SHORT:
case GPMF_TYPE_UNSIGNED_SHORT:
case GPMF_TYPE_FLOAT:
case GPMF_TYPE_SIGNED_LONG:
case GPMF_TYPE_UNSIGNED_LONG:
case GPMF_TYPE_DOUBLE:
// All supported formats.
{
GPMF_stream fs;
GPMF_CopyState(ms, &fs);
if (GPMF_OK == GPMF_FindPrev(&fs, GPMF_KEY_SCALE, GPMF_CURRENT_LEVEL))
{
scaledata = (uint32_t *)GPMF_RawData(&fs);
scaletype = GPMF_SAMPLE_TYPE(fs.buffer[fs.pos + 1]);
switch (scaletype)
{
case GPMF_TYPE_SIGNED_BYTE:
case GPMF_TYPE_UNSIGNED_BYTE:
case GPMF_TYPE_SIGNED_SHORT:
case GPMF_TYPE_UNSIGNED_SHORT:
case GPMF_TYPE_SIGNED_LONG:
case GPMF_TYPE_UNSIGNED_LONG:
case GPMF_TYPE_FLOAT:
scalecount = GPMF_SAMPLES(fs.buffer[fs.pos + 1]);
scaletypesize = GPMF_SizeofType(scaletype);
if (scalecount > 1)
if (scalecount != elements)
return GPMF_ERROR_SCALE_COUNT;
GPMF_FormattedData(&fs, tmpbuffer, tmpbuffersize, 0, scalecount);
scaledata = (uint32_t *)tmpbuffer;
break;
default:
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
break;
}
}
else
{
scaletype = 'L';
scalecount = 1;
tmpbuffer[0] = 1; // set the scale to 1 is no scale was provided
scaledata = (uint32_t *)tmpbuffer;
}
}
while (read_samples--)
{
uint32_t i;
uint8_t *scaledata8 = (uint8_t *)scaledata;
for (i = 0; i < elements; i++)
{
switch (complextype[i % inputtypeelements])
{
case GPMF_TYPE_FLOAT: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, float, uint32_t) break;
case GPMF_TYPE_SIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, int8_t, uint8_t) break;
case GPMF_TYPE_UNSIGNED_BYTE: MACRO_BSWAP_CAST_SCALE(NOSWAP8, uint8_t, uint8_t) break;
case GPMF_TYPE_SIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, int16_t, uint16_t) break;
case GPMF_TYPE_UNSIGNED_SHORT: MACRO_BSWAP_CAST_SCALE(BYTESWAP16, uint16_t, uint16_t) break;
case GPMF_TYPE_SIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, int32_t, uint32_t) break;
case GPMF_TYPE_UNSIGNED_LONG: MACRO_BSWAP_CAST_SCALE(BYTESWAP32, uint32_t, uint32_t) break;
case GPMF_TYPE_SIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;
case GPMF_TYPE_UNSIGNED_64BIT_INT: MACRO_BSWAP_CAST_SCALE(BYTESWAP64, uint64_t, uint64_t) break;
default:
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
break;
}
if (scalecount > 1)
scaledata8 += scaletypesize;
}
}
break;
default:
return GPMF_ERROR_TYPE_NOT_SUPPORTED;
break;
}
return GPMF_OK;
}
return GPMF_ERROR_MEMORY;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_1019_0 |
crossvul-cpp_data_good_3207_0 | /*
* Yerase's TNEF Stream Reader Library
* Copyright (C) 2003 Randall E. Hand
*
* 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
*
* You can contact me at randall.hand@gmail.com for questions or assistance
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <limits.h>
#include "ytnef.h"
#include "tnef-errors.h"
#include "mapi.h"
#include "mapidefs.h"
#include "mapitags.h"
#include "config.h"
#define RTF_PREBUF "{\\rtf1\\ansi\\mac\\deff0\\deftab720{\\fonttbl;}{\\f0\\fnil \\froman \\fswiss \\fmodern \\fscript \\fdecor MS Sans SerifSymbolArialTimes New RomanCourier{\\colortbl\\red0\\green0\\blue0\n\r\\par \\pard\\plain\\f0\\fs20\\b\\i\\u\\tab\\tx"
#define DEBUG(lvl, curlvl, msg) \
if ((lvl) >= (curlvl)) \
printf("DEBUG(%i/%i): %s\n", curlvl, lvl, msg);
#define DEBUG1(lvl, curlvl, msg, var1) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1); \
printf("\n"); \
}
#define DEBUG2(lvl, curlvl, msg, var1, var2) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1, var2); \
printf("\n"); \
}
#define DEBUG3(lvl, curlvl, msg, var1, var2, var3) \
if ((lvl) >= (curlvl)) { \
printf("DEBUG(%i/%i):", curlvl, lvl); \
printf(msg, var1, var2,var3); \
printf("\n"); \
}
#define MIN(x,y) (((x)<(y))?(x):(y))
#define ALLOCCHECK(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(-1); } }
#define ALLOCCHECK_CHAR(x) { if(!x) { printf("Out of Memory at %s : %i\n", __FILE__, __LINE__); return(NULL); } }
#define SIZECHECK(x) { if ((((char *)d - (char *)data) + x) > size) { printf("Corrupted file detected at %s : %i\n", __FILE__, __LINE__); return(-1); } }
int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p);
void SetFlip(void);
int TNEFDefaultHandler STD_ARGLIST;
int TNEFAttachmentFilename STD_ARGLIST;
int TNEFAttachmentSave STD_ARGLIST;
int TNEFDetailedPrint STD_ARGLIST;
int TNEFHexBreakdown STD_ARGLIST;
int TNEFBody STD_ARGLIST;
int TNEFRendData STD_ARGLIST;
int TNEFDateHandler STD_ARGLIST;
int TNEFPriority STD_ARGLIST;
int TNEFVersion STD_ARGLIST;
int TNEFMapiProperties STD_ARGLIST;
int TNEFIcon STD_ARGLIST;
int TNEFSubjectHandler STD_ARGLIST;
int TNEFFromHandler STD_ARGLIST;
int TNEFRecipTable STD_ARGLIST;
int TNEFAttachmentMAPI STD_ARGLIST;
int TNEFSentFor STD_ARGLIST;
int TNEFMessageClass STD_ARGLIST;
int TNEFMessageID STD_ARGLIST;
int TNEFParentID STD_ARGLIST;
int TNEFOriginalMsgClass STD_ARGLIST;
int TNEFCodePage STD_ARGLIST;
BYTE *TNEFFileContents = NULL;
DWORD TNEFFileContentsSize;
BYTE *TNEFFileIcon = NULL;
DWORD TNEFFileIconSize;
int IsCompressedRTF(variableLength *p);
TNEFHandler TNEFList[] = {
{attNull, "Null", TNEFDefaultHandler},
{attFrom, "From", TNEFFromHandler},
{attSubject, "Subject", TNEFSubjectHandler},
{attDateSent, "Date Sent", TNEFDateHandler},
{attDateRecd, "Date Received", TNEFDateHandler},
{attMessageStatus, "Message Status", TNEFDefaultHandler},
{attMessageClass, "Message Class", TNEFMessageClass},
{attMessageID, "Message ID", TNEFMessageID},
{attParentID, "Parent ID", TNEFParentID},
{attConversationID, "Conversation ID", TNEFDefaultHandler},
{attBody, "Body", TNEFBody},
{attPriority, "Priority", TNEFPriority},
{attAttachData, "Attach Data", TNEFAttachmentSave},
{attAttachTitle, "Attach Title", TNEFAttachmentFilename},
{attAttachMetaFile, "Attach Meta-File", TNEFIcon},
{attAttachCreateDate, "Attachment Create Date", TNEFDateHandler},
{attAttachModifyDate, "Attachment Modify Date", TNEFDateHandler},
{attDateModified, "Date Modified", TNEFDateHandler},
{attAttachTransportFilename, "Attachment Transport name", TNEFDefaultHandler},
{attAttachRenddata, "Attachment Display info", TNEFRendData},
{attMAPIProps, "MAPI Properties", TNEFMapiProperties},
{attRecipTable, "Recip Table", TNEFRecipTable},
{attAttachment, "Attachment", TNEFAttachmentMAPI},
{attTnefVersion, "TNEF Version", TNEFVersion},
{attOemCodepage, "OEM CodePage", TNEFCodePage},
{attOriginalMessageClass, "Original Message Class", TNEFOriginalMsgClass},
{attOwner, "Owner", TNEFDefaultHandler},
{attSentFor, "Sent For", TNEFSentFor},
{attDelegate, "Delegate", TNEFDefaultHandler},
{attDateStart, "Date Start", TNEFDateHandler},
{attDateEnd, "Date End", TNEFDateHandler},
{attAidOwner, "Aid Owner", TNEFDefaultHandler},
{attRequestRes, "Request Response", TNEFDefaultHandler}
};
WORD SwapWord(BYTE *p, int size) {
union BYTES2WORD
{
WORD word;
BYTE bytes[sizeof(WORD)];
};
union BYTES2WORD converter;
converter.word = 0;
int i = 0;
int correct = size > sizeof(WORD) ? sizeof(WORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.word;
}
DWORD SwapDWord(BYTE *p, int size) {
union BYTES2DWORD
{
DWORD dword;
BYTE bytes[sizeof(DWORD)];
};
union BYTES2DWORD converter;
converter.dword = 0;
int i = 0;
int correct = size > sizeof(DWORD) ? sizeof(DWORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.dword;
}
DDWORD SwapDDWord(BYTE *p, int size) {
union BYTES2DDWORD
{
DDWORD ddword;
BYTE bytes[sizeof(DDWORD)];
};
union BYTES2DDWORD converter;
converter.ddword = 0;
int i = 0;
int correct = size > sizeof(DDWORD) ? sizeof(DDWORD) : size;
#ifdef WORDS_BIGENDIAN
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[correct - i];
}
#else
for (i = 0; i < correct; ++i)
{
converter.bytes[i] = p[i];
}
#endif
return converter.ddword;
}
/* convert 16-bit unicode to UTF8 unicode */
char *to_utf8(size_t len, char *buf) {
int i, j = 0;
/* worst case length */
if (len > 10000) { // deal with this by adding an arbitrary limit
printf("suspecting a corrupt file in UTF8 conversion\n");
exit(-1);
}
char *utf8 = malloc(3 * len / 2 + 1);
for (i = 0; i < len - 1; i += 2) {
unsigned int c = SwapWord((BYTE *)buf + i, 2);
if (c <= 0x007f) {
utf8[j++] = 0x00 | ((c & 0x007f) >> 0);
} else if (c < 0x07ff) {
utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6);
utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
} else {
utf8[j++] = 0xe0 | ((c & 0xf000) >> 12);
utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6);
utf8[j++] = 0x80 | ((c & 0x003f) >> 0);
}
}
/* just in case the original was not null terminated */
utf8[j++] = '\0';
return utf8;
}
// -----------------------------------------------------------------------------
int TNEFDefaultHandler STD_ARGLIST {
if (TNEF->Debug >= 1)
printf("%s: [%i] %s\n", TNEFList[id].name, size, data);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFCodePage STD_ARGLIST {
TNEF->CodePage.size = size;
TNEF->CodePage.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->CodePage.data);
memcpy(TNEF->CodePage.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFParentID STD_ARGLIST {
memcpy(TNEF->parentID, data, MIN(size, sizeof(TNEF->parentID)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFMessageID STD_ARGLIST {
memcpy(TNEF->messageID, data, MIN(size, sizeof(TNEF->messageID)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFBody STD_ARGLIST {
TNEF->body.size = size;
TNEF->body.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->body.data);
memcpy(TNEF->body.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFOriginalMsgClass STD_ARGLIST {
TNEF->OriginalMessageClass.size = size;
TNEF->OriginalMessageClass.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->OriginalMessageClass.data);
memcpy(TNEF->OriginalMessageClass.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFMessageClass STD_ARGLIST {
memcpy(TNEF->messageClass, data, MIN(size, sizeof(TNEF->messageClass)));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFFromHandler STD_ARGLIST {
TNEF->from.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->from.data);
TNEF->from.size = size;
memcpy(TNEF->from.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFSubjectHandler STD_ARGLIST {
if (TNEF->subject.data)
free(TNEF->subject.data);
TNEF->subject.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->subject.data);
TNEF->subject.size = size;
memcpy(TNEF->subject.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRendData STD_ARGLIST {
Attachment *p;
// Find the last attachment.
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
// Add a new one
p->next = calloc(1, sizeof(Attachment));
ALLOCCHECK(p->next);
p = p->next;
TNEFInitAttachment(p);
int correct = (size >= sizeof(renddata)) ? sizeof(renddata) : size;
memcpy(&(p->RenderData), data, correct);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFVersion STD_ARGLIST {
WORD major;
WORD minor;
minor = SwapWord((BYTE*)data, size);
major = SwapWord((BYTE*)data + 2, size - 2);
snprintf(TNEF->version, sizeof(TNEF->version), "TNEF%i.%i", major, minor);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFIcon STD_ARGLIST {
Attachment *p;
// Find the last attachment.
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->IconData.size = size;
p->IconData.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(p->IconData.data);
memcpy(p->IconData.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRecipTable STD_ARGLIST {
DWORD count;
BYTE *d;
int current_row;
int propcount;
int current_prop;
d = (BYTE*)data;
count = SwapDWord((BYTE*)d, 4);
d += 4;
// printf("Recipient Table containing %u rows\n", count);
return 0;
for (current_row = 0; current_row < count; current_row++) {
propcount = SwapDWord((BYTE*)d, 4);
if (TNEF->Debug >= 1)
printf("> Row %i contains %i properties\n", current_row, propcount);
d += 4;
for (current_prop = 0; current_prop < propcount; current_prop++) {
}
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentMAPI STD_ARGLIST {
Attachment *p;
// Find the last attachment.
//
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
return TNEFFillMapi(TNEF, (BYTE*)data, size, &(p->MAPI));
}
// -----------------------------------------------------------------------------
int TNEFMapiProperties STD_ARGLIST {
if (TNEFFillMapi(TNEF, (BYTE*)data, size, &(TNEF->MapiProperties)) < 0) {
printf("ERROR Parsing MAPI block\n");
return -1;
};
if (TNEF->Debug >= 3) {
MAPIPrint(&(TNEF->MapiProperties));
}
return 0;
}
int TNEFFillMapi(TNEFStruct *TNEF, BYTE *data, DWORD size, MAPIProps *p) {
int i, j;
DWORD num;
BYTE *d;
MAPIProperty *mp;
DWORD type;
DWORD length;
variableLength *vl;
WORD temp_word;
DWORD temp_dword;
DDWORD temp_ddword;
int count = -1;
int offset;
d = data;
p->count = SwapDWord((BYTE*)data, 4);
d += 4;
p->properties = calloc(p->count, sizeof(MAPIProperty));
ALLOCCHECK(p->properties);
mp = p->properties;
for (i = 0; i < p->count; i++) {
if (count == -1) {
mp->id = SwapDWord((BYTE*)d, 4);
d += 4;
mp->custom = 0;
mp->count = 1;
mp->namedproperty = 0;
length = -1;
if (PROP_ID(mp->id) >= 0x8000) {
// Read the GUID
SIZECHECK(16);
memcpy(&(mp->guid[0]), d, 16);
d += 16;
SIZECHECK(4);
length = SwapDWord((BYTE*)d, 4);
d += sizeof(DWORD);
if (length > 0) {
mp->namedproperty = length;
mp->propnames = calloc(length, sizeof(variableLength));
ALLOCCHECK(mp->propnames);
while (length > 0) {
SIZECHECK(4);
type = SwapDWord((BYTE*)d, 4);
mp->propnames[length - 1].data = calloc(type, sizeof(BYTE));
ALLOCCHECK(mp->propnames[length - 1].data);
mp->propnames[length - 1].size = type;
d += 4;
for (j = 0; j < (type >> 1); j++) {
SIZECHECK(j*2);
mp->propnames[length - 1].data[j] = d[j * 2];
}
d += type + ((type % 4) ? (4 - type % 4) : 0);
length--;
}
} else {
// READ the type
SIZECHECK(sizeof(DWORD));
type = SwapDWord((BYTE*)d, sizeof(DWORD));
d += sizeof(DWORD);
mp->id = PROP_TAG(PROP_TYPE(mp->id), type);
}
mp->custom = 1;
}
DEBUG2(TNEF->Debug, 3, "Type id = %04x, Prop id = %04x", PROP_TYPE(mp->id),
PROP_ID(mp->id));
if (PROP_TYPE(mp->id) & MV_FLAG) {
mp->id = PROP_TAG(PROP_TYPE(mp->id) - MV_FLAG, PROP_ID(mp->id));
SIZECHECK(4);
mp->count = SwapDWord((BYTE*)d, 4);
d += 4;
count = 0;
}
mp->data = calloc(mp->count, sizeof(variableLength));
ALLOCCHECK(mp->data);
vl = mp->data;
} else {
i--;
count++;
vl = &(mp->data[count]);
}
switch (PROP_TYPE(mp->id)) {
case PT_BINARY:
case PT_OBJECT:
case PT_STRING8:
case PT_UNICODE:
// First number of objects (assume 1 for now)
if (count == -1) {
SIZECHECK(4);
vl->size = SwapDWord((BYTE*)d, 4);
d += 4;
}
// now size of object
SIZECHECK(4);
vl->size = SwapDWord((BYTE*)d, 4);
d += 4;
// now actual object
if (vl->size != 0) {
SIZECHECK(vl->size);
if (PROP_TYPE(mp->id) == PT_UNICODE) {
vl->data =(BYTE*) to_utf8(vl->size, (char*)d);
} else {
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
memcpy(vl->data, d, vl->size);
}
} else {
vl->data = NULL;
}
// Make sure to read in a multiple of 4
num = vl->size;
offset = ((num % 4) ? (4 - num % 4) : 0);
d += num + ((num % 4) ? (4 - num % 4) : 0);
break;
case PT_I2:
// Read in 2 bytes, but proceed by 4 bytes
vl->size = 2;
vl->data = calloc(vl->size, sizeof(WORD));
ALLOCCHECK(vl->data);
SIZECHECK(sizeof(WORD))
temp_word = SwapWord((BYTE*)d, sizeof(WORD));
memcpy(vl->data, &temp_word, vl->size);
d += 4;
break;
case PT_BOOLEAN:
case PT_LONG:
case PT_R4:
case PT_CURRENCY:
case PT_APPTIME:
case PT_ERROR:
vl->size = 4;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(4);
temp_dword = SwapDWord((BYTE*)d, 4);
memcpy(vl->data, &temp_dword, vl->size);
d += 4;
break;
case PT_DOUBLE:
case PT_I8:
case PT_SYSTIME:
vl->size = 8;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(8);
temp_ddword = SwapDDWord(d, 8);
memcpy(vl->data, &temp_ddword, vl->size);
d += 8;
break;
case PT_CLSID:
vl->size = 16;
vl->data = calloc(vl->size, sizeof(BYTE));
ALLOCCHECK(vl->data);
SIZECHECK(vl->size);
memcpy(vl->data, d, vl->size);
d+=16;
break;
default:
printf("Bad file\n");
exit(-1);
}
switch (PROP_ID(mp->id)) {
case PR_SUBJECT:
case PR_SUBJECT_IPM:
case PR_ORIGINAL_SUBJECT:
case PR_NORMALIZED_SUBJECT:
case PR_CONVERSATION_TOPIC:
DEBUG(TNEF->Debug, 3, "Got a Subject");
if (TNEF->subject.size == 0) {
int i;
DEBUG(TNEF->Debug, 3, "Assigning a Subject");
TNEF->subject.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(TNEF->subject.data);
TNEF->subject.size = vl->size;
memcpy(TNEF->subject.data, vl->data, vl->size);
// Unfortunately, we have to normalize out some invalid
// characters, or else the file won't write
for (i = 0; i != TNEF->subject.size; i++) {
switch (TNEF->subject.data[i]) {
case '\\':
case '/':
case '\0':
TNEF->subject.data[i] = '_';
break;
}
}
}
break;
}
if (count == (mp->count - 1)) {
count = -1;
}
if (count == -1) {
mp++;
}
}
if ((d - data) < size) {
if (TNEF->Debug >= 1) {
printf("ERROR DURING MAPI READ\n");
printf("Read %td bytes, Expected %u bytes\n", (d - data), size);
printf("%td bytes missing\n", size - (d - data));
}
} else if ((d - data) > size) {
if (TNEF->Debug >= 1) {
printf("ERROR DURING MAPI READ\n");
printf("Read %td bytes, Expected %u bytes\n", (d - data), size);
printf("%li bytes extra\n", (d - data) - size);
}
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFSentFor STD_ARGLIST {
WORD name_length, addr_length;
BYTE *d;
d = (BYTE*)data;
while ((d - (BYTE*)data) < size) {
SIZECHECK(sizeof(WORD));
name_length = SwapWord((BYTE*)d, sizeof(WORD));
d += sizeof(WORD);
if (TNEF->Debug >= 1)
printf("Sent For : %s", d);
d += name_length;
SIZECHECK(sizeof(WORD));
addr_length = SwapWord((BYTE*)d, sizeof(WORD));
d += sizeof(WORD);
if (TNEF->Debug >= 1)
printf("<%s>\n", d);
d += addr_length;
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFDateHandler STD_ARGLIST {
dtr *Date;
Attachment *p;
WORD * tmp_src, *tmp_dst;
int i;
p = &(TNEF->starting_attach);
switch (TNEFList[id].id) {
case attDateSent: Date = &(TNEF->dateSent); break;
case attDateRecd: Date = &(TNEF->dateReceived); break;
case attDateModified: Date = &(TNEF->dateModified); break;
case attDateStart: Date = &(TNEF->DateStart); break;
case attDateEnd: Date = &(TNEF->DateEnd); break;
case attAttachCreateDate:
while (p->next != NULL) p = p->next;
Date = &(p->CreateDate);
break;
case attAttachModifyDate:
while (p->next != NULL) p = p->next;
Date = &(p->ModifyDate);
break;
default:
if (TNEF->Debug >= 1)
printf("MISSING CASE\n");
return YTNEF_UNKNOWN_PROPERTY;
}
tmp_src = (WORD *)data;
tmp_dst = (WORD *)Date;
for (i = 0; i < sizeof(dtr) / sizeof(WORD); i++) {
*tmp_dst++ = SwapWord((BYTE *)tmp_src++, sizeof(WORD));
}
return 0;
}
void TNEFPrintDate(dtr Date) {
char days[7][15] = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
};
char months[12][15] = {"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October", "November",
"December"
};
if (Date.wDayOfWeek < 7)
printf("%s ", days[Date.wDayOfWeek]);
if ((Date.wMonth < 13) && (Date.wMonth > 0))
printf("%s ", months[Date.wMonth - 1]);
printf("%hu, %hu ", Date.wDay, Date.wYear);
if (Date.wHour > 12)
printf("%i:%02hu:%02hu pm", (Date.wHour - 12),
Date.wMinute, Date.wSecond);
else if (Date.wHour == 12)
printf("%hu:%02hu:%02hu pm", (Date.wHour),
Date.wMinute, Date.wSecond);
else
printf("%hu:%02hu:%02hu am", Date.wHour,
Date.wMinute, Date.wSecond);
}
// -----------------------------------------------------------------------------
int TNEFHexBreakdown STD_ARGLIST {
int i;
if (TNEF->Debug == 0)
return 0;
printf("%s: [%i bytes] \n", TNEFList[id].name, size);
for (i = 0; i < size; i++) {
printf("%02x ", data[i]);
if ((i + 1) % 16 == 0) printf("\n");
}
printf("\n");
return 0;
}
// -----------------------------------------------------------------------------
int TNEFDetailedPrint STD_ARGLIST {
int i;
if (TNEF->Debug == 0)
return 0;
printf("%s: [%i bytes] \n", TNEFList[id].name, size);
for (i = 0; i < size; i++) {
printf("%c", data[i]);
}
printf("\n");
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentFilename STD_ARGLIST {
Attachment *p;
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->Title.size = size;
p->Title.data = calloc(size, sizeof(BYTE));
ALLOCCHECK(p->Title.data);
memcpy(p->Title.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFAttachmentSave STD_ARGLIST {
Attachment *p;
p = &(TNEF->starting_attach);
while (p->next != NULL) p = p->next;
p->FileData.data = calloc(sizeof(char), size);
ALLOCCHECK(p->FileData.data);
p->FileData.size = size;
memcpy(p->FileData.data, data, size);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFPriority STD_ARGLIST {
DWORD value;
value = SwapDWord((BYTE*)data, size);
switch (value) {
case 3:
sprintf((TNEF->priority), "high");
break;
case 2:
sprintf((TNEF->priority), "normal");
break;
case 1:
sprintf((TNEF->priority), "low");
break;
default:
sprintf((TNEF->priority), "N/A");
break;
}
return 0;
}
// -----------------------------------------------------------------------------
int TNEFCheckForSignature(DWORD sig) {
DWORD signature = 0x223E9F78;
sig = SwapDWord((BYTE *)&sig, sizeof(DWORD));
if (signature == sig) {
return 0;
} else {
return YTNEF_NOT_TNEF_STREAM;
}
}
// -----------------------------------------------------------------------------
int TNEFGetKey(TNEFStruct *TNEF, WORD *key) {
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(WORD), 1, key) < 1) {
if (TNEF->Debug >= 1)
printf("Error reading Key\n");
return YTNEF_ERROR_READING_DATA;
}
*key = SwapWord((BYTE *)key, sizeof(WORD));
DEBUG1(TNEF->Debug, 2, "Key = 0x%X", *key);
DEBUG1(TNEF->Debug, 2, "Key = %i", *key);
return 0;
}
// -----------------------------------------------------------------------------
int TNEFGetHeader(TNEFStruct *TNEF, DWORD *type, DWORD *size) {
BYTE component;
DEBUG(TNEF->Debug, 2, "About to read Component");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(BYTE), 1, &component) < 1) {
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "About to read type");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, type) < 1) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading type\n");
return YTNEF_ERROR_READING_DATA;
}
DEBUG1(TNEF->Debug, 2, "Type = 0x%X", *type);
DEBUG1(TNEF->Debug, 2, "Type = %u", *type);
DEBUG(TNEF->Debug, 2, "About to read size");
if (TNEF->IO.ReadProc(&(TNEF->IO), sizeof(DWORD), 1, size) < 1) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading size\n");
return YTNEF_ERROR_READING_DATA;
}
DEBUG1(TNEF->Debug, 2, "Size = %u", *size);
*type = SwapDWord((BYTE *)type, sizeof(DWORD));
*size = SwapDWord((BYTE *)size, sizeof(DWORD));
return 0;
}
// -----------------------------------------------------------------------------
int TNEFRawRead(TNEFStruct *TNEF, BYTE *data, DWORD size, WORD *checksum) {
WORD temp;
int i;
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(BYTE), size, data) < size) {
if (TNEF->Debug >= 1)
printf("ERROR: Error reading data\n");
return YTNEF_ERROR_READING_DATA;
}
if (checksum != NULL) {
*checksum = 0;
for (i = 0; i < size; i++) {
temp = data[i];
*checksum = (*checksum + temp);
}
}
return 0;
}
#define INITVARLENGTH(x) (x).data = NULL; (x).size = 0;
#define INITDTR(x) (x).wYear=0; (x).wMonth=0; (x).wDay=0; \
(x).wHour=0; (x).wMinute=0; (x).wSecond=0; \
(x).wDayOfWeek=0;
#define INITSTR(x) memset((x), 0, sizeof(x));
void TNEFInitMapi(MAPIProps *p) {
p->count = 0;
p->properties = NULL;
}
void TNEFInitAttachment(Attachment *p) {
INITDTR(p->Date);
INITVARLENGTH(p->Title);
INITVARLENGTH(p->MetaFile);
INITDTR(p->CreateDate);
INITDTR(p->ModifyDate);
INITVARLENGTH(p->TransportFilename);
INITVARLENGTH(p->FileData);
INITVARLENGTH(p->IconData);
memset(&(p->RenderData), 0, sizeof(renddata));
TNEFInitMapi(&(p->MAPI));
p->next = NULL;
}
void TNEFInitialize(TNEFStruct *TNEF) {
INITSTR(TNEF->version);
INITVARLENGTH(TNEF->from);
INITVARLENGTH(TNEF->subject);
INITDTR(TNEF->dateSent);
INITDTR(TNEF->dateReceived);
INITSTR(TNEF->messageStatus);
INITSTR(TNEF->messageClass);
INITSTR(TNEF->messageID);
INITSTR(TNEF->parentID);
INITSTR(TNEF->conversationID);
INITVARLENGTH(TNEF->body);
INITSTR(TNEF->priority);
TNEFInitAttachment(&(TNEF->starting_attach));
INITDTR(TNEF->dateModified);
TNEFInitMapi(&(TNEF->MapiProperties));
INITVARLENGTH(TNEF->CodePage);
INITVARLENGTH(TNEF->OriginalMessageClass);
INITVARLENGTH(TNEF->Owner);
INITVARLENGTH(TNEF->SentFor);
INITVARLENGTH(TNEF->Delegate);
INITDTR(TNEF->DateStart);
INITDTR(TNEF->DateEnd);
INITVARLENGTH(TNEF->AidOwner);
TNEF->RequestRes = 0;
TNEF->IO.data = NULL;
TNEF->IO.InitProc = NULL;
TNEF->IO.ReadProc = NULL;
TNEF->IO.CloseProc = NULL;
}
#undef INITVARLENGTH
#undef INITDTR
#undef INITSTR
#define FREEVARLENGTH(x) if ((x).size > 0) { \
free((x).data); (x).size =0; }
void TNEFFree(TNEFStruct *TNEF) {
Attachment *p, *store;
FREEVARLENGTH(TNEF->from);
FREEVARLENGTH(TNEF->subject);
FREEVARLENGTH(TNEF->body);
FREEVARLENGTH(TNEF->CodePage);
FREEVARLENGTH(TNEF->OriginalMessageClass);
FREEVARLENGTH(TNEF->Owner);
FREEVARLENGTH(TNEF->SentFor);
FREEVARLENGTH(TNEF->Delegate);
FREEVARLENGTH(TNEF->AidOwner);
TNEFFreeMapiProps(&(TNEF->MapiProperties));
p = TNEF->starting_attach.next;
while (p != NULL) {
TNEFFreeAttachment(p);
store = p->next;
free(p);
p = store;
}
}
void TNEFFreeAttachment(Attachment *p) {
FREEVARLENGTH(p->Title);
FREEVARLENGTH(p->MetaFile);
FREEVARLENGTH(p->TransportFilename);
FREEVARLENGTH(p->FileData);
FREEVARLENGTH(p->IconData);
TNEFFreeMapiProps(&(p->MAPI));
}
void TNEFFreeMapiProps(MAPIProps *p) {
int i, j;
for (i = 0; i < p->count; i++) {
for (j = 0; j < p->properties[i].count; j++) {
FREEVARLENGTH(p->properties[i].data[j]);
}
free(p->properties[i].data);
for (j = 0; j < p->properties[i].namedproperty; j++) {
FREEVARLENGTH(p->properties[i].propnames[j]);
}
free(p->properties[i].propnames);
}
free(p->properties);
p->count = 0;
}
#undef FREEVARLENGTH
// Procedures to handle File IO
int TNEFFile_Open(TNEFIOStruct *IO) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG1(finfo->Debug, 3, "Opening %s", finfo->filename);
if ((finfo->fptr = fopen(finfo->filename, "rb")) == NULL) {
return -1;
} else {
return 0;
}
}
int TNEFFile_Read(TNEFIOStruct *IO, int size, int count, void *dest) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG2(finfo->Debug, 3, "Reading %i blocks of %i size", count, size);
if (finfo->fptr != NULL) {
return fread((BYTE *)dest, size, count, finfo->fptr);
} else {
return -1;
}
}
int TNEFFile_Close(TNEFIOStruct *IO) {
TNEFFileInfo *finfo;
finfo = (TNEFFileInfo *)IO->data;
DEBUG1(finfo->Debug, 3, "Closing file %s", finfo->filename);
if (finfo->fptr != NULL) {
fclose(finfo->fptr);
finfo->fptr = NULL;
}
return 0;
}
int TNEFParseFile(char *filename, TNEFStruct *TNEF) {
TNEFFileInfo finfo;
if (TNEF->Debug >= 1)
printf("Attempting to parse %s...\n", filename);
finfo.filename = filename;
finfo.fptr = NULL;
finfo.Debug = TNEF->Debug;
TNEF->IO.data = (void *)&finfo;
TNEF->IO.InitProc = TNEFFile_Open;
TNEF->IO.ReadProc = TNEFFile_Read;
TNEF->IO.CloseProc = TNEFFile_Close;
return TNEFParse(TNEF);
}
//-------------------------------------------------------------
// Procedures to handle Memory IO
int TNEFMemory_Open(TNEFIOStruct *IO) {
TNEFMemInfo *minfo;
minfo = (TNEFMemInfo *)IO->data;
minfo->ptr = minfo->dataStart;
return 0;
}
int TNEFMemory_Read(TNEFIOStruct *IO, int size, int count, void *dest) {
TNEFMemInfo *minfo;
int length;
long max;
minfo = (TNEFMemInfo *)IO->data;
length = count * size;
max = (minfo->dataStart + minfo->size) - (minfo->ptr);
if (length > max) {
return -1;
}
DEBUG1(minfo->Debug, 3, "Copying %i bytes", length);
memcpy(dest, minfo->ptr, length);
minfo->ptr += length;
return count;
}
int TNEFMemory_Close(TNEFIOStruct *IO) {
// Do nothing, really...
return 0;
}
int TNEFParseMemory(BYTE *memory, long size, TNEFStruct *TNEF) {
TNEFMemInfo minfo;
DEBUG(TNEF->Debug, 1, "Attempting to parse memory block...\n");
minfo.dataStart = memory;
minfo.ptr = memory;
minfo.size = size;
minfo.Debug = TNEF->Debug;
TNEF->IO.data = (void *)&minfo;
TNEF->IO.InitProc = TNEFMemory_Open;
TNEF->IO.ReadProc = TNEFMemory_Read;
TNEF->IO.CloseProc = TNEFMemory_Close;
return TNEFParse(TNEF);
}
int TNEFParse(TNEFStruct *TNEF) {
WORD key;
DWORD type;
DWORD size;
DWORD signature;
BYTE *data;
WORD checksum, header_checksum;
int i;
if (TNEF->IO.ReadProc == NULL) {
printf("ERROR: Setup incorrectly: No ReadProc\n");
return YTNEF_INCORRECT_SETUP;
}
if (TNEF->IO.InitProc != NULL) {
DEBUG(TNEF->Debug, 2, "About to initialize");
if (TNEF->IO.InitProc(&TNEF->IO) != 0) {
return YTNEF_CANNOT_INIT_DATA;
}
DEBUG(TNEF->Debug, 2, "Initialization finished");
}
DEBUG(TNEF->Debug, 2, "Reading Signature");
if (TNEF->IO.ReadProc(&TNEF->IO, sizeof(DWORD), 1, &signature) < 1) {
printf("ERROR: Error reading signature\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_READING_DATA;
}
DEBUG(TNEF->Debug, 2, "Checking Signature");
if (TNEFCheckForSignature(signature) < 0) {
printf("ERROR: Signature does not match. Not TNEF.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NOT_TNEF_STREAM;
}
DEBUG(TNEF->Debug, 2, "Reading Key.");
if (TNEFGetKey(TNEF, &key) < 0) {
printf("ERROR: Unable to retrieve key.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_NO_KEY;
}
DEBUG(TNEF->Debug, 2, "Starting Full Processing.");
while (TNEFGetHeader(TNEF, &type, &size) == 0) {
DEBUG2(TNEF->Debug, 2, "Header says type=0x%X, size=%u", type, size);
DEBUG2(TNEF->Debug, 2, "Header says type=%u, size=%u", type, size);
data = calloc(size, sizeof(BYTE));
ALLOCCHECK(data);
if (TNEFRawRead(TNEF, data, size, &header_checksum) < 0) {
printf("ERROR: Unable to read data.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
if (TNEFRawRead(TNEF, (BYTE *)&checksum, 2, NULL) < 0) {
printf("ERROR: Unable to read checksum.\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_ERROR_READING_DATA;
}
checksum = SwapWord((BYTE *)&checksum, sizeof(WORD));
if (checksum != header_checksum) {
printf("ERROR: Checksum mismatch. Data corruption?:\n");
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
free(data);
return YTNEF_BAD_CHECKSUM;
}
for (i = 0; i < (sizeof(TNEFList) / sizeof(TNEFHandler)); i++) {
if (TNEFList[i].id == type) {
if (TNEFList[i].handler != NULL) {
if (TNEFList[i].handler(TNEF, i, (char*)data, size) < 0) {
free(data);
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return YTNEF_ERROR_IN_HANDLER;
} else {
// Found our handler and processed it. now time to get out
break;
}
} else {
DEBUG2(TNEF->Debug, 1, "No handler for %s: %u bytes",
TNEFList[i].name, size);
}
}
}
free(data);
}
if (TNEF->IO.CloseProc != NULL) {
TNEF->IO.CloseProc(&TNEF->IO);
}
return 0;
}
// ----------------------------------------------------------------------------
variableLength *MAPIFindUserProp(MAPIProps *p, unsigned int ID) {
int i;
if (p != NULL) {
for (i = 0; i < p->count; i++) {
if ((p->properties[i].id == ID) && (p->properties[i].custom == 1)) {
return (p->properties[i].data);
}
}
}
return MAPI_UNDEFINED;
}
variableLength *MAPIFindProperty(MAPIProps *p, unsigned int ID) {
int i;
if (p != NULL) {
for (i = 0; i < p->count; i++) {
if ((p->properties[i].id == ID) && (p->properties[i].custom == 0)) {
return (p->properties[i].data);
}
}
}
return MAPI_UNDEFINED;
}
int MAPISysTimetoDTR(BYTE *data, dtr *thedate) {
DDWORD ddword_tmp;
int startingdate = 0;
int tmp_date;
int days_in_year = 365;
unsigned int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
ddword_tmp = *((DDWORD *)data);
ddword_tmp = ddword_tmp / 10; // micro-s
ddword_tmp /= 1000; // ms
ddword_tmp /= 1000; // s
thedate->wSecond = (ddword_tmp % 60);
ddword_tmp /= 60; // seconds to minutes
thedate->wMinute = (ddword_tmp % 60);
ddword_tmp /= 60; //minutes to hours
thedate->wHour = (ddword_tmp % 24);
ddword_tmp /= 24; // Hours to days
// Now calculate the year based on # of days
thedate->wYear = 1601;
startingdate = 1;
while (ddword_tmp >= days_in_year) {
ddword_tmp -= days_in_year;
thedate->wYear++;
days_in_year = 365;
startingdate++;
if ((thedate->wYear % 4) == 0) {
if ((thedate->wYear % 100) == 0) {
// if the year is 1700,1800,1900, etc, then it is only
// a leap year if exactly divisible by 400, not 4.
if ((thedate->wYear % 400) == 0) {
startingdate++;
days_in_year = 366;
}
} else {
startingdate++;
days_in_year = 366;
}
}
startingdate %= 7;
}
// the remaining number is the day # in this year
// So now calculate the Month, & Day of month
if ((thedate->wYear % 4) == 0) {
// 29 days in february in a leap year
months[1] = 29;
}
tmp_date = (int)ddword_tmp;
thedate->wDayOfWeek = (tmp_date + startingdate) % 7;
thedate->wMonth = 0;
while (tmp_date > months[thedate->wMonth]) {
tmp_date -= months[thedate->wMonth];
thedate->wMonth++;
}
thedate->wMonth++;
thedate->wDay = tmp_date + 1;
return 0;
}
void MAPIPrint(MAPIProps *p) {
int j, i, index, h, x;
DDWORD *ddword_ptr;
DDWORD ddword_tmp;
dtr thedate;
MAPIProperty *mapi;
variableLength *mapidata;
variableLength vlTemp;
int found;
for (j = 0; j < p->count; j++) {
mapi = &(p->properties[j]);
printf(" #%i: Type: [", j);
switch (PROP_TYPE(mapi->id)) {
case PT_UNSPECIFIED:
printf(" NONE "); break;
case PT_NULL:
printf(" NULL "); break;
case PT_I2:
printf(" I2 "); break;
case PT_LONG:
printf(" LONG "); break;
case PT_R4:
printf(" R4 "); break;
case PT_DOUBLE:
printf(" DOUBLE "); break;
case PT_CURRENCY:
printf("CURRENCY "); break;
case PT_APPTIME:
printf("APP TIME "); break;
case PT_ERROR:
printf(" ERROR "); break;
case PT_BOOLEAN:
printf(" BOOLEAN "); break;
case PT_OBJECT:
printf(" OBJECT "); break;
case PT_I8:
printf(" I8 "); break;
case PT_STRING8:
printf(" STRING8 "); break;
case PT_UNICODE:
printf(" UNICODE "); break;
case PT_SYSTIME:
printf("SYS TIME "); break;
case PT_CLSID:
printf("OLE GUID "); break;
case PT_BINARY:
printf(" BINARY "); break;
default:
printf("<%x>", PROP_TYPE(mapi->id)); break;
}
printf("] Code: [");
if (mapi->custom == 1) {
printf("UD:x%04x", PROP_ID(mapi->id));
} else {
found = 0;
for (index = 0; index < sizeof(MPList) / sizeof(MAPIPropertyTagList); index++) {
if ((MPList[index].id == PROP_ID(mapi->id)) && (found == 0)) {
printf("%s", MPList[index].name);
found = 1;
}
}
if (found == 0) {
printf("0x%04x", PROP_ID(mapi->id));
}
}
printf("]\n");
if (mapi->namedproperty > 0) {
for (i = 0; i < mapi->namedproperty; i++) {
printf(" Name: %s\n", mapi->propnames[i].data);
}
}
for (i = 0; i < mapi->count; i++) {
mapidata = &(mapi->data[i]);
if (mapi->count > 1) {
printf(" [%i/%u] ", i, mapi->count);
} else {
printf(" ");
}
printf("Size: %i", mapidata->size);
switch (PROP_TYPE(mapi->id)) {
case PT_SYSTIME:
MAPISysTimetoDTR(mapidata->data, &thedate);
printf(" Value: ");
ddword_tmp = *((DDWORD *)mapidata->data);
TNEFPrintDate(thedate);
printf(" [HEX: ");
for (x = 0; x < sizeof(ddword_tmp); x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("] (%llu)\n", ddword_tmp);
break;
case PT_LONG:
printf(" Value: %i\n", *((int*)mapidata->data));
break;
case PT_I2:
printf(" Value: %hi\n", *((short int*)mapidata->data));
break;
case PT_BOOLEAN:
if (mapi->data->data[0] != 0) {
printf(" Value: True\n");
} else {
printf(" Value: False\n");
}
break;
case PT_OBJECT:
printf("\n");
break;
case PT_BINARY:
if (IsCompressedRTF(mapidata) == 1) {
printf(" Detected Compressed RTF. ");
printf("Decompressed text follows\n");
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
if ((vlTemp.data = (BYTE*)DecompressRTF(mapidata, &(vlTemp.size))) != NULL) {
printf("%s\n", vlTemp.data);
free(vlTemp.data);
}
printf("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
} else {
printf(" Value: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_STRING8:
printf(" Value: [%s]\n", mapidata->data);
if (strlen((char*)mapidata->data) != mapidata->size - 1) {
printf("Detected Hidden data: [");
for (h = 0; h < mapidata->size; h++) {
if (isprint(mapidata->data[h])) {
printf("%c", mapidata->data[h]);
} else {
printf(".");
}
}
printf("]\n");
}
break;
case PT_CLSID:
printf(" Value: ");
printf("[HEX: ");
for(x=0; x< 16; x++) {
printf(" %02x", (BYTE)mapidata->data[x]);
}
printf("]\n");
break;
default:
printf(" Value: [%s]\n", mapidata->data);
}
}
}
}
int IsCompressedRTF(variableLength *p) {
unsigned int in;
BYTE *src;
ULONG magic;
if (p->size < 4)
return 0;
src = p->data;
in = 0;
in += 4;
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
if (magic == 0x414c454d) {
return 1;
} else if (magic == 0x75465a4c) {
return 1;
} else {
return 0;
}
}
BYTE *DecompressRTF(variableLength *p, int *size) {
BYTE *dst; // destination for uncompressed bytes
BYTE *src;
unsigned int in;
unsigned int out;
variableLength comp_Prebuf;
ULONG compressedSize, uncompressedSize, magic;
comp_Prebuf.size = strlen(RTF_PREBUF);
comp_Prebuf.data = calloc(comp_Prebuf.size+1, 1);
ALLOCCHECK_CHAR(comp_Prebuf.data);
memcpy(comp_Prebuf.data, RTF_PREBUF, comp_Prebuf.size);
src = p->data;
in = 0;
if (p->size < 20) {
printf("File too small\n");
return(NULL);
}
compressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
uncompressedSize = (ULONG)SwapDWord((BYTE*)src + in, 4);
in += 4;
magic = SwapDWord((BYTE*)src + in, 4);
in += 4;
in += 4;
// check size excluding the size field itself
if (compressedSize != p->size - 4) {
printf(" Size Mismatch: %u != %i\n", compressedSize, p->size - 4);
free(comp_Prebuf.data);
return NULL;
}
// process the data
if (magic == 0x414c454d) {
// magic number that identifies the stream as a uncompressed stream
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + 4, uncompressedSize);
} else if (magic == 0x75465a4c) {
// magic number that identifies the stream as a compressed stream
int flagCount = 0;
int flags = 0;
// Prevent overflow on 32 Bit Systems
if (comp_Prebuf.size >= INT_MAX - uncompressedSize) {
printf("Corrupted file\n");
exit(-1);
}
dst = calloc(comp_Prebuf.size + uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, comp_Prebuf.data, comp_Prebuf.size);
out = comp_Prebuf.size;
while (out < (comp_Prebuf.size + uncompressedSize)) {
// each flag byte flags 8 literals/references, 1 per bit
flags = (flagCount++ % 8 == 0) ? src[in++] : flags >> 1;
if ((flags & 1) == 1) { // each flag bit is 1 for reference, 0 for literal
unsigned int offset = src[in++];
unsigned int length = src[in++];
unsigned int end;
offset = (offset << 4) | (length >> 4); // the offset relative to block start
length = (length & 0xF) + 2; // the number of bytes to copy
// the decompression buffer is supposed to wrap around back
// to the beginning when the end is reached. we save the
// need for such a buffer by pointing straight into the data
// buffer, and simulating this behaviour by modifying the
// pointers appropriately.
offset = (out / 4096) * 4096 + offset;
if (offset >= out) // take from previous block
offset -= 4096;
// note: can't use System.arraycopy, because the referenced
// bytes can cross through the current out position.
end = offset + length;
while ((offset < end) && (out < (comp_Prebuf.size + uncompressedSize))
&& (offset < (comp_Prebuf.size + uncompressedSize)))
dst[out++] = dst[offset++];
} else { // literal
if ((out >= (comp_Prebuf.size + uncompressedSize)) ||
(in >= p->size)) {
printf("Corrupted stream\n");
exit(-1);
}
dst[out++] = src[in++];
}
}
// copy it back without the prebuffered data
src = dst;
dst = calloc(uncompressedSize, 1);
ALLOCCHECK_CHAR(dst);
memcpy(dst, src + comp_Prebuf.size, uncompressedSize);
free(src);
*size = uncompressedSize;
free(comp_Prebuf.data);
return dst;
} else { // unknown magic number
printf("Unknown compression type (magic number %x)\n", magic);
}
free(comp_Prebuf.data);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_3207_0 |
crossvul-cpp_data_bad_468_0 | /*
* MPEG-4 decoder
* Copyright (c) 2000,2001 Fabrice Bellard
* Copyright (c) 2002-2010 Michael Niedermayer <michaelni@gmx.at>
*
* 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 UNCHECKED_BITSTREAM_READER 1
#include "libavutil/internal.h"
#include "libavutil/opt.h"
#include "error_resilience.h"
#include "hwaccel.h"
#include "idctdsp.h"
#include "internal.h"
#include "mpegutils.h"
#include "mpegvideo.h"
#include "mpegvideodata.h"
#include "mpeg4video.h"
#include "h263.h"
#include "profiles.h"
#include "thread.h"
#include "xvididct.h"
/* The defines below define the number of bits that are read at once for
* reading vlc values. Changing these may improve speed and data cache needs
* be aware though that decreasing them may need the number of stages that is
* passed to get_vlc* to be increased. */
#define SPRITE_TRAJ_VLC_BITS 6
#define DC_VLC_BITS 9
#define MB_TYPE_B_VLC_BITS 4
#define STUDIO_INTRA_BITS 9
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb);
static VLC dc_lum, dc_chrom;
static VLC sprite_trajectory;
static VLC mb_type_b_vlc;
static const int mb_type_b_map[4] = {
MB_TYPE_DIRECT2 | MB_TYPE_L0L1,
MB_TYPE_L0L1 | MB_TYPE_16x16,
MB_TYPE_L1 | MB_TYPE_16x16,
MB_TYPE_L0 | MB_TYPE_16x16,
};
/**
* Predict the ac.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir the ac prediction direction
*/
void ff_mpeg4_pred_ac(MpegEncContext *s, int16_t *block, int n, int dir)
{
int i;
int16_t *ac_val, *ac_val1;
int8_t *const qscale_table = s->current_picture.qscale_table;
/* find prediction */
ac_val = &s->ac_val[0][0][0] + s->block_index[n] * 16;
ac_val1 = ac_val;
if (s->ac_pred) {
if (dir == 0) {
const int xy = s->mb_x - 1 + s->mb_y * s->mb_stride;
/* left prediction */
ac_val -= 16;
if (s->mb_x == 0 || s->qscale == qscale_table[xy] ||
n == 1 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ac_val[i];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i << 3]] += ROUNDED_DIV(ac_val[i] * qscale_table[xy], s->qscale);
}
} else {
const int xy = s->mb_x + s->mb_y * s->mb_stride - s->mb_stride;
/* top prediction */
ac_val -= 16 * s->block_wrap[n];
if (s->mb_y == 0 || s->qscale == qscale_table[xy] ||
n == 2 || n == 3) {
/* same qscale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ac_val[i + 8];
} else {
/* different qscale, we must rescale */
for (i = 1; i < 8; i++)
block[s->idsp.idct_permutation[i]] += ROUNDED_DIV(ac_val[i + 8] * qscale_table[xy], s->qscale);
}
}
}
/* left copy */
for (i = 1; i < 8; i++)
ac_val1[i] = block[s->idsp.idct_permutation[i << 3]];
/* top copy */
for (i = 1; i < 8; i++)
ac_val1[8 + i] = block[s->idsp.idct_permutation[i]];
}
/**
* check if the next stuff is a resync marker or the end.
* @return 0 if not
*/
static inline int mpeg4_is_resync(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int bits_count = get_bits_count(&s->gb);
int v = show_bits(&s->gb, 16);
if (s->workaround_bugs & FF_BUG_NO_PADDING && !ctx->resync_marker)
return 0;
while (v <= 0xFF) {
if (s->pict_type == AV_PICTURE_TYPE_B ||
(v >> (8 - s->pict_type) != 1) || s->partitioned_frame)
break;
skip_bits(&s->gb, 8 + s->pict_type);
bits_count += 8 + s->pict_type;
v = show_bits(&s->gb, 16);
}
if (bits_count + 8 >= s->gb.size_in_bits) {
v >>= 8;
v |= 0x7F >> (7 - (bits_count & 7));
if (v == 0x7F)
return s->mb_num;
} else {
if (v == ff_mpeg4_resync_prefix[bits_count & 7]) {
int len, mb_num;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
GetBitContext gb = s->gb;
skip_bits(&s->gb, 1);
align_get_bits(&s->gb);
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
mb_num = get_bits(&s->gb, mb_num_bits);
if (!mb_num || mb_num > s->mb_num || get_bits_count(&s->gb)+6 > s->gb.size_in_bits)
mb_num= -1;
s->gb = gb;
if (len >= ff_mpeg4_get_video_packet_prefix_length(s))
return mb_num;
}
}
return 0;
}
static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int a = 2 << s->sprite_warping_accuracy;
int rho = 3 - s->sprite_warping_accuracy;
int r = 16 / a;
int alpha = 1;
int beta = 0;
int w = s->width;
int h = s->height;
int min_ab, i, w2, h2, w3, h3;
int sprite_ref[4][2];
int virtual_ref[2][2];
int64_t sprite_offset[2][2];
int64_t sprite_delta[2][2];
// only true for rectangle shapes
const int vop_ref[4][2] = { { 0, 0 }, { s->width, 0 },
{ 0, s->height }, { s->width, s->height } };
int d[4][2] = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
if (w <= 0 || h <= 0)
return AVERROR_INVALIDDATA;
/* the decoder was not properly initialized and we cannot continue */
if (sprite_trajectory.table == NULL)
return AVERROR_INVALIDDATA;
for (i = 0; i < ctx->num_sprite_warping_points; i++) {
int length;
int x = 0, y = 0;
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
x = get_xbits(gb, length);
if (!(ctx->divx_version == 500 && ctx->divx_build == 413))
check_marker(s->avctx, gb, "before sprite_trajectory");
length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);
if (length > 0)
y = get_xbits(gb, length);
check_marker(s->avctx, gb, "after sprite_trajectory");
ctx->sprite_traj[i][0] = d[i][0] = x;
ctx->sprite_traj[i][1] = d[i][1] = y;
}
for (; i < 4; i++)
ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;
while ((1 << alpha) < w)
alpha++;
while ((1 << beta) < h)
beta++; /* typo in the MPEG-4 std for the definition of w' and h' */
w2 = 1 << alpha;
h2 = 1 << beta;
// Note, the 4th point isn't used for GMC
if (ctx->divx_version == 500 && ctx->divx_build == 413) {
sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];
sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];
sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];
sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];
sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];
sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];
} else {
sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);
sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);
sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);
sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);
sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);
sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);
}
/* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);
* sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */
/* This is mostly identical to the MPEG-4 std (and is totally unreadable
* because of that...). Perhaps it should be reordered to be more readable.
* The idea behind this virtual_ref mess is to be able to use shifts later
* per pixel instead of divides so the distance between points is converted
* from w&h based to w2&h2 based which are of the 2^x form. */
virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
w2 * (r * sprite_ref[1][0] - 16LL * vop_ref[1][0])), w);
virtual_ref[0][1] = 16 * vop_ref[0][1] +
ROUNDED_DIV(((w - w2) *
(r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
w2 * (r * sprite_ref[1][1] - 16LL * vop_ref[1][1])), w);
virtual_ref[1][0] = 16 * vop_ref[0][0] +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16LL * vop_ref[0][0]) +
h2 * (r * sprite_ref[2][0] - 16LL * vop_ref[2][0])), h);
virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +
ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16LL * vop_ref[0][1]) +
h2 * (r * sprite_ref[2][1] - 16LL * vop_ref[2][1])), h);
switch (ctx->num_sprite_warping_points) {
case 0:
sprite_offset[0][0] =
sprite_offset[0][1] =
sprite_offset[1][0] =
sprite_offset[1][1] = 0;
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 1: // GMC only
sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];
sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];
sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -
a * (vop_ref[0][0] / 2);
sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -
a * (vop_ref[0][1] / 2);
sprite_delta[0][0] = a;
sprite_delta[0][1] =
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] =
ctx->sprite_shift[1] = 0;
break;
case 2:
sprite_offset[0][0] = ((int64_t) sprite_ref[0][0] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[0][1] = ((int64_t) sprite_ref[0][1] * (1 << alpha + rho)) +
((int64_t) -r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t) -vop_ref[0][0]) +
((int64_t) -r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t) -vop_ref[0][1]) + (1 << (alpha + rho - 1));
sprite_offset[1][0] = (((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t) r * sprite_ref[0][1] - virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_offset[1][1] = (((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) *
((int64_t)-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) *
((int64_t)-2 * vop_ref[0][1] + 1) + 2 * w2 * r *
(int64_t) sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));
sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);
sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);
sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);
ctx->sprite_shift[0] = alpha + rho;
ctx->sprite_shift[1] = alpha + rho + 2;
break;
case 3:
min_ab = FFMIN(alpha, beta);
w3 = w2 >> min_ab;
h3 = h2 >> min_ab;
sprite_offset[0][0] = ((int64_t)sprite_ref[0][0] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[0][1] = ((int64_t)sprite_ref[0][1] * (1 << (alpha + beta + rho - min_ab))) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-vop_ref[0][0]) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-vop_ref[0][1]) +
((int64_t)1 << (alpha + beta + rho - min_ab - 1));
sprite_offset[1][0] = ((int64_t)-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][0] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_offset[1][1] = ((int64_t)-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3 * (-2 * vop_ref[0][0] + 1) +
((int64_t)-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3 * (-2 * vop_ref[0][1] + 1) +
(int64_t)2 * w2 * h3 * r * sprite_ref[0][1] - 16 * w2 * h3 +
((int64_t)1 << (alpha + beta + rho - min_ab + 1));
sprite_delta[0][0] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[0][0]) * h3;
sprite_delta[0][1] = (-r * (int64_t)sprite_ref[0][0] + virtual_ref[1][0]) * w3;
sprite_delta[1][0] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[0][1]) * h3;
sprite_delta[1][1] = (-r * (int64_t)sprite_ref[0][1] + virtual_ref[1][1]) * w3;
ctx->sprite_shift[0] = alpha + beta + rho - min_ab;
ctx->sprite_shift[1] = alpha + beta + rho - min_ab + 2;
break;
}
/* try to simplify the situation */
if (sprite_delta[0][0] == a << ctx->sprite_shift[0] &&
sprite_delta[0][1] == 0 &&
sprite_delta[1][0] == 0 &&
sprite_delta[1][1] == a << ctx->sprite_shift[0]) {
sprite_offset[0][0] >>= ctx->sprite_shift[0];
sprite_offset[0][1] >>= ctx->sprite_shift[0];
sprite_offset[1][0] >>= ctx->sprite_shift[1];
sprite_offset[1][1] >>= ctx->sprite_shift[1];
sprite_delta[0][0] = a;
sprite_delta[0][1] = 0;
sprite_delta[1][0] = 0;
sprite_delta[1][1] = a;
ctx->sprite_shift[0] = 0;
ctx->sprite_shift[1] = 0;
s->real_sprite_warping_points = 1;
} else {
int shift_y = 16 - ctx->sprite_shift[0];
int shift_c = 16 - ctx->sprite_shift[1];
for (i = 0; i < 2; i++) {
if (shift_c < 0 || shift_y < 0 ||
FFABS( sprite_offset[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_offset[1][i]) >= INT_MAX >> shift_c ||
FFABS( sprite_delta[0][i]) >= INT_MAX >> shift_y ||
FFABS( sprite_delta[1][i]) >= INT_MAX >> shift_y
) {
avpriv_request_sample(s->avctx, "Too large sprite shift, delta or offset");
goto overflow;
}
}
for (i = 0; i < 2; i++) {
sprite_offset[0][i] *= 1 << shift_y;
sprite_offset[1][i] *= 1 << shift_c;
sprite_delta[0][i] *= 1 << shift_y;
sprite_delta[1][i] *= 1 << shift_y;
ctx->sprite_shift[i] = 16;
}
for (i = 0; i < 2; i++) {
int64_t sd[2] = {
sprite_delta[i][0] - a * (1LL<<16),
sprite_delta[i][1] - a * (1LL<<16)
};
if (llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sprite_delta[i][0] * (w+16LL) + sprite_delta[i][1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_delta[i][1] * (w+16LL)) >= INT_MAX ||
llabs(sd[0]) >= INT_MAX ||
llabs(sd[1]) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[1] * (h+16LL)) >= INT_MAX ||
llabs(sprite_offset[0][i] + sd[0] * (w+16LL) + sd[1] * (h+16LL)) >= INT_MAX
) {
avpriv_request_sample(s->avctx, "Overflow on sprite points");
goto overflow;
}
}
s->real_sprite_warping_points = ctx->num_sprite_warping_points;
}
for (i = 0; i < 4; i++) {
s->sprite_offset[i&1][i>>1] = sprite_offset[i&1][i>>1];
s->sprite_delta [i&1][i>>1] = sprite_delta [i&1][i>>1];
}
return 0;
overflow:
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
return AVERROR_PATCHWELCOME;
}
static int decode_new_pred(Mpeg4DecContext *ctx, GetBitContext *gb) {
MpegEncContext *s = &ctx->m;
int len = FFMIN(ctx->time_increment_bits + 3, 15);
get_bits(gb, len);
if (get_bits1(gb))
get_bits(gb, len);
check_marker(s->avctx, gb, "after new_pred");
return 0;
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_video_packet_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num_bits = av_log2(s->mb_num - 1) + 1;
int header_extension = 0, mb_num, len;
/* is there enough space left for a video packet + header */
if (get_bits_count(&s->gb) > s->gb.size_in_bits - 20)
return AVERROR_INVALIDDATA;
for (len = 0; len < 32; len++)
if (get_bits1(&s->gb))
break;
if (len != ff_mpeg4_get_video_packet_prefix_length(s)) {
av_log(s->avctx, AV_LOG_ERROR, "marker does not match f_code\n");
return AVERROR_INVALIDDATA;
}
if (ctx->shape != RECT_SHAPE) {
header_extension = get_bits1(&s->gb);
// FIXME more stuff here
}
mb_num = get_bits(&s->gb, mb_num_bits);
if (mb_num >= s->mb_num || !mb_num) {
av_log(s->avctx, AV_LOG_ERROR,
"illegal mb_num in video packet (%d %d) \n", mb_num, s->mb_num);
return AVERROR_INVALIDDATA;
}
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE) {
int qscale = get_bits(&s->gb, s->quant_precision);
if (qscale)
s->chroma_qscale = s->qscale = qscale;
}
if (ctx->shape == RECT_SHAPE)
header_extension = get_bits1(&s->gb);
if (header_extension) {
int time_incr = 0;
while (get_bits1(&s->gb) != 0)
time_incr++;
check_marker(s->avctx, &s->gb, "before time_increment in video packed header");
skip_bits(&s->gb, ctx->time_increment_bits); /* time_increment */
check_marker(s->avctx, &s->gb, "before vop_coding_type in video packed header");
skip_bits(&s->gb, 2); /* vop coding type */
// FIXME not rect stuff here
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits(&s->gb, 3); /* intra dc vlc threshold */
// FIXME don't just ignore everything
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
if (mpeg4_decode_sprite_trajectory(ctx, &s->gb) < 0)
return AVERROR_INVALIDDATA;
av_log(s->avctx, AV_LOG_ERROR, "untested\n");
}
// FIXME reduced res stuff here
if (s->pict_type != AV_PICTURE_TYPE_I) {
int f_code = get_bits(&s->gb, 3); /* fcode_for */
if (f_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (f_code=0)\n");
}
if (s->pict_type == AV_PICTURE_TYPE_B) {
int b_code = get_bits(&s->gb, 3);
if (b_code == 0)
av_log(s->avctx, AV_LOG_ERROR,
"Error, video packet header damaged (b_code=0)\n");
}
}
}
if (ctx->new_pred)
decode_new_pred(ctx, &s->gb);
return 0;
}
static void reset_studio_dc_predictors(MpegEncContext *s)
{
/* Reset DC Predictors */
s->last_dc[0] =
s->last_dc[1] =
s->last_dc[2] = 1 << (s->avctx->bits_per_raw_sample + s->dct_precision + s->intra_dc_precision - 1);
}
/**
* Decode the next video packet.
* @return <0 if something went wrong
*/
int ff_mpeg4_decode_studio_slice_header(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
GetBitContext *gb = &s->gb;
unsigned vlc_len;
uint16_t mb_num;
if (get_bits_left(gb) >= 32 && get_bits_long(gb, 32) == SLICE_START_CODE) {
vlc_len = av_log2(s->mb_width * s->mb_height) + 1;
mb_num = get_bits(gb, vlc_len);
if (mb_num >= s->mb_num)
return AVERROR_INVALIDDATA;
s->mb_x = mb_num % s->mb_width;
s->mb_y = mb_num / s->mb_width;
if (ctx->shape != BIN_ONLY_SHAPE)
s->qscale = mpeg_get_qscale(s);
if (get_bits1(gb)) { /* slice_extension_flag */
skip_bits1(gb); /* intra_slice */
skip_bits1(gb); /* slice_VOP_id_enable */
skip_bits(gb, 6); /* slice_VOP_id */
while (get_bits1(gb)) /* extra_bit_slice */
skip_bits(gb, 8); /* extra_information_slice */
}
reset_studio_dc_predictors(s);
}
else {
return AVERROR_INVALIDDATA;
}
return 0;
}
/**
* Get the average motion vector for a GMC MB.
* @param n either 0 for the x component or 1 for y
* @return the average MV for a GMC MB
*/
static inline int get_amv(Mpeg4DecContext *ctx, int n)
{
MpegEncContext *s = &ctx->m;
int x, y, mb_v, sum, dx, dy, shift;
int len = 1 << (s->f_code + 4);
const int a = s->sprite_warping_accuracy;
if (s->workaround_bugs & FF_BUG_AMV)
len >>= s->quarter_sample;
if (s->real_sprite_warping_points == 1) {
if (ctx->divx_version == 500 && ctx->divx_build == 413)
sum = s->sprite_offset[0][n] / (1 << (a - s->quarter_sample));
else
sum = RSHIFT(s->sprite_offset[0][n] * (1 << s->quarter_sample), a);
} else {
dx = s->sprite_delta[n][0];
dy = s->sprite_delta[n][1];
shift = ctx->sprite_shift[0];
if (n)
dy -= 1 << (shift + a + 1);
else
dx -= 1 << (shift + a + 1);
mb_v = s->sprite_offset[0][n] + dx * s->mb_x * 16 + dy * s->mb_y * 16;
sum = 0;
for (y = 0; y < 16; y++) {
int v;
v = mb_v + dy * y;
// FIXME optimize
for (x = 0; x < 16; x++) {
sum += v >> shift;
v += dx;
}
}
sum = RSHIFT(sum, a + 8 - s->quarter_sample);
}
if (sum < -len)
sum = -len;
else if (sum >= len)
sum = len - 1;
return sum;
}
/**
* Decode the dc value.
* @param n block index (0-3 are luma, 4-5 are chroma)
* @param dir_ptr the prediction direction will be stored here
* @return the quantized dc
*/
static inline int mpeg4_decode_dc(MpegEncContext *s, int n, int *dir_ptr)
{
int level, code;
if (n < 4)
code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);
else
code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);
if (code < 0 || code > 9 /* && s->nbit < 9 */) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dc vlc\n");
return AVERROR_INVALIDDATA;
}
if (code == 0) {
level = 0;
} else {
if (IS_3IV1) {
if (code == 1)
level = 2 * get_bits1(&s->gb) - 1;
else {
if (get_bits1(&s->gb))
level = get_bits(&s->gb, code - 1) + (1 << (code - 1));
else
level = -get_bits(&s->gb, code - 1) - (1 << (code - 1));
}
} else {
level = get_xbits(&s->gb, code);
}
if (code > 8) {
if (get_bits1(&s->gb) == 0) { /* marker */
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_COMPLIANT)) {
av_log(s->avctx, AV_LOG_ERROR, "dc marker bit missing\n");
return AVERROR_INVALIDDATA;
}
}
}
}
return ff_mpeg4_pred_dc(s, n, level, dir_ptr, 0);
}
/**
* Decode first partition.
* @return number of MBs decoded or <0 if an error occurred
*/
static int mpeg4_decode_partition_a(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
/* decode first partition */
s->first_slice_line = 1;
for (; s->mb_y < s->mb_height; s->mb_y++) {
ff_init_block_index(s);
for (; s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
int cbpc;
int dir = 0;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int i;
do {
if (show_bits_long(&s->gb, 19) == DC_MARKER)
return mb_num - 1;
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
s->cbp_table[xy] = cbpc & 3;
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mb_intra = 1;
if (cbpc & 4)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->mbintra_table[xy] = 1;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->pred_dir_table[xy] = dir;
} else { /* P/S_TYPE */
int mx, my, pred_x, pred_y, bits;
int16_t *const mot_val = s->current_picture.motion_val[0][s->block_index[0]];
const int stride = s->b8_stride * 2;
try_again:
bits = show_bits(&s->gb, 17);
if (bits == MOTION_MARKER)
return mb_num - 1;
skip_bits1(&s->gb);
if (bits & 0x10000) {
/* skip mb */
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
mx = my = 0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
continue;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (cbpc == 20)
goto try_again;
s->cbp_table[xy] = cbpc & (8 + 3); // 8 is dquant
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra) {
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
s->mbintra_table[xy] = 1;
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = 0;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = 0;
} else {
if (s->mbintra_table[xy])
ff_clean_intra_table_entries(s);
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE &&
(cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
if ((cbpc & 16) == 0) {
/* 16x16 motion prediction */
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
if (!s->mcsel) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_L0;
} else {
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->current_picture.mb_type[xy] = MB_TYPE_16x16 |
MB_TYPE_GMC |
MB_TYPE_L0;
}
mot_val[0] =
mot_val[2] =
mot_val[0 + stride] =
mot_val[2 + stride] = mx;
mot_val[1] =
mot_val[3] =
mot_val[1 + stride] =
mot_val[3 + stride] = my;
} else {
int i;
s->current_picture.mb_type[xy] = MB_TYPE_8x8 |
MB_TYPE_L0;
for (i = 0; i < 4; i++) {
int16_t *mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
mot_val[0] = mx;
mot_val[1] = my;
}
}
}
}
}
s->mb_x = 0;
}
return mb_num;
}
/**
* decode second partition.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partition_b(MpegEncContext *s, int mb_count)
{
int mb_num = 0;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
s->mb_x = s->resync_mb_x;
s->first_slice_line = 1;
for (s->mb_y = s->resync_mb_y; mb_num < mb_count; s->mb_y++) {
ff_init_block_index(s);
for (; mb_num < mb_count && s->mb_x < s->mb_width; s->mb_x++) {
const int xy = s->mb_x + s->mb_y * s->mb_stride;
mb_num++;
ff_update_block_index(s);
if (s->mb_x == s->resync_mb_x && s->mb_y == s->resync_mb_y + 1)
s->first_slice_line = 0;
if (s->pict_type == AV_PICTURE_TYPE_I) {
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
} else { /* P || S_TYPE */
if (IS_INTRA(s->current_picture.mb_type[xy])) {
int i;
int dir = 0;
int ac_pred = get_bits1(&s->gb);
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
for (i = 0; i < 6; i++) {
int dc_pred_dir;
int dc = mpeg4_decode_dc(s, i, &dc_pred_dir);
if (dc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"DC corrupted at %d %d\n", s->mb_x, s->mb_y);
return dc;
}
dir <<= 1;
if (dc_pred_dir)
dir |= 1;
}
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= cbpy << 2;
s->current_picture.mb_type[xy] |= ac_pred * MB_TYPE_ACPRED;
s->pred_dir_table[xy] = dir;
} else if (IS_SKIP(s->current_picture.mb_type[xy])) {
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] = 0;
} else {
int cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy corrupted at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
if (s->cbp_table[xy] & 8)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
s->current_picture.qscale_table[xy] = s->qscale;
s->cbp_table[xy] &= 3; // remove dquant
s->cbp_table[xy] |= (cbpy ^ 0xf) << 2;
}
}
}
if (mb_num >= mb_count)
return 0;
s->mb_x = 0;
}
return 0;
}
/**
* Decode the first and second partition.
* @return <0 if error (and sets error type in the error_status_table)
*/
int ff_mpeg4_decode_partitions(Mpeg4DecContext *ctx)
{
MpegEncContext *s = &ctx->m;
int mb_num;
int ret;
const int part_a_error = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_ERROR | ER_MV_ERROR) : ER_MV_ERROR;
const int part_a_end = s->pict_type == AV_PICTURE_TYPE_I ? (ER_DC_END | ER_MV_END) : ER_MV_END;
mb_num = mpeg4_decode_partition_a(ctx);
if (mb_num <= 0) {
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return mb_num ? mb_num : AVERROR_INVALIDDATA;
}
if (s->resync_mb_x + s->resync_mb_y * s->mb_width + mb_num > s->mb_num) {
av_log(s->avctx, AV_LOG_ERROR, "slice below monitor ...\n");
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, part_a_error);
return AVERROR_INVALIDDATA;
}
s->mb_num_left = mb_num;
if (s->pict_type == AV_PICTURE_TYPE_I) {
while (show_bits(&s->gb, 9) == 1)
skip_bits(&s->gb, 9);
if (get_bits_long(&s->gb, 19) != DC_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first I partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} else {
while (show_bits(&s->gb, 10) == 1)
skip_bits(&s->gb, 10);
if (get_bits(&s->gb, 17) != MOTION_MARKER) {
av_log(s->avctx, AV_LOG_ERROR,
"marker missing after first P partition at %d %d\n",
s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
}
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, part_a_end);
ret = mpeg4_decode_partition_b(s, mb_num);
if (ret < 0) {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x, s->mb_y, ER_DC_ERROR);
return ret;
} else {
if (s->pict_type == AV_PICTURE_TYPE_P)
ff_er_add_slice(&s->er, s->resync_mb_x, s->resync_mb_y,
s->mb_x - 1, s->mb_y, ER_DC_END);
}
return 0;
}
/**
* Decode a block.
* @return <0 if an error occurred
*/
static inline int mpeg4_decode_block(Mpeg4DecContext *ctx, int16_t *block,
int n, int coded, int intra, int rvlc)
{
MpegEncContext *s = &ctx->m;
int level, i, last, run, qmul, qadd;
int av_uninit(dc_pred_dir);
RLTable *rl;
RL_VLC_ELEM *rl_vlc;
const uint8_t *scan_table;
// Note intra & rvlc should be optimized away if this is inlined
if (intra) {
if (ctx->use_intra_dc_vlc) {
/* DC coef */
if (s->partitioned_frame) {
level = s->dc_val[0][s->block_index[n]];
if (n < 4)
level = FASTDIV((level + (s->y_dc_scale >> 1)), s->y_dc_scale);
else
level = FASTDIV((level + (s->c_dc_scale >> 1)), s->c_dc_scale);
dc_pred_dir = (s->pred_dir_table[s->mb_x + s->mb_y * s->mb_stride] << n) & 32;
} else {
level = mpeg4_decode_dc(s, n, &dc_pred_dir);
if (level < 0)
return level;
}
block[0] = level;
i = 0;
} else {
i = -1;
ff_mpeg4_pred_dc(s, n, 0, &dc_pred_dir, 0);
}
if (!coded)
goto not_coded;
if (rvlc) {
rl = &ff_rvlc_rl_intra;
rl_vlc = ff_rvlc_rl_intra.rl_vlc[0];
} else {
rl = &ff_mpeg4_rl_intra;
rl_vlc = ff_mpeg4_rl_intra.rl_vlc[0];
}
if (s->ac_pred) {
if (dc_pred_dir == 0)
scan_table = s->intra_v_scantable.permutated; /* left */
else
scan_table = s->intra_h_scantable.permutated; /* top */
} else {
scan_table = s->intra_scantable.permutated;
}
qmul = 1;
qadd = 0;
} else {
i = -1;
if (!coded) {
s->block_last_index[n] = i;
return 0;
}
if (rvlc)
rl = &ff_rvlc_rl_inter;
else
rl = &ff_h263_rl_inter;
scan_table = s->intra_scantable.permutated;
if (s->mpeg_quant) {
qmul = 1;
qadd = 0;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[0];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[0];
} else {
qmul = s->qscale << 1;
qadd = (s->qscale - 1) | 1;
if (rvlc)
rl_vlc = ff_rvlc_rl_inter.rl_vlc[s->qscale];
else
rl_vlc = ff_h263_rl_inter.rl_vlc[s->qscale];
}
}
{
OPEN_READER(re, &s->gb);
for (;;) {
UPDATE_CACHE(re, &s->gb);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);
if (level == 0) {
/* escape */
if (rvlc) {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 1 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in rvlc esc\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_UBITS(re, &s->gb, 11);
SKIP_CACHE(re, &s->gb, 11);
if (SHOW_UBITS(re, &s->gb, 5) != 0x10) {
av_log(s->avctx, AV_LOG_ERROR, "reverse esc missing\n");
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 5);
level = level * qmul + qadd;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
SKIP_COUNTER(re, &s->gb, 1 + 11 + 5 + 1);
i += run + 1;
if (last)
i += 192;
} else {
int cache;
cache = GET_CACHE(re, &s->gb);
if (IS_3IV1)
cache ^= 0xC0000000;
if (cache & 0x80000000) {
if (cache & 0x40000000) {
/* third escape */
SKIP_CACHE(re, &s->gb, 2);
last = SHOW_UBITS(re, &s->gb, 1);
SKIP_CACHE(re, &s->gb, 1);
run = SHOW_UBITS(re, &s->gb, 6);
SKIP_COUNTER(re, &s->gb, 2 + 1 + 6);
UPDATE_CACHE(re, &s->gb);
if (IS_3IV1) {
level = SHOW_SBITS(re, &s->gb, 12);
LAST_SKIP_BITS(re, &s->gb, 12);
} else {
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"1. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_CACHE(re, &s->gb, 1);
level = SHOW_SBITS(re, &s->gb, 12);
SKIP_CACHE(re, &s->gb, 12);
if (SHOW_UBITS(re, &s->gb, 1) == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"2. marker bit missing in 3. esc\n");
if (!(s->avctx->err_recognition & AV_EF_IGNORE_ERR))
return AVERROR_INVALIDDATA;
}
SKIP_COUNTER(re, &s->gb, 1 + 12 + 1);
}
#if 0
if (s->error_recognition >= FF_ER_COMPLIANT) {
const int abs_level= FFABS(level);
if (abs_level<=MAX_LEVEL && run<=MAX_RUN) {
const int run1= run - rl->max_run[last][abs_level] - 1;
if (abs_level <= rl->max_level[last][run]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (s->error_recognition > FF_ER_COMPLIANT) {
if (abs_level <= rl->max_level[last][run]*2) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");
return AVERROR_INVALIDDATA;
}
if (run1 >= 0 && abs_level <= rl->max_level[last][run1]) {
av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");
return AVERROR_INVALIDDATA;
}
}
}
}
#endif
if (level > 0)
level = level * qmul + qadd;
else
level = level * qmul - qadd;
if ((unsigned)(level + 2048) > 4095) {
if (s->avctx->err_recognition & (AV_EF_BITSTREAM|AV_EF_AGGRESSIVE)) {
if (level > 2560 || level < -2560) {
av_log(s->avctx, AV_LOG_ERROR,
"|level| overflow in 3. esc, qp=%d\n",
s->qscale);
return AVERROR_INVALIDDATA;
}
}
level = level < 0 ? -2048 : 2047;
}
i += run + 1;
if (last)
i += 192;
} else {
/* second escape */
SKIP_BITS(re, &s->gb, 2);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run + rl->max_run[run >> 7][level / qmul] + 1; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
} else {
/* first escape */
SKIP_BITS(re, &s->gb, 1);
GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);
i += run;
level = level + rl->max_level[run >> 7][(run - 1) & 63] * qmul; // FIXME opt indexing
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
}
} else {
i += run;
level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);
LAST_SKIP_BITS(re, &s->gb, 1);
}
ff_tlog(s->avctx, "dct[%d][%d] = %- 4d end?:%d\n", scan_table[i&63]&7, scan_table[i&63] >> 3, level, i>62);
if (i > 62) {
i -= 192;
if (i & (~63)) {
av_log(s->avctx, AV_LOG_ERROR,
"ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
block[scan_table[i]] = level;
break;
}
block[scan_table[i]] = level;
}
CLOSE_READER(re, &s->gb);
}
not_coded:
if (intra) {
if (!ctx->use_intra_dc_vlc) {
block[0] = ff_mpeg4_pred_dc(s, n, block[0], &dc_pred_dir, 0);
i -= i >> 31; // if (i == -1) i = 0;
}
ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);
if (s->ac_pred)
i = 63; // FIXME not optimal
}
s->block_last_index[n] = i;
return 0;
}
/**
* decode partition C of one MB.
* @return <0 if an error occurred
*/
static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbp, mb_type;
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
mb_type = s->current_picture.mb_type[xy];
cbp = s->cbp_table[xy];
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (s->current_picture.qscale_table[xy] != s->qscale)
ff_set_qscale(s, s->current_picture.qscale_table[xy]);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
int i;
for (i = 0; i < 4; i++) {
s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0];
s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1];
}
s->mb_intra = IS_INTRA(mb_type);
if (IS_SKIP(mb_type)) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S
&& ctx->vol_sprite_usage == GMC_SPRITE) {
s->mcsel = 1;
s->mb_skipped = 0;
} else {
s->mcsel = 0;
s->mb_skipped = 1;
}
} else if (s->mb_intra) {
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
} else if (!s->mb_intra) {
// s->mcsel = 0; // FIXME do we need to init that?
s->mv_dir = MV_DIR_FORWARD;
if (IS_8X8(mb_type)) {
s->mv_type = MV_TYPE_8X8;
} else {
s->mv_type = MV_TYPE_16X16;
}
}
} else { /* I-Frame */
s->mb_intra = 1;
s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]);
}
if (!IS_SKIP(mb_type)) {
int i;
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"texture corrupted at %d %d %d\n",
s->mb_x, s->mb_y, s->mb_intra);
return AVERROR_INVALIDDATA;
}
cbp += cbp;
}
}
/* per-MB end of slice check */
if (--s->mb_num_left <= 0) {
if (mpeg4_is_resync(ctx))
return SLICE_END;
else
return SLICE_NOEND;
} else {
if (mpeg4_is_resync(ctx)) {
const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1;
if (s->cbp_table[xy + delta])
return SLICE_END;
}
return SLICE_OK;
}
}
static int mpeg4_decode_mb(MpegEncContext *s, int16_t block[6][64])
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cbpc, cbpy, i, cbp, pred_x, pred_y, mx, my, dquant;
int16_t *mot_val;
static const int8_t quant_tab[4] = { -1, -2, 1, 2 };
const int xy = s->mb_x + s->mb_y * s->mb_stride;
av_assert2(s == (void*)ctx);
av_assert2(s->h263_pred);
if (s->pict_type == AV_PICTURE_TYPE_P ||
s->pict_type == AV_PICTURE_TYPE_S) {
do {
if (get_bits1(&s->gb)) {
/* skip mb */
s->mb_intra = 0;
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE) {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 1;
s->mv[0][0][0] = get_amv(ctx, 0);
s->mv[0][0][1] = get_amv(ctx, 1);
s->mb_skipped = 0;
} else {
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
s->mcsel = 0;
s->mv[0][0][0] = 0;
s->mv[0][0][1] = 0;
s->mb_skipped = 1;
}
goto end;
}
cbpc = get_vlc2(&s->gb, ff_h263_inter_MCBPC_vlc.table, INTER_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"mcbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 20);
s->bdsp.clear_blocks(s->block[0]);
dquant = cbpc & 8;
s->mb_intra = ((cbpc & 4) != 0);
if (s->mb_intra)
goto intra;
if (s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE && (cbpc & 16) == 0)
s->mcsel = get_bits1(&s->gb);
else
s->mcsel = 0;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1) ^ 0x0F;
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"P cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if ((!s->progressive_sequence) &&
(cbp || (s->workaround_bugs & FF_BUG_XVID_ILACE)))
s->interlaced_dct = get_bits1(&s->gb);
s->mv_dir = MV_DIR_FORWARD;
if ((cbpc & 16) == 0) {
if (s->mcsel) {
s->current_picture.mb_type[xy] = MB_TYPE_GMC |
MB_TYPE_16x16 |
MB_TYPE_L0;
/* 16x16 global motion prediction */
s->mv_type = MV_TYPE_16X16;
mx = get_amv(ctx, 0);
my = get_amv(ctx, 1);
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
} else if ((!s->progressive_sequence) && get_bits1(&s->gb)) {
s->current_picture.mb_type[xy] = MB_TYPE_16x8 |
MB_TYPE_L0 |
MB_TYPE_INTERLACED;
/* 16x8 field motion prediction */
s->mv_type = MV_TYPE_FIELD;
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y / 2, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_16x16 | MB_TYPE_L0;
/* 16x16 motion prediction */
s->mv_type = MV_TYPE_16X16;
ff_h263_pred_motion(s, 0, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][0][0] = mx;
s->mv[0][0][1] = my;
}
} else {
s->current_picture.mb_type[xy] = MB_TYPE_8x8 | MB_TYPE_L0;
s->mv_type = MV_TYPE_8X8;
for (i = 0; i < 4; i++) {
mot_val = ff_h263_pred_motion(s, i, 0, &pred_x, &pred_y);
mx = ff_h263_decode_motion(s, pred_x, s->f_code);
if (mx >= 0xffff)
return AVERROR_INVALIDDATA;
my = ff_h263_decode_motion(s, pred_y, s->f_code);
if (my >= 0xffff)
return AVERROR_INVALIDDATA;
s->mv[0][i][0] = mx;
s->mv[0][i][1] = my;
mot_val[0] = mx;
mot_val[1] = my;
}
}
} else if (s->pict_type == AV_PICTURE_TYPE_B) {
int modb1; // first bit of modb
int modb2; // second bit of modb
int mb_type;
s->mb_intra = 0; // B-frames never contain intra blocks
s->mcsel = 0; // ... true gmc blocks
if (s->mb_x == 0) {
for (i = 0; i < 2; i++) {
s->last_mv[i][0][0] =
s->last_mv[i][0][1] =
s->last_mv[i][1][0] =
s->last_mv[i][1][1] = 0;
}
ff_thread_await_progress(&s->next_picture_ptr->tf, s->mb_y, 0);
}
/* if we skipped it in the future P-frame than skip it now too */
s->mb_skipped = s->next_picture.mbskip_table[s->mb_y * s->mb_stride + s->mb_x]; // Note, skiptab=0 if last was GMC
if (s->mb_skipped) {
/* skip mb */
for (i = 0; i < 6; i++)
s->block_last_index[i] = -1;
s->mv_dir = MV_DIR_FORWARD;
s->mv_type = MV_TYPE_16X16;
s->mv[0][0][0] =
s->mv[0][0][1] =
s->mv[1][0][0] =
s->mv[1][0][1] = 0;
s->current_picture.mb_type[xy] = MB_TYPE_SKIP |
MB_TYPE_16x16 |
MB_TYPE_L0;
goto end;
}
modb1 = get_bits1(&s->gb);
if (modb1) {
// like MB_TYPE_B_DIRECT but no vectors coded
mb_type = MB_TYPE_DIRECT2 | MB_TYPE_SKIP | MB_TYPE_L0L1;
cbp = 0;
} else {
modb2 = get_bits1(&s->gb);
mb_type = get_vlc2(&s->gb, mb_type_b_vlc.table, MB_TYPE_B_VLC_BITS, 1);
if (mb_type < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal MB_type\n");
return AVERROR_INVALIDDATA;
}
mb_type = mb_type_b_map[mb_type];
if (modb2) {
cbp = 0;
} else {
s->bdsp.clear_blocks(s->block[0]);
cbp = get_bits(&s->gb, 6);
}
if ((!IS_DIRECT(mb_type)) && cbp) {
if (get_bits1(&s->gb))
ff_set_qscale(s, s->qscale + get_bits1(&s->gb) * 4 - 2);
}
if (!s->progressive_sequence) {
if (cbp)
s->interlaced_dct = get_bits1(&s->gb);
if (!IS_DIRECT(mb_type) && get_bits1(&s->gb)) {
mb_type |= MB_TYPE_16x8 | MB_TYPE_INTERLACED;
mb_type &= ~MB_TYPE_16x16;
if (USES_LIST(mb_type, 0)) {
s->field_select[0][0] = get_bits1(&s->gb);
s->field_select[0][1] = get_bits1(&s->gb);
}
if (USES_LIST(mb_type, 1)) {
s->field_select[1][0] = get_bits1(&s->gb);
s->field_select[1][1] = get_bits1(&s->gb);
}
}
}
s->mv_dir = 0;
if ((mb_type & (MB_TYPE_DIRECT2 | MB_TYPE_INTERLACED)) == 0) {
s->mv_type = MV_TYPE_16X16;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
mx = ff_h263_decode_motion(s, s->last_mv[0][0][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][0][1], s->f_code);
s->last_mv[0][1][0] =
s->last_mv[0][0][0] =
s->mv[0][0][0] = mx;
s->last_mv[0][1][1] =
s->last_mv[0][0][1] =
s->mv[0][0][1] = my;
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
mx = ff_h263_decode_motion(s, s->last_mv[1][0][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][0][1], s->b_code);
s->last_mv[1][1][0] =
s->last_mv[1][0][0] =
s->mv[1][0][0] = mx;
s->last_mv[1][1][1] =
s->last_mv[1][0][1] =
s->mv[1][0][1] = my;
}
} else if (!IS_DIRECT(mb_type)) {
s->mv_type = MV_TYPE_FIELD;
if (USES_LIST(mb_type, 0)) {
s->mv_dir = MV_DIR_FORWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[0][i][0], s->f_code);
my = ff_h263_decode_motion(s, s->last_mv[0][i][1] / 2, s->f_code);
s->last_mv[0][i][0] =
s->mv[0][i][0] = mx;
s->last_mv[0][i][1] = (s->mv[0][i][1] = my) * 2;
}
}
if (USES_LIST(mb_type, 1)) {
s->mv_dir |= MV_DIR_BACKWARD;
for (i = 0; i < 2; i++) {
mx = ff_h263_decode_motion(s, s->last_mv[1][i][0], s->b_code);
my = ff_h263_decode_motion(s, s->last_mv[1][i][1] / 2, s->b_code);
s->last_mv[1][i][0] =
s->mv[1][i][0] = mx;
s->last_mv[1][i][1] = (s->mv[1][i][1] = my) * 2;
}
}
}
}
if (IS_DIRECT(mb_type)) {
if (IS_SKIP(mb_type)) {
mx =
my = 0;
} else {
mx = ff_h263_decode_motion(s, 0, 1);
my = ff_h263_decode_motion(s, 0, 1);
}
s->mv_dir = MV_DIR_FORWARD | MV_DIR_BACKWARD | MV_DIRECT;
mb_type |= ff_mpeg4_set_direct_mv(s, mx, my);
}
s->current_picture.mb_type[xy] = mb_type;
} else { /* I-Frame */
do {
cbpc = get_vlc2(&s->gb, ff_h263_intra_MCBPC_vlc.table, INTRA_MCBPC_VLC_BITS, 2);
if (cbpc < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpc damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
} while (cbpc == 8);
dquant = cbpc & 4;
s->mb_intra = 1;
intra:
s->ac_pred = get_bits1(&s->gb);
if (s->ac_pred)
s->current_picture.mb_type[xy] = MB_TYPE_INTRA | MB_TYPE_ACPRED;
else
s->current_picture.mb_type[xy] = MB_TYPE_INTRA;
cbpy = get_vlc2(&s->gb, ff_h263_cbpy_vlc.table, CBPY_VLC_BITS, 1);
if (cbpy < 0) {
av_log(s->avctx, AV_LOG_ERROR,
"I cbpy damaged at %d %d\n", s->mb_x, s->mb_y);
return AVERROR_INVALIDDATA;
}
cbp = (cbpc & 3) | (cbpy << 2);
ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold;
if (dquant)
ff_set_qscale(s, s->qscale + quant_tab[get_bits(&s->gb, 2)]);
if (!s->progressive_sequence)
s->interlaced_dct = get_bits1(&s->gb);
s->bdsp.clear_blocks(s->block[0]);
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 1, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
goto end;
}
/* decode each block */
for (i = 0; i < 6; i++) {
if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, 0, 0) < 0)
return AVERROR_INVALIDDATA;
cbp += cbp;
}
end:
/* per-MB end of slice check */
if (s->codec_id == AV_CODEC_ID_MPEG4) {
int next = mpeg4_is_resync(ctx);
if (next) {
if (s->mb_x + s->mb_y*s->mb_width + 1 > next && (s->avctx->err_recognition & AV_EF_AGGRESSIVE)) {
return AVERROR_INVALIDDATA;
} else if (s->mb_x + s->mb_y*s->mb_width + 1 >= next)
return SLICE_END;
if (s->pict_type == AV_PICTURE_TYPE_B) {
const int delta= s->mb_x + 1 == s->mb_width ? 2 : 1;
ff_thread_await_progress(&s->next_picture_ptr->tf,
(s->mb_x + delta >= s->mb_width)
? FFMIN(s->mb_y + 1, s->mb_height - 1)
: s->mb_y, 0);
if (s->next_picture.mbskip_table[xy + delta])
return SLICE_OK;
}
return SLICE_END;
}
}
return SLICE_OK;
}
/* As per spec, studio start code search isn't the same as the old type of start code */
static void next_start_code_studio(GetBitContext *gb)
{
align_get_bits(gb);
while (get_bits_left(gb) >= 24 && show_bits_long(gb, 24) != 0x1) {
get_bits(gb, 8);
}
}
/* additional_code, vlc index */
static const uint8_t ac_state_tab[22][2] =
{
{0, 0},
{0, 1},
{1, 1},
{2, 1},
{3, 1},
{4, 1},
{5, 1},
{1, 2},
{2, 2},
{3, 2},
{4, 2},
{5, 2},
{6, 2},
{1, 3},
{2, 4},
{3, 5},
{4, 6},
{5, 7},
{6, 8},
{7, 9},
{8, 10},
{0, 11}
};
static int mpeg4_decode_studio_block(MpegEncContext *s, int32_t block[64], int n)
{
Mpeg4DecContext *ctx = s->avctx->priv_data;
int cc, dct_dc_size, dct_diff, code, j, idx = 1, group = 0, run = 0,
additional_code_len, sign, mismatch;
VLC *cur_vlc = &ctx->studio_intra_tab[0];
uint8_t *const scantable = s->intra_scantable.permutated;
const uint16_t *quant_matrix;
uint32_t flc;
const int min = -1 * (1 << (s->avctx->bits_per_raw_sample + 6));
const int max = ((1 << (s->avctx->bits_per_raw_sample + 6)) - 1);
mismatch = 1;
memset(block, 0, 64 * sizeof(int32_t));
if (n < 4) {
cc = 0;
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->intra_matrix;
} else {
cc = (n & 1) + 1;
if (ctx->rgb)
dct_dc_size = get_vlc2(&s->gb, ctx->studio_luma_dc.table, STUDIO_INTRA_BITS, 2);
else
dct_dc_size = get_vlc2(&s->gb, ctx->studio_chroma_dc.table, STUDIO_INTRA_BITS, 2);
quant_matrix = s->chroma_intra_matrix;
}
if (dct_dc_size < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal dct_dc_size vlc\n");
return AVERROR_INVALIDDATA;
} else if (dct_dc_size == 0) {
dct_diff = 0;
} else {
dct_diff = get_xbits(&s->gb, dct_dc_size);
if (dct_dc_size > 8) {
if(!check_marker(s->avctx, &s->gb, "dct_dc_size > 8"))
return AVERROR_INVALIDDATA;
}
}
s->last_dc[cc] += dct_diff;
if (s->mpeg_quant)
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision);
else
block[0] = s->last_dc[cc] * (8 >> s->intra_dc_precision) * (8 >> s->dct_precision);
/* TODO: support mpeg_quant for AC coefficients */
block[0] = av_clip(block[0], min, max);
mismatch ^= block[0];
/* AC Coefficients */
while (1) {
group = get_vlc2(&s->gb, cur_vlc->table, STUDIO_INTRA_BITS, 2);
if (group < 0) {
av_log(s->avctx, AV_LOG_ERROR, "illegal ac coefficient group vlc\n");
return AVERROR_INVALIDDATA;
}
additional_code_len = ac_state_tab[group][0];
cur_vlc = &ctx->studio_intra_tab[ac_state_tab[group][1]];
if (group == 0) {
/* End of Block */
break;
} else if (group >= 1 && group <= 6) {
/* Zero run length (Table B.47) */
run = 1 << additional_code_len;
if (additional_code_len)
run += get_bits(&s->gb, additional_code_len);
idx += run;
continue;
} else if (group >= 7 && group <= 12) {
/* Zero run length and +/-1 level (Table B.48) */
code = get_bits(&s->gb, additional_code_len);
sign = code & 1;
code >>= 1;
run = (1 << (additional_code_len - 1)) + code;
idx += run;
j = scantable[idx++];
block[j] = sign ? 1 : -1;
} else if (group >= 13 && group <= 20) {
/* Level value (Table B.49) */
j = scantable[idx++];
block[j] = get_xbits(&s->gb, additional_code_len);
} else if (group == 21) {
/* Escape */
j = scantable[idx++];
additional_code_len = s->avctx->bits_per_raw_sample + s->dct_precision + 4;
flc = get_bits(&s->gb, additional_code_len);
if (flc >> (additional_code_len-1))
block[j] = -1 * (( flc ^ ((1 << additional_code_len) -1)) + 1);
else
block[j] = flc;
}
block[j] = ((8 * 2 * block[j] * quant_matrix[j] * s->qscale) >> s->dct_precision) / 32;
block[j] = av_clip(block[j], min, max);
mismatch ^= block[j];
}
block[63] ^= mismatch & 1;
return 0;
}
static int mpeg4_decode_studio_mb(MpegEncContext *s, int16_t block_[12][64])
{
int i;
/* StudioMacroblock */
/* Assumes I-VOP */
s->mb_intra = 1;
if (get_bits1(&s->gb)) { /* compression_mode */
/* DCT */
/* macroblock_type, 1 or 2-bit VLC */
if (!get_bits1(&s->gb)) {
skip_bits1(&s->gb);
s->qscale = mpeg_get_qscale(s);
}
for (i = 0; i < mpeg4_block_count[s->chroma_format]; i++) {
if (mpeg4_decode_studio_block(s, (*s->block32)[i], i) < 0)
return AVERROR_INVALIDDATA;
}
} else {
/* DPCM */
check_marker(s->avctx, &s->gb, "DPCM block start");
avpriv_request_sample(s->avctx, "DPCM encoded block");
next_start_code_studio(&s->gb);
return SLICE_ERROR;
}
if (get_bits_left(&s->gb) >= 24 && show_bits(&s->gb, 23) == 0) {
next_start_code_studio(&s->gb);
return SLICE_END;
}
return SLICE_OK;
}
static int mpeg4_decode_gop_header(MpegEncContext *s, GetBitContext *gb)
{
int hours, minutes, seconds;
if (!show_bits(gb, 23)) {
av_log(s->avctx, AV_LOG_WARNING, "GOP header invalid\n");
return AVERROR_INVALIDDATA;
}
hours = get_bits(gb, 5);
minutes = get_bits(gb, 6);
check_marker(s->avctx, gb, "in gop_header");
seconds = get_bits(gb, 6);
s->time_base = seconds + 60*(minutes + 60*hours);
skip_bits1(gb);
skip_bits1(gb);
return 0;
}
static int mpeg4_decode_profile_level(MpegEncContext *s, GetBitContext *gb, int *profile, int *level)
{
*profile = get_bits(gb, 4);
*level = get_bits(gb, 4);
// for Simple profile, level 0
if (*profile == 0 && *level == 8) {
*level = 0;
}
return 0;
}
static int mpeg4_decode_visual_object(MpegEncContext *s, GetBitContext *gb)
{
int visual_object_type;
int is_visual_object_identifier = get_bits1(gb);
if (is_visual_object_identifier) {
skip_bits(gb, 4+3);
}
visual_object_type = get_bits(gb, 4);
if (visual_object_type == VOT_VIDEO_ID ||
visual_object_type == VOT_STILL_TEXTURE_ID) {
int video_signal_type = get_bits1(gb);
if (video_signal_type) {
int video_range, color_description;
skip_bits(gb, 3); // video_format
video_range = get_bits1(gb);
color_description = get_bits1(gb);
s->avctx->color_range = video_range ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
if (color_description) {
s->avctx->color_primaries = get_bits(gb, 8);
s->avctx->color_trc = get_bits(gb, 8);
s->avctx->colorspace = get_bits(gb, 8);
}
}
}
return 0;
}
static void mpeg4_load_default_matrices(MpegEncContext *s)
{
int i, v;
/* load default matrices */
for (i = 0; i < 64; i++) {
int j = s->idsp.idct_permutation[i];
v = ff_mpeg4_default_intra_matrix[i];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
v = ff_mpeg4_default_non_intra_matrix[i];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
}
static int decode_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height, vo_ver_id;
/* vol header */
skip_bits(gb, 1); /* random access */
s->vo_type = get_bits(gb, 8);
/* If we are in studio profile (per vo_type), check if its all consistent
* and if so continue pass control to decode_studio_vol_header().
* elIf something is inconsistent, error out
* else continue with (non studio) vol header decpoding.
*/
if (s->vo_type == CORE_STUDIO_VO_TYPE ||
s->vo_type == SIMPLE_STUDIO_VO_TYPE) {
if (s->avctx->profile != FF_PROFILE_UNKNOWN && s->avctx->profile != FF_PROFILE_MPEG4_SIMPLE_STUDIO)
return AVERROR_INVALIDDATA;
s->studio_profile = 1;
s->avctx->profile = FF_PROFILE_MPEG4_SIMPLE_STUDIO;
return decode_studio_vol_header(ctx, gb);
} else if (s->studio_profile) {
return AVERROR_PATCHWELCOME;
}
if (get_bits1(gb) != 0) { /* is_ol_id */
vo_ver_id = get_bits(gb, 4); /* vo_ver_id */
skip_bits(gb, 3); /* vo_priority */
} else {
vo_ver_id = 1;
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
if ((ctx->vol_control_parameters = get_bits1(gb))) { /* vol control parameter */
int chroma_format = get_bits(gb, 2);
if (chroma_format != CHROMA_420)
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
s->low_delay = get_bits1(gb);
if (get_bits1(gb)) { /* vbv parameters */
get_bits(gb, 15); /* first_half_bitrate */
check_marker(s->avctx, gb, "after first_half_bitrate");
get_bits(gb, 15); /* latter_half_bitrate */
check_marker(s->avctx, gb, "after latter_half_bitrate");
get_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
get_bits(gb, 3); /* latter_half_vbv_buffer_size */
get_bits(gb, 11); /* first_half_vbv_occupancy */
check_marker(s->avctx, gb, "after first_half_vbv_occupancy");
get_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
}
} else {
/* is setting low delay flag only once the smartest thing to do?
* low delay detection will not be overridden. */
if (s->picture_number == 0) {
switch(s->vo_type) {
case SIMPLE_VO_TYPE:
case ADV_SIMPLE_VO_TYPE:
s->low_delay = 1;
break;
default:
s->low_delay = 0;
}
}
}
ctx->shape = get_bits(gb, 2); /* vol shape */
if (ctx->shape != RECT_SHAPE)
av_log(s->avctx, AV_LOG_ERROR, "only rectangular vol supported\n");
if (ctx->shape == GRAY_SHAPE && vo_ver_id != 1) {
av_log(s->avctx, AV_LOG_ERROR, "Gray shape not supported\n");
skip_bits(gb, 4); /* video_object_layer_shape_extension */
}
check_marker(s->avctx, gb, "before time_increment_resolution");
s->avctx->framerate.num = get_bits(gb, 16);
if (!s->avctx->framerate.num) {
av_log(s->avctx, AV_LOG_ERROR, "framerate==0\n");
return AVERROR_INVALIDDATA;
}
ctx->time_increment_bits = av_log2(s->avctx->framerate.num - 1) + 1;
if (ctx->time_increment_bits < 1)
ctx->time_increment_bits = 1;
check_marker(s->avctx, gb, "before fixed_vop_rate");
if (get_bits1(gb) != 0) /* fixed_vop_rate */
s->avctx->framerate.den = get_bits(gb, ctx->time_increment_bits);
else
s->avctx->framerate.den = 1;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
ctx->t_frame = 0;
if (ctx->shape != BIN_ONLY_SHAPE) {
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before width");
width = get_bits(gb, 13);
check_marker(s->avctx, gb, "before height");
height = get_bits(gb, 13);
check_marker(s->avctx, gb, "after height");
if (width && height && /* they should be non zero but who knows */
!(s->width && s->codec_tag == AV_RL32("MP4S"))) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->progressive_sequence =
s->progressive_frame = get_bits1(gb) ^ 1;
s->interlaced_dct = 0;
if (!get_bits1(gb) && (s->avctx->debug & FF_DEBUG_PICT_INFO))
av_log(s->avctx, AV_LOG_INFO, /* OBMC Disable */
"MPEG-4 OBMC not supported (very likely buggy encoder)\n");
if (vo_ver_id == 1)
ctx->vol_sprite_usage = get_bits1(gb); /* vol_sprite_usage */
else
ctx->vol_sprite_usage = get_bits(gb, 2); /* vol_sprite_usage */
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "Static Sprites not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE) {
if (ctx->vol_sprite_usage == STATIC_SPRITE) {
skip_bits(gb, 13); // sprite_width
check_marker(s->avctx, gb, "after sprite_width");
skip_bits(gb, 13); // sprite_height
check_marker(s->avctx, gb, "after sprite_height");
skip_bits(gb, 13); // sprite_left
check_marker(s->avctx, gb, "after sprite_left");
skip_bits(gb, 13); // sprite_top
check_marker(s->avctx, gb, "after sprite_top");
}
ctx->num_sprite_warping_points = get_bits(gb, 6);
if (ctx->num_sprite_warping_points > 3) {
av_log(s->avctx, AV_LOG_ERROR,
"%d sprite_warping_points\n",
ctx->num_sprite_warping_points);
ctx->num_sprite_warping_points = 0;
return AVERROR_INVALIDDATA;
}
s->sprite_warping_accuracy = get_bits(gb, 2);
ctx->sprite_brightness_change = get_bits1(gb);
if (ctx->vol_sprite_usage == STATIC_SPRITE)
skip_bits1(gb); // low_latency_sprite
}
// FIXME sadct disable bit if verid!=1 && shape not rect
if (get_bits1(gb) == 1) { /* not_8_bit */
s->quant_precision = get_bits(gb, 4); /* quant_precision */
if (get_bits(gb, 4) != 8) /* bits_per_pixel */
av_log(s->avctx, AV_LOG_ERROR, "N-bit not supported\n");
if (s->quant_precision != 5)
av_log(s->avctx, AV_LOG_ERROR,
"quant precision %d\n", s->quant_precision);
if (s->quant_precision<3 || s->quant_precision>9) {
s->quant_precision = 5;
}
} else {
s->quant_precision = 5;
}
// FIXME a bunch of grayscale shape things
if ((s->mpeg_quant = get_bits1(gb))) { /* vol_quant_type */
int i, v;
mpeg4_load_default_matrices(s);
/* load custom intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = last;
s->chroma_intra_matrix[j] = last;
}
}
/* load custom non intra matrix */
if (get_bits1(gb)) {
int last = 0;
for (i = 0; i < 64; i++) {
int j;
if (get_bits_left(gb) < 8) {
av_log(s->avctx, AV_LOG_ERROR, "insufficient data for custom matrix\n");
return AVERROR_INVALIDDATA;
}
v = get_bits(gb, 8);
if (v == 0)
break;
last = v;
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = v;
s->chroma_inter_matrix[j] = v;
}
/* replicate last value */
for (; i < 64; i++) {
int j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->inter_matrix[j] = last;
s->chroma_inter_matrix[j] = last;
}
}
// FIXME a bunch of grayscale shape things
}
if (vo_ver_id != 1)
s->quarter_sample = get_bits1(gb);
else
s->quarter_sample = 0;
if (get_bits_left(gb) < 4) {
av_log(s->avctx, AV_LOG_ERROR, "VOL Header truncated\n");
return AVERROR_INVALIDDATA;
}
if (!get_bits1(gb)) {
int pos = get_bits_count(gb);
int estimation_method = get_bits(gb, 2);
if (estimation_method < 2) {
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* opaque */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* transparent */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* inter_cae */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* no_update */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* upsampling */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* intra_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter_blocks */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* inter4v_blocks */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* not coded blocks */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 1")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_coeffs */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* dct_lines */
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* vlc_syms */
ctx->cplx_estimation_trash_i += 4 * get_bits1(gb); /* vlc_bits */
}
if (!get_bits1(gb)) {
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* apm */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* npm */
ctx->cplx_estimation_trash_b += 8 * get_bits1(gb); /* interpolate_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* forwback_mc_q */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel2 */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* halfpel4 */
}
if (!check_marker(s->avctx, gb, "in complexity estimation part 2")) {
skip_bits_long(gb, pos - get_bits_count(gb));
goto no_cplx_est;
}
if (estimation_method == 1) {
ctx->cplx_estimation_trash_i += 8 * get_bits1(gb); /* sadct */
ctx->cplx_estimation_trash_p += 8 * get_bits1(gb); /* qpel */
}
} else
av_log(s->avctx, AV_LOG_ERROR,
"Invalid Complexity estimation method %d\n",
estimation_method);
} else {
no_cplx_est:
ctx->cplx_estimation_trash_i =
ctx->cplx_estimation_trash_p =
ctx->cplx_estimation_trash_b = 0;
}
ctx->resync_marker = !get_bits1(gb); /* resync_marker_disabled */
s->data_partitioning = get_bits1(gb);
if (s->data_partitioning)
ctx->rvlc = get_bits1(gb);
if (vo_ver_id != 1) {
ctx->new_pred = get_bits1(gb);
if (ctx->new_pred) {
av_log(s->avctx, AV_LOG_ERROR, "new pred not supported\n");
skip_bits(gb, 2); /* requested upstream message type */
skip_bits1(gb); /* newpred segment type */
}
if (get_bits1(gb)) // reduced_res_vop
av_log(s->avctx, AV_LOG_ERROR,
"reduced resolution VOP not supported\n");
} else {
ctx->new_pred = 0;
}
ctx->scalability = get_bits1(gb);
if (ctx->scalability) {
GetBitContext bak = *gb;
int h_sampling_factor_n;
int h_sampling_factor_m;
int v_sampling_factor_n;
int v_sampling_factor_m;
skip_bits1(gb); // hierarchy_type
skip_bits(gb, 4); /* ref_layer_id */
skip_bits1(gb); /* ref_layer_sampling_dir */
h_sampling_factor_n = get_bits(gb, 5);
h_sampling_factor_m = get_bits(gb, 5);
v_sampling_factor_n = get_bits(gb, 5);
v_sampling_factor_m = get_bits(gb, 5);
ctx->enhancement_type = get_bits1(gb);
if (h_sampling_factor_n == 0 || h_sampling_factor_m == 0 ||
v_sampling_factor_n == 0 || v_sampling_factor_m == 0) {
/* illegal scalability header (VERY broken encoder),
* trying to workaround */
ctx->scalability = 0;
*gb = bak;
} else
av_log(s->avctx, AV_LOG_ERROR, "scalability not supported\n");
// bin shape stuff FIXME
}
}
if (s->avctx->debug&FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG, "tb %d/%d, tincrbits:%d, qp_prec:%d, ps:%d, low_delay:%d %s%s%s%s\n",
s->avctx->framerate.den, s->avctx->framerate.num,
ctx->time_increment_bits,
s->quant_precision,
s->progressive_sequence,
s->low_delay,
ctx->scalability ? "scalability " :"" , s->quarter_sample ? "qpel " : "",
s->data_partitioning ? "partition " : "", ctx->rvlc ? "rvlc " : ""
);
}
return 0;
}
/**
* Decode the user data stuff in the header.
* Also initializes divx/xvid/lavc_version/build.
*/
static int decode_user_data(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
char buf[256];
int i;
int e;
int ver = 0, build = 0, ver2 = 0, ver3 = 0;
char last;
for (i = 0; i < 255 && get_bits_count(gb) < gb->size_in_bits; i++) {
if (show_bits(gb, 23) == 0)
break;
buf[i] = get_bits(gb, 8);
}
buf[i] = 0;
/* divx detection */
e = sscanf(buf, "DivX%dBuild%d%c", &ver, &build, &last);
if (e < 2)
e = sscanf(buf, "DivX%db%d%c", &ver, &build, &last);
if (e >= 2) {
ctx->divx_version = ver;
ctx->divx_build = build;
s->divx_packed = e == 3 && last == 'p';
}
/* libavcodec detection */
e = sscanf(buf, "FFmpe%*[^b]b%d", &build) + 3;
if (e != 4)
e = sscanf(buf, "FFmpeg v%d.%d.%d / libavcodec build: %d", &ver, &ver2, &ver3, &build);
if (e != 4) {
e = sscanf(buf, "Lavc%d.%d.%d", &ver, &ver2, &ver3) + 1;
if (e > 1) {
if (ver > 0xFFU || ver2 > 0xFFU || ver3 > 0xFFU) {
av_log(s->avctx, AV_LOG_WARNING,
"Unknown Lavc version string encountered, %d.%d.%d; "
"clamping sub-version values to 8-bits.\n",
ver, ver2, ver3);
}
build = ((ver & 0xFF) << 16) + ((ver2 & 0xFF) << 8) + (ver3 & 0xFF);
}
}
if (e != 4) {
if (strcmp(buf, "ffmpeg") == 0)
ctx->lavc_build = 4600;
}
if (e == 4)
ctx->lavc_build = build;
/* Xvid detection */
e = sscanf(buf, "XviD%d", &build);
if (e == 1)
ctx->xvid_build = build;
return 0;
}
int ff_mpeg4_workaround_bugs(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1) {
if (s->codec_tag == AV_RL32("XVID") ||
s->codec_tag == AV_RL32("XVIX") ||
s->codec_tag == AV_RL32("RMP4") ||
s->codec_tag == AV_RL32("ZMP4") ||
s->codec_tag == AV_RL32("SIPP"))
ctx->xvid_build = 0;
}
if (ctx->xvid_build == -1 && ctx->divx_version == -1 && ctx->lavc_build == -1)
if (s->codec_tag == AV_RL32("DIVX") && s->vo_type == 0 &&
ctx->vol_control_parameters == 0)
ctx->divx_version = 400; // divx 4
if (ctx->xvid_build >= 0 && ctx->divx_version >= 0) {
ctx->divx_version =
ctx->divx_build = -1;
}
if (s->workaround_bugs & FF_BUG_AUTODETECT) {
if (s->codec_tag == AV_RL32("XVIX"))
s->workaround_bugs |= FF_BUG_XVID_ILACE;
if (s->codec_tag == AV_RL32("UMP4"))
s->workaround_bugs |= FF_BUG_UMP4;
if (ctx->divx_version >= 500 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->divx_version > 502 && ctx->divx_build < 1814)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA2;
if (ctx->xvid_build <= 3U)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->xvid_build <= 1U)
s->workaround_bugs |= FF_BUG_QPEL_CHROMA;
if (ctx->xvid_build <= 12U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->xvid_build <= 32U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
#define SET_QPEL_FUNC(postfix1, postfix2) \
s->qdsp.put_ ## postfix1 = ff_put_ ## postfix2; \
s->qdsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2; \
s->qdsp.avg_ ## postfix1 = ff_avg_ ## postfix2;
if (ctx->lavc_build < 4653U)
s->workaround_bugs |= FF_BUG_STD_QPEL;
if (ctx->lavc_build < 4655U)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->lavc_build < 4670U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->lavc_build <= 4712U)
s->workaround_bugs |= FF_BUG_DC_CLIP;
if ((ctx->lavc_build&0xFF) >= 100) {
if (ctx->lavc_build > 3621476 && ctx->lavc_build < 3752552 &&
(ctx->lavc_build < 3752037 || ctx->lavc_build > 3752191) // 3.2.1+
)
s->workaround_bugs |= FF_BUG_IEDGE;
}
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_DIRECT_BLOCKSIZE;
if (ctx->divx_version == 501 && ctx->divx_build == 20020416)
s->padding_bug_score = 256 * 256 * 256 * 64;
if (ctx->divx_version < 500U)
s->workaround_bugs |= FF_BUG_EDGE;
if (ctx->divx_version >= 0)
s->workaround_bugs |= FF_BUG_HPEL_CHROMA;
}
if (s->workaround_bugs & FF_BUG_STD_QPEL) {
SET_QPEL_FUNC(qpel_pixels_tab[0][5], qpel16_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][7], qpel16_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][9], qpel16_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][5], qpel8_mc11_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][7], qpel8_mc31_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][9], qpel8_mc12_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)
SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)
}
if (avctx->debug & FF_DEBUG_BUGS)
av_log(s->avctx, AV_LOG_DEBUG,
"bugs: %X lavc_build:%d xvid_build:%d divx_version:%d divx_build:%d %s\n",
s->workaround_bugs, ctx->lavc_build, ctx->xvid_build,
ctx->divx_version, ctx->divx_build, s->divx_packed ? "p" : "");
if (CONFIG_MPEG4_DECODER && ctx->xvid_build >= 0 &&
s->codec_id == AV_CODEC_ID_MPEG4 &&
avctx->idct_algo == FF_IDCT_AUTO) {
avctx->idct_algo = FF_IDCT_XVID;
ff_mpv_idct_init(s);
return 1;
}
return 0;
}
static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int time_incr, time_increment;
int64_t pts;
s->mcsel = 0;
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* pict type: I = 0 , P = 1 */
if (s->pict_type == AV_PICTURE_TYPE_B && s->low_delay &&
ctx->vol_control_parameters == 0 && !(s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)) {
av_log(s->avctx, AV_LOG_ERROR, "low_delay flag set incorrectly, clearing it\n");
s->low_delay = 0;
}
s->partitioned_frame = s->data_partitioning && s->pict_type != AV_PICTURE_TYPE_B;
if (s->partitioned_frame)
s->decode_mb = mpeg4_decode_partitioned_mb;
else
s->decode_mb = mpeg4_decode_mb;
time_incr = 0;
while (get_bits1(gb) != 0)
time_incr++;
check_marker(s->avctx, gb, "before time_increment");
if (ctx->time_increment_bits == 0 ||
!(show_bits(gb, ctx->time_increment_bits + 1) & 1)) {
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits %d is invalid in relation to the current bitstream, this is likely caused by a missing VOL header\n", ctx->time_increment_bits);
for (ctx->time_increment_bits = 1;
ctx->time_increment_bits < 16;
ctx->time_increment_bits++) {
if (s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE)) {
if ((show_bits(gb, ctx->time_increment_bits + 6) & 0x37) == 0x30)
break;
} else if ((show_bits(gb, ctx->time_increment_bits + 5) & 0x1F) == 0x18)
break;
}
av_log(s->avctx, AV_LOG_WARNING,
"time_increment_bits set to %d bits, based on bitstream analysis\n", ctx->time_increment_bits);
if (s->avctx->framerate.num && 4*s->avctx->framerate.num < 1<<ctx->time_increment_bits) {
s->avctx->framerate.num = 1<<ctx->time_increment_bits;
s->avctx->time_base = av_inv_q(av_mul_q(s->avctx->framerate, (AVRational){s->avctx->ticks_per_frame, 1}));
}
}
if (IS_3IV1)
time_increment = get_bits1(gb); // FIXME investigate further
else
time_increment = get_bits(gb, ctx->time_increment_bits);
if (s->pict_type != AV_PICTURE_TYPE_B) {
s->last_time_base = s->time_base;
s->time_base += time_incr;
s->time = s->time_base * (int64_t)s->avctx->framerate.num + time_increment;
if (s->workaround_bugs & FF_BUG_UMP4) {
if (s->time < s->last_non_b_time) {
/* header is not mpeg-4-compatible, broken encoder,
* trying to workaround */
s->time_base++;
s->time += s->avctx->framerate.num;
}
}
s->pp_time = s->time - s->last_non_b_time;
s->last_non_b_time = s->time;
} else {
s->time = (s->last_time_base + time_incr) * (int64_t)s->avctx->framerate.num + time_increment;
s->pb_time = s->pp_time - (s->last_non_b_time - s->time);
if (s->pp_time <= s->pb_time ||
s->pp_time <= s->pp_time - s->pb_time ||
s->pp_time <= 0) {
/* messed up order, maybe after seeking? skipping current B-frame */
return FRAME_SKIPPED;
}
ff_mpeg4_init_direct_mv(s);
if (ctx->t_frame == 0)
ctx->t_frame = s->pb_time;
if (ctx->t_frame == 0)
ctx->t_frame = 1; // 1/0 protection
s->pp_field_time = (ROUNDED_DIV(s->last_non_b_time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
s->pb_field_time = (ROUNDED_DIV(s->time, ctx->t_frame) -
ROUNDED_DIV(s->last_non_b_time - s->pp_time, ctx->t_frame)) * 2;
if (s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1) {
s->pb_field_time = 2;
s->pp_field_time = 4;
if (!s->progressive_sequence)
return FRAME_SKIPPED;
}
}
if (s->avctx->framerate.den)
pts = ROUNDED_DIV(s->time, s->avctx->framerate.den);
else
pts = AV_NOPTS_VALUE;
ff_dlog(s->avctx, "MPEG4 PTS: %"PRId64"\n", pts);
check_marker(s->avctx, gb, "before vop_coded");
/* vop coded */
if (get_bits1(gb) != 1) {
if (s->avctx->debug & FF_DEBUG_PICT_INFO)
av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");
return FRAME_SKIPPED;
}
if (ctx->new_pred)
decode_new_pred(ctx, gb);
if (ctx->shape != BIN_ONLY_SHAPE &&
(s->pict_type == AV_PICTURE_TYPE_P ||
(s->pict_type == AV_PICTURE_TYPE_S &&
ctx->vol_sprite_usage == GMC_SPRITE))) {
/* rounding type for motion estimation */
s->no_rounding = get_bits1(gb);
} else {
s->no_rounding = 0;
}
// FIXME reduced res stuff
if (ctx->shape != RECT_SHAPE) {
if (ctx->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {
skip_bits(gb, 13); /* width */
check_marker(s->avctx, gb, "after width");
skip_bits(gb, 13); /* height */
check_marker(s->avctx, gb, "after height");
skip_bits(gb, 13); /* hor_spat_ref */
check_marker(s->avctx, gb, "after hor_spat_ref");
skip_bits(gb, 13); /* ver_spat_ref */
}
skip_bits1(gb); /* change_CR_disable */
if (get_bits1(gb) != 0)
skip_bits(gb, 8); /* constant_alpha_value */
}
// FIXME complexity estimation stuff
if (ctx->shape != BIN_ONLY_SHAPE) {
skip_bits_long(gb, ctx->cplx_estimation_trash_i);
if (s->pict_type != AV_PICTURE_TYPE_I)
skip_bits_long(gb, ctx->cplx_estimation_trash_p);
if (s->pict_type == AV_PICTURE_TYPE_B)
skip_bits_long(gb, ctx->cplx_estimation_trash_b);
if (get_bits_left(gb) < 3) {
av_log(s->avctx, AV_LOG_ERROR, "Header truncated\n");
return AVERROR_INVALIDDATA;
}
ctx->intra_dc_threshold = ff_mpeg4_dc_threshold[get_bits(gb, 3)];
if (!s->progressive_sequence) {
s->top_field_first = get_bits1(gb);
s->alternate_scan = get_bits1(gb);
} else
s->alternate_scan = 0;
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
if (s->pict_type == AV_PICTURE_TYPE_S) {
if((ctx->vol_sprite_usage == STATIC_SPRITE ||
ctx->vol_sprite_usage == GMC_SPRITE)) {
if (mpeg4_decode_sprite_trajectory(ctx, gb) < 0)
return AVERROR_INVALIDDATA;
if (ctx->sprite_brightness_change)
av_log(s->avctx, AV_LOG_ERROR,
"sprite_brightness_change not supported\n");
if (ctx->vol_sprite_usage == STATIC_SPRITE)
av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");
} else {
memset(s->sprite_offset, 0, sizeof(s->sprite_offset));
memset(s->sprite_delta, 0, sizeof(s->sprite_delta));
}
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->chroma_qscale = s->qscale = get_bits(gb, s->quant_precision);
if (s->qscale == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (qscale=0)\n");
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
if (s->pict_type != AV_PICTURE_TYPE_I) {
s->f_code = get_bits(gb, 3); /* fcode_for */
if (s->f_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG-4 header (f_code=0)\n");
s->f_code = 1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as there is nothing left from the image then
}
} else
s->f_code = 1;
if (s->pict_type == AV_PICTURE_TYPE_B) {
s->b_code = get_bits(gb, 3);
if (s->b_code == 0) {
av_log(s->avctx, AV_LOG_ERROR,
"Error, header damaged or not MPEG4 header (b_code=0)\n");
s->b_code=1;
return AVERROR_INVALIDDATA; // makes no sense to continue, as the MV decoding will break very quickly
}
} else
s->b_code = 1;
if (s->avctx->debug & FF_DEBUG_PICT_INFO) {
av_log(s->avctx, AV_LOG_DEBUG,
"qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d time:%"PRId64" tincr:%d\n",
s->qscale, s->f_code, s->b_code,
s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),
gb->size_in_bits,s->progressive_sequence, s->alternate_scan,
s->top_field_first, s->quarter_sample ? "q" : "h",
s->data_partitioning, ctx->resync_marker,
ctx->num_sprite_warping_points, s->sprite_warping_accuracy,
1 - s->no_rounding, s->vo_type,
ctx->vol_control_parameters ? " VOLC" : " ", ctx->intra_dc_threshold,
ctx->cplx_estimation_trash_i, ctx->cplx_estimation_trash_p,
ctx->cplx_estimation_trash_b,
s->time,
time_increment
);
}
if (!ctx->scalability) {
if (ctx->shape != RECT_SHAPE && s->pict_type != AV_PICTURE_TYPE_I)
skip_bits1(gb); // vop shape coding type
} else {
if (ctx->enhancement_type) {
int load_backward_shape = get_bits1(gb);
if (load_backward_shape)
av_log(s->avctx, AV_LOG_ERROR,
"load backward shape isn't supported\n");
}
skip_bits(gb, 2); // ref_select_code
}
}
/* detect buggy encoders which don't set the low_delay flag
* (divx4/xvid/opendivx). Note we cannot detect divx5 without B-frames
* easily (although it's buggy too) */
if (s->vo_type == 0 && ctx->vol_control_parameters == 0 &&
ctx->divx_version == -1 && s->picture_number == 0) {
av_log(s->avctx, AV_LOG_WARNING,
"looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");
s->low_delay = 1;
}
s->picture_number++; // better than pic number==0 always ;)
// FIXME add short header support
s->y_dc_scale_table = ff_mpeg4_y_dc_scale_table;
s->c_dc_scale_table = ff_mpeg4_c_dc_scale_table;
if (s->workaround_bugs & FF_BUG_EDGE) {
s->h_edge_pos = s->width;
s->v_edge_pos = s->height;
}
return 0;
}
static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb)
{
int i, j, v;
if (get_bits1(gb)) {
/* intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->intra_matrix[j] = v;
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
if (get_bits1(gb)) {
/* chroma_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
v = get_bits(gb, 8);
j = s->idsp.idct_permutation[ff_zigzag_direct[i]];
s->chroma_intra_matrix[j] = v;
}
}
if (get_bits1(gb)) {
/* chroma_non_intra_quantiser_matrix */
for (i = 0; i < 64; i++) {
get_bits(gb, 8);
}
}
next_start_code_studio(gb);
}
static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)
{
uint32_t startcode;
uint8_t extension_type;
startcode = show_bits_long(gb, 32);
if (startcode == USER_DATA_STARTCODE || startcode == EXT_STARTCODE) {
if ((id == 2 || id == 4) && startcode == EXT_STARTCODE) {
skip_bits_long(gb, 32);
extension_type = get_bits(gb, 4);
if (extension_type == QUANT_MATRIX_EXT_ID)
read_quant_matrix_ext(s, gb);
}
}
}
static void decode_smpte_tc(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
skip_bits(gb, 16); /* Time_code[63..48] */
check_marker(s->avctx, gb, "after Time_code[63..48]");
skip_bits(gb, 16); /* Time_code[47..32] */
check_marker(s->avctx, gb, "after Time_code[47..32]");
skip_bits(gb, 16); /* Time_code[31..16] */
check_marker(s->avctx, gb, "after Time_code[31..16]");
skip_bits(gb, 16); /* Time_code[15..0] */
check_marker(s->avctx, gb, "after Time_code[15..0]");
skip_bits(gb, 4); /* reserved_bits */
}
/**
* Decode the next studio vop header.
* @return <0 if something went wrong
*/
static int decode_studio_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
if (get_bits_left(gb) <= 32)
return 0;
s->decode_mb = mpeg4_decode_studio_mb;
decode_smpte_tc(ctx, gb);
skip_bits(gb, 10); /* temporal_reference */
skip_bits(gb, 2); /* vop_structure */
s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I; /* vop_coding_type */
if (get_bits1(gb)) { /* vop_coded */
skip_bits1(gb); /* top_field_first */
skip_bits1(gb); /* repeat_first_field */
s->progressive_frame = get_bits1(gb) ^ 1; /* progressive_frame */
}
if (s->pict_type == AV_PICTURE_TYPE_I) {
if (get_bits1(gb))
reset_studio_dc_predictors(s);
}
if (ctx->shape != BIN_ONLY_SHAPE) {
s->alternate_scan = get_bits1(gb);
s->frame_pred_frame_dct = get_bits1(gb);
s->dct_precision = get_bits(gb, 2);
s->intra_dc_precision = get_bits(gb, 2);
s->q_scale_type = get_bits1(gb);
}
if (s->alternate_scan) {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
} else {
ff_init_scantable(s->idsp.idct_permutation, &s->inter_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_scantable, ff_zigzag_direct);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);
ff_init_scantable(s->idsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);
}
mpeg4_load_default_matrices(s);
next_start_code_studio(gb);
extension_and_user_data(s, gb, 4);
return 0;
}
static int decode_studiovisualobject(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int visual_object_type;
skip_bits(gb, 4); /* visual_object_verid */
visual_object_type = get_bits(gb, 4);
if (visual_object_type != VOT_VIDEO_ID) {
avpriv_request_sample(s->avctx, "VO type %u", visual_object_type);
return AVERROR_PATCHWELCOME;
}
next_start_code_studio(gb);
extension_and_user_data(s, gb, 1);
return 0;
}
static int decode_studio_vol_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
int width, height;
int bits_per_raw_sample;
// random_accessible_vol and video_object_type_indication have already
// been read by the caller decode_vol_header()
skip_bits(gb, 4); /* video_object_layer_verid */
ctx->shape = get_bits(gb, 2); /* video_object_layer_shape */
skip_bits(gb, 4); /* video_object_layer_shape_extension */
skip_bits1(gb); /* progressive_sequence */
if (ctx->shape != BIN_ONLY_SHAPE) {
ctx->rgb = get_bits1(gb); /* rgb_components */
s->chroma_format = get_bits(gb, 2); /* chroma_format */
if (!s->chroma_format) {
av_log(s->avctx, AV_LOG_ERROR, "illegal chroma format\n");
return AVERROR_INVALIDDATA;
}
bits_per_raw_sample = get_bits(gb, 4); /* bit_depth */
if (bits_per_raw_sample == 10) {
if (ctx->rgb) {
s->avctx->pix_fmt = AV_PIX_FMT_GBRP10;
}
else {
s->avctx->pix_fmt = s->chroma_format == CHROMA_422 ? AV_PIX_FMT_YUV422P10 : AV_PIX_FMT_YUV444P10;
}
}
else {
avpriv_request_sample(s->avctx, "MPEG-4 Studio profile bit-depth %u", bits_per_raw_sample);
return AVERROR_PATCHWELCOME;
}
s->avctx->bits_per_raw_sample = bits_per_raw_sample;
}
if (ctx->shape == RECT_SHAPE) {
check_marker(s->avctx, gb, "before video_object_layer_width");
width = get_bits(gb, 14); /* video_object_layer_width */
check_marker(s->avctx, gb, "before video_object_layer_height");
height = get_bits(gb, 14); /* video_object_layer_height */
check_marker(s->avctx, gb, "after video_object_layer_height");
/* Do the same check as non-studio profile */
if (width && height) {
if (s->width && s->height &&
(s->width != width || s->height != height))
s->context_reinit = 1;
s->width = width;
s->height = height;
}
}
s->aspect_ratio_info = get_bits(gb, 4);
if (s->aspect_ratio_info == FF_ASPECT_EXTENDED) {
s->avctx->sample_aspect_ratio.num = get_bits(gb, 8); // par_width
s->avctx->sample_aspect_ratio.den = get_bits(gb, 8); // par_height
} else {
s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[s->aspect_ratio_info];
}
skip_bits(gb, 4); /* frame_rate_code */
skip_bits(gb, 15); /* first_half_bit_rate */
check_marker(s->avctx, gb, "after first_half_bit_rate");
skip_bits(gb, 15); /* latter_half_bit_rate */
check_marker(s->avctx, gb, "after latter_half_bit_rate");
skip_bits(gb, 15); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 3); /* latter_half_vbv_buffer_size */
skip_bits(gb, 11); /* first_half_vbv_buffer_size */
check_marker(s->avctx, gb, "after first_half_vbv_buffer_size");
skip_bits(gb, 15); /* latter_half_vbv_occupancy */
check_marker(s->avctx, gb, "after latter_half_vbv_occupancy");
s->low_delay = get_bits1(gb);
s->mpeg_quant = get_bits1(gb); /* mpeg2_stream */
next_start_code_studio(gb);
extension_and_user_data(s, gb, 2);
return 0;
}
/**
* Decode MPEG-4 headers.
* @return <0 if no VOP found (or a damaged one)
* FRAME_SKIPPED if a not coded VOP is found
* 0 if a VOP is found
*/
int ff_mpeg4_decode_picture_header(Mpeg4DecContext *ctx, GetBitContext *gb)
{
MpegEncContext *s = &ctx->m;
unsigned startcode, v;
int ret;
int vol = 0;
/* search next start code */
align_get_bits(gb);
// If we have not switched to studio profile than we also did not switch bps
// that means something else (like a previous instance) outside set bps which
// would be inconsistant with the currect state, thus reset it
if (!s->studio_profile && s->avctx->bits_per_raw_sample != 8)
s->avctx->bits_per_raw_sample = 0;
if (s->codec_tag == AV_RL32("WV1F") && show_bits(gb, 24) == 0x575630) {
skip_bits(gb, 24);
if (get_bits(gb, 8) == 0xF0)
goto end;
}
startcode = 0xff;
for (;;) {
if (get_bits_count(gb) >= gb->size_in_bits) {
if (gb->size_in_bits == 8 &&
(ctx->divx_version >= 0 || ctx->xvid_build >= 0) || s->codec_tag == AV_RL32("QMP4")) {
av_log(s->avctx, AV_LOG_VERBOSE, "frame skip %d\n", gb->size_in_bits);
return FRAME_SKIPPED; // divx bug
} else
return AVERROR_INVALIDDATA; // end of stream
}
/* use the bits after the test */
v = get_bits(gb, 8);
startcode = ((startcode << 8) | v) & 0xffffffff;
if ((startcode & 0xFFFFFF00) != 0x100)
continue; // no startcode
if (s->avctx->debug & FF_DEBUG_STARTCODE) {
av_log(s->avctx, AV_LOG_DEBUG, "startcode: %3X ", startcode);
if (startcode <= 0x11F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Start");
else if (startcode <= 0x12F)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Layer Start");
else if (startcode <= 0x13F)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode <= 0x15F)
av_log(s->avctx, AV_LOG_DEBUG, "FGS bp start");
else if (startcode <= 0x1AF)
av_log(s->avctx, AV_LOG_DEBUG, "Reserved");
else if (startcode == 0x1B0)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq Start");
else if (startcode == 0x1B1)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Seq End");
else if (startcode == 0x1B2)
av_log(s->avctx, AV_LOG_DEBUG, "User Data");
else if (startcode == 0x1B3)
av_log(s->avctx, AV_LOG_DEBUG, "Group of VOP start");
else if (startcode == 0x1B4)
av_log(s->avctx, AV_LOG_DEBUG, "Video Session Error");
else if (startcode == 0x1B5)
av_log(s->avctx, AV_LOG_DEBUG, "Visual Object Start");
else if (startcode == 0x1B6)
av_log(s->avctx, AV_LOG_DEBUG, "Video Object Plane start");
else if (startcode == 0x1B7)
av_log(s->avctx, AV_LOG_DEBUG, "slice start");
else if (startcode == 0x1B8)
av_log(s->avctx, AV_LOG_DEBUG, "extension start");
else if (startcode == 0x1B9)
av_log(s->avctx, AV_LOG_DEBUG, "fgs start");
else if (startcode == 0x1BA)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object start");
else if (startcode == 0x1BB)
av_log(s->avctx, AV_LOG_DEBUG, "FBA Object Plane start");
else if (startcode == 0x1BC)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object start");
else if (startcode == 0x1BD)
av_log(s->avctx, AV_LOG_DEBUG, "Mesh Object Plane start");
else if (startcode == 0x1BE)
av_log(s->avctx, AV_LOG_DEBUG, "Still Texture Object start");
else if (startcode == 0x1BF)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Spatial Layer start");
else if (startcode == 0x1C0)
av_log(s->avctx, AV_LOG_DEBUG, "Texture SNR Layer start");
else if (startcode == 0x1C1)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Tile start");
else if (startcode == 0x1C2)
av_log(s->avctx, AV_LOG_DEBUG, "Texture Shape Layer start");
else if (startcode == 0x1C3)
av_log(s->avctx, AV_LOG_DEBUG, "stuffing start");
else if (startcode <= 0x1C5)
av_log(s->avctx, AV_LOG_DEBUG, "reserved");
else if (startcode <= 0x1FF)
av_log(s->avctx, AV_LOG_DEBUG, "System start");
av_log(s->avctx, AV_LOG_DEBUG, " at %d\n", get_bits_count(gb));
}
if (startcode >= 0x120 && startcode <= 0x12F) {
if (vol) {
av_log(s->avctx, AV_LOG_WARNING, "Ignoring multiple VOL headers\n");
continue;
}
vol++;
if ((ret = decode_vol_header(ctx, gb)) < 0)
return ret;
} else if (startcode == USER_DATA_STARTCODE) {
decode_user_data(ctx, gb);
} else if (startcode == GOP_STARTCODE) {
mpeg4_decode_gop_header(s, gb);
} else if (startcode == VOS_STARTCODE) {
int profile, level;
mpeg4_decode_profile_level(s, gb, &profile, &level);
if (profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO &&
(level > 0 && level < 9)) {
s->studio_profile = 1;
next_start_code_studio(gb);
extension_and_user_data(s, gb, 0);
} else if (s->studio_profile) {
avpriv_request_sample(s->avctx, "Mixes studio and non studio profile\n");
return AVERROR_PATCHWELCOME;
}
s->avctx->profile = profile;
s->avctx->level = level;
} else if (startcode == VISUAL_OBJ_STARTCODE) {
if (s->studio_profile) {
if ((ret = decode_studiovisualobject(ctx, gb)) < 0)
return ret;
} else
mpeg4_decode_visual_object(s, gb);
} else if (startcode == VOP_STARTCODE) {
break;
}
align_get_bits(gb);
startcode = 0xff;
}
end:
if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)
s->low_delay = 1;
s->avctx->has_b_frames = !s->low_delay;
if (s->studio_profile) {
if (!s->avctx->bits_per_raw_sample) {
av_log(s->avctx, AV_LOG_ERROR, "Missing VOL header\n");
return AVERROR_INVALIDDATA;
}
return decode_studio_vop_header(ctx, gb);
} else
return decode_vop_header(ctx, gb);
}
av_cold void ff_mpeg4videodec_static_init(void) {
static int done = 0;
if (!done) {
ff_rl_init(&ff_mpeg4_rl_intra, ff_mpeg4_static_rl_table_store[0]);
ff_rl_init(&ff_rvlc_rl_inter, ff_mpeg4_static_rl_table_store[1]);
ff_rl_init(&ff_rvlc_rl_intra, ff_mpeg4_static_rl_table_store[2]);
INIT_VLC_RL(ff_mpeg4_rl_intra, 554);
INIT_VLC_RL(ff_rvlc_rl_inter, 1072);
INIT_VLC_RL(ff_rvlc_rl_intra, 1072);
INIT_VLC_STATIC(&dc_lum, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_lum[0][1], 2, 1,
&ff_mpeg4_DCtab_lum[0][0], 2, 1, 512);
INIT_VLC_STATIC(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,
&ff_mpeg4_DCtab_chrom[0][1], 2, 1,
&ff_mpeg4_DCtab_chrom[0][0], 2, 1, 512);
INIT_VLC_STATIC(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,
&ff_sprite_trajectory_tab[0][1], 4, 2,
&ff_sprite_trajectory_tab[0][0], 4, 2, 128);
INIT_VLC_STATIC(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,
&ff_mb_type_b_tab[0][1], 2, 1,
&ff_mb_type_b_tab[0][0], 2, 1, 16);
done = 1;
}
}
int ff_mpeg4_frame_end(AVCodecContext *avctx, const uint8_t *buf, int buf_size)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
/* divx 5.01+ bitstream reorder stuff */
/* Since this clobbers the input buffer and hwaccel codecs still need the
* data during hwaccel->end_frame we should not do this any earlier */
if (s->divx_packed) {
int current_pos = s->gb.buffer == s->bitstream_buffer ? 0 : (get_bits_count(&s->gb) >> 3);
int startcode_found = 0;
if (buf_size - current_pos > 7) {
int i;
for (i = current_pos; i < buf_size - 4; i++)
if (buf[i] == 0 &&
buf[i + 1] == 0 &&
buf[i + 2] == 1 &&
buf[i + 3] == 0xB6) {
startcode_found = !(buf[i + 4] & 0x40);
break;
}
}
if (startcode_found) {
if (!ctx->showed_packed_warning) {
av_log(s->avctx, AV_LOG_INFO, "Video uses a non-standard and "
"wasteful way to store B-frames ('packed B-frames'). "
"Consider using the mpeg4_unpack_bframes bitstream filter without encoding but stream copy to fix it.\n");
ctx->showed_packed_warning = 1;
}
av_fast_padded_malloc(&s->bitstream_buffer,
&s->allocated_bitstream_buffer_size,
buf_size - current_pos);
if (!s->bitstream_buffer) {
s->bitstream_buffer_size = 0;
return AVERROR(ENOMEM);
}
memcpy(s->bitstream_buffer, buf + current_pos,
buf_size - current_pos);
s->bitstream_buffer_size = buf_size - current_pos;
}
}
return 0;
}
#if HAVE_THREADS
static int mpeg4_update_thread_context(AVCodecContext *dst,
const AVCodecContext *src)
{
Mpeg4DecContext *s = dst->priv_data;
const Mpeg4DecContext *s1 = src->priv_data;
int init = s->m.context_initialized;
int ret = ff_mpeg_update_thread_context(dst, src);
if (ret < 0)
return ret;
memcpy(((uint8_t*)s) + sizeof(MpegEncContext), ((uint8_t*)s1) + sizeof(MpegEncContext), sizeof(Mpeg4DecContext) - sizeof(MpegEncContext));
if (CONFIG_MPEG4_DECODER && !init && s1->xvid_build >= 0)
ff_xvid_idct_init(&s->m.idsp, dst);
return 0;
}
#endif
static av_cold int init_studio_vlcs(Mpeg4DecContext *ctx)
{
int i, ret;
for (i = 0; i < 12; i++) {
ret = init_vlc(&ctx->studio_intra_tab[i], STUDIO_INTRA_BITS, 22,
&ff_mpeg4_studio_intra[i][0][1], 4, 2,
&ff_mpeg4_studio_intra[i][0][0], 4, 2,
0);
if (ret < 0)
return ret;
}
ret = init_vlc(&ctx->studio_luma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_luma[0][1], 4, 2,
&ff_mpeg4_studio_dc_luma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
ret = init_vlc(&ctx->studio_chroma_dc, STUDIO_INTRA_BITS, 19,
&ff_mpeg4_studio_dc_chroma[0][1], 4, 2,
&ff_mpeg4_studio_dc_chroma[0][0], 4, 2,
0);
if (ret < 0)
return ret;
return 0;
}
static av_cold int decode_init(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
MpegEncContext *s = &ctx->m;
int ret;
ctx->divx_version =
ctx->divx_build =
ctx->xvid_build =
ctx->lavc_build = -1;
if ((ret = ff_h263_decode_init(avctx)) < 0)
return ret;
ff_mpeg4videodec_static_init();
if ((ret = init_studio_vlcs(ctx)) < 0)
return ret;
s->h263_pred = 1;
s->low_delay = 0; /* default, might be overridden in the vol header during header parsing */
s->decode_mb = mpeg4_decode_mb;
ctx->time_increment_bits = 4; /* default value for broken headers */
avctx->chroma_sample_location = AVCHROMA_LOC_LEFT;
avctx->internal->allocate_progress = 1;
return 0;
}
static av_cold int decode_end(AVCodecContext *avctx)
{
Mpeg4DecContext *ctx = avctx->priv_data;
int i;
if (!avctx->internal->is_copy) {
for (i = 0; i < 12; i++)
ff_free_vlc(&ctx->studio_intra_tab[i]);
ff_free_vlc(&ctx->studio_luma_dc);
ff_free_vlc(&ctx->studio_chroma_dc);
}
return ff_h263_decode_end(avctx);
}
static const AVOption mpeg4_options[] = {
{"quarter_sample", "1/4 subpel MC", offsetof(MpegEncContext, quarter_sample), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{"divx_packed", "divx style packed b frames", offsetof(MpegEncContext, divx_packed), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, 0},
{NULL}
};
static const AVClass mpeg4_class = {
.class_name = "MPEG4 Video Decoder",
.item_name = av_default_item_name,
.option = mpeg4_options,
.version = LIBAVUTIL_VERSION_INT,
};
AVCodec ff_mpeg4_decoder = {
.name = "mpeg4",
.long_name = NULL_IF_CONFIG_SMALL("MPEG-4 part 2"),
.type = AVMEDIA_TYPE_VIDEO,
.id = AV_CODEC_ID_MPEG4,
.priv_data_size = sizeof(Mpeg4DecContext),
.init = decode_init,
.close = decode_end,
.decode = ff_h263_decode_frame,
.capabilities = AV_CODEC_CAP_DRAW_HORIZ_BAND | AV_CODEC_CAP_DR1 |
AV_CODEC_CAP_TRUNCATED | AV_CODEC_CAP_DELAY |
AV_CODEC_CAP_FRAME_THREADS,
.caps_internal = FF_CODEC_CAP_SKIP_FRAME_FILL_PARAM,
.flush = ff_mpeg_flush,
.max_lowres = 3,
.pix_fmts = ff_h263_hwaccel_pixfmt_list_420,
.profiles = NULL_IF_CONFIG_SMALL(ff_mpeg4_video_profiles),
.update_thread_context = ONLY_IF_THREADS_ENABLED(mpeg4_update_thread_context),
.priv_class = &mpeg4_class,
.hw_configs = (const AVCodecHWConfigInternal*[]) {
#if CONFIG_MPEG4_NVDEC_HWACCEL
HWACCEL_NVDEC(mpeg4),
#endif
#if CONFIG_MPEG4_VAAPI_HWACCEL
HWACCEL_VAAPI(mpeg4),
#endif
#if CONFIG_MPEG4_VDPAU_HWACCEL
HWACCEL_VDPAU(mpeg4),
#endif
#if CONFIG_MPEG4_VIDEOTOOLBOX_HWACCEL
HWACCEL_VIDEOTOOLBOX(mpeg4),
#endif
NULL
},
};
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_468_0 |
crossvul-cpp_data_good_329_0 | /*
* Copyright (c) 2016 Antonin Décimo, Jean-Raphaël Gaglione
*
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
/* \summary: Home Networking Control Protocol (HNCP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdlib.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent);
void
hncp_print(netdissect_options *ndo,
const u_char *cp, u_int length)
{
ND_PRINT((ndo, "hncp (%d)", length));
hncp_print_rec(ndo, cp, length, 1);
}
/* RFC7787 */
#define DNCP_REQUEST_NETWORK_STATE 1
#define DNCP_REQUEST_NODE_STATE 2
#define DNCP_NODE_ENDPOINT 3
#define DNCP_NETWORK_STATE 4
#define DNCP_NODE_STATE 5
#define DNCP_PEER 8
#define DNCP_KEEP_ALIVE_INTERVAL 9
#define DNCP_TRUST_VERDICT 10
/* RFC7788 */
#define HNCP_HNCP_VERSION 32
#define HNCP_EXTERNAL_CONNECTION 33
#define HNCP_DELEGATED_PREFIX 34
#define HNCP_PREFIX_POLICY 43
#define HNCP_DHCPV4_DATA 37 /* This is correct, see RFC 7788 Errata ID 5113. */
#define HNCP_DHCPV6_DATA 38 /* idem */
#define HNCP_ASSIGNED_PREFIX 35
#define HNCP_NODE_ADDRESS 36
#define HNCP_DNS_DELEGATED_ZONE 39
#define HNCP_DOMAIN_NAME 40
#define HNCP_NODE_NAME 41
#define HNCP_MANAGED_PSK 42
/* See type_mask in hncp_print_rec below */
#define RANGE_DNCP_RESERVED 0x10000
#define RANGE_HNCP_UNASSIGNED 0x10001
#define RANGE_DNCP_PRIVATE_USE 0x10002
#define RANGE_DNCP_FUTURE_USE 0x10003
static const struct tok type_values[] = {
{ DNCP_REQUEST_NETWORK_STATE, "Request network state" },
{ DNCP_REQUEST_NODE_STATE, "Request node state" },
{ DNCP_NODE_ENDPOINT, "Node endpoint" },
{ DNCP_NETWORK_STATE, "Network state" },
{ DNCP_NODE_STATE, "Node state" },
{ DNCP_PEER, "Peer" },
{ DNCP_KEEP_ALIVE_INTERVAL, "Keep-alive interval" },
{ DNCP_TRUST_VERDICT, "Trust-Verdict" },
{ HNCP_HNCP_VERSION, "HNCP-Version" },
{ HNCP_EXTERNAL_CONNECTION, "External-Connection" },
{ HNCP_DELEGATED_PREFIX, "Delegated-Prefix" },
{ HNCP_PREFIX_POLICY, "Prefix-Policy" },
{ HNCP_DHCPV4_DATA, "DHCPv4-Data" },
{ HNCP_DHCPV6_DATA, "DHCPv6-Data" },
{ HNCP_ASSIGNED_PREFIX, "Assigned-Prefix" },
{ HNCP_NODE_ADDRESS, "Node-Address" },
{ HNCP_DNS_DELEGATED_ZONE, "DNS-Delegated-Zone" },
{ HNCP_DOMAIN_NAME, "Domain-Name" },
{ HNCP_NODE_NAME, "Node-Name" },
{ HNCP_MANAGED_PSK, "Managed-PSK" },
{ RANGE_DNCP_RESERVED, "Reserved" },
{ RANGE_HNCP_UNASSIGNED, "Unassigned" },
{ RANGE_DNCP_PRIVATE_USE, "Private use" },
{ RANGE_DNCP_FUTURE_USE, "Future use" },
{ 0, NULL}
};
#define DH4OPT_DNS_SERVERS 6 /* RFC2132 */
#define DH4OPT_NTP_SERVERS 42 /* RFC2132 */
#define DH4OPT_DOMAIN_SEARCH 119 /* RFC3397 */
static const struct tok dh4opt_str[] = {
{ DH4OPT_DNS_SERVERS, "DNS-server" },
{ DH4OPT_NTP_SERVERS, "NTP-server"},
{ DH4OPT_DOMAIN_SEARCH, "DNS-search" },
{ 0, NULL }
};
#define DH6OPT_DNS_SERVERS 23 /* RFC3646 */
#define DH6OPT_DOMAIN_LIST 24 /* RFC3646 */
#define DH6OPT_SNTP_SERVERS 31 /* RFC4075 */
static const struct tok dh6opt_str[] = {
{ DH6OPT_DNS_SERVERS, "DNS-server" },
{ DH6OPT_DOMAIN_LIST, "DNS-search-list" },
{ DH6OPT_SNTP_SERVERS, "SNTP-servers" },
{ 0, NULL }
};
/*
* For IPv4-mapped IPv6 addresses, length of the prefix that precedes
* the 4 bytes of IPv4 address at the end of the IPv6 address.
*/
#define IPV4_MAPPED_HEADING_LEN 12
/*
* Is an IPv6 address an IPv4-mapped address?
*/
static inline int
is_ipv4_mapped_address(const u_char *addr)
{
/* The value of the prefix */
static const u_char ipv4_mapped_heading[IPV4_MAPPED_HEADING_LEN] =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF };
return memcmp(addr, ipv4_mapped_heading, IPV4_MAPPED_HEADING_LEN) == 0;
}
static const char *
format_nid(const u_char *data)
{
static char buf[4][sizeof("01:01:01:01")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%02x:%02x:%02x:%02x",
data[0], data[1], data[2], data[3]);
return buf[i];
}
static const char *
format_256(const u_char *data)
{
static char buf[4][sizeof("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%016" PRIx64 "%016" PRIx64 "%016" PRIx64 "%016" PRIx64,
EXTRACT_64BITS(data),
EXTRACT_64BITS(data + 8),
EXTRACT_64BITS(data + 16),
EXTRACT_64BITS(data + 24)
);
return buf[i];
}
static const char *
format_interval(const uint32_t n)
{
static char buf[4][sizeof("0000000.000s")];
static int i = 0;
i = (i + 1) % 4;
snprintf(buf[i], sizeof(buf[i]), "%u.%03us", n / 1000, n % 1000);
return buf[i];
}
static const char *
format_ip6addr(netdissect_options *ndo, const u_char *cp)
{
if (is_ipv4_mapped_address(cp))
return ipaddr_string(ndo, cp + IPV4_MAPPED_HEADING_LEN);
else
return ip6addr_string(ndo, cp);
}
static int
print_prefix(netdissect_options *ndo, const u_char *prefix, u_int max_length)
{
int plenbytes;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::/128")];
if (prefix[0] >= 96 && max_length >= IPV4_MAPPED_HEADING_LEN + 1 &&
is_ipv4_mapped_address(&prefix[1])) {
struct in_addr addr;
u_int plen;
plen = prefix[0]-96;
if (32 < plen)
return -1;
max_length -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
if (max_length < (u_int)plenbytes + IPV4_MAPPED_HEADING_LEN)
return -3;
memcpy(&addr, &prefix[1 + IPV4_MAPPED_HEADING_LEN], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, sizeof(buf), "%s/%d", ipaddr_string(ndo, &addr), plen);
plenbytes += 1 + IPV4_MAPPED_HEADING_LEN;
} else {
plenbytes = decode_prefix6(ndo, prefix, max_length, buf, sizeof(buf));
if (plenbytes < 0)
return plenbytes;
}
ND_PRINT((ndo, "%s", buf));
return plenbytes;
}
static int
print_dns_label(netdissect_options *ndo,
const u_char *cp, u_int max_length, int print)
{
u_int length = 0;
while (length < max_length) {
u_int lab_length = cp[length++];
if (lab_length == 0)
return (int)length;
if (length > 1 && print)
safeputchar(ndo, '.');
if (length+lab_length > max_length) {
if (print)
safeputs(ndo, cp+length, max_length-length);
break;
}
if (print)
safeputs(ndo, cp+length, lab_length);
length += lab_length;
}
if (print)
ND_PRINT((ndo, "[|DNS]"));
return -1;
}
static int
dhcpv4_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint8_t type, optlen;
i = 0;
while (i < length) {
if (i + 2 > length)
return -1;
tlv = cp + i;
type = (uint8_t)tlv[0];
optlen = (uint8_t)tlv[1];
value = tlv + 2;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh4opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 2 ));
if (i + 2 + optlen > length)
return -1;
switch (type) {
case DH4OPT_DNS_SERVERS:
case DH4OPT_NTP_SERVERS: {
if (optlen < 4 || optlen % 4 != 0) {
return -1;
}
for (t = 0; t < optlen; t += 4)
ND_PRINT((ndo, " %s", ipaddr_string(ndo, value + t)));
}
break;
case DH4OPT_DOMAIN_SEARCH: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 2 + optlen;
}
return 0;
}
static int
dhcpv6_print(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
u_int i, t;
const u_char *tlv, *value;
uint16_t type, optlen;
i = 0;
while (i < length) {
if (i + 4 > length)
return -1;
tlv = cp + i;
type = EXTRACT_16BITS(tlv);
optlen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
ND_PRINT((ndo, "%s", tok2str(dh6opt_str, "Unknown", type)));
ND_PRINT((ndo," (%u)", optlen + 4 ));
if (i + 4 + optlen > length)
return -1;
switch (type) {
case DH6OPT_DNS_SERVERS:
case DH6OPT_SNTP_SERVERS: {
if (optlen % 16 != 0) {
ND_PRINT((ndo, " %s", istr));
return -1;
}
for (t = 0; t < optlen; t += 16)
ND_PRINT((ndo, " %s", ip6addr_string(ndo, value + t)));
}
break;
case DH6OPT_DOMAIN_LIST: {
const u_char *tp = value;
while (tp < value + optlen) {
ND_PRINT((ndo, " "));
if ((tp = ns_nprint(ndo, tp, value + optlen)) == NULL)
return -1;
}
}
break;
}
i += 4 + optlen;
}
return 0;
}
/* Determine in-line mode */
static int
is_in_line(netdissect_options *ndo, int indent)
{
return indent - 1 >= ndo->ndo_vflag && ndo->ndo_vflag < 3;
}
static void
print_type_in_line(netdissect_options *ndo,
uint32_t type, int count, int indent, int *first_one)
{
if (count > 0) {
if (*first_one) {
*first_one = 0;
if (indent > 1) {
u_int t;
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
} else {
ND_PRINT((ndo, " "));
}
} else {
ND_PRINT((ndo, ", "));
}
ND_PRINT((ndo, "%s", tok2str(type_values, "Easter Egg", type)));
if (count > 1)
ND_PRINT((ndo, " (x%d)", count));
}
}
void
hncp_print_rec(netdissect_options *ndo,
const u_char *cp, u_int length, int indent)
{
const int in_line = is_in_line(ndo, indent);
int first_one = 1;
u_int i, t;
uint32_t last_type_mask = 0xffffffffU;
int last_type_count = -1;
const u_char *tlv, *value;
uint16_t type, bodylen;
uint32_t type_mask;
i = 0;
while (i < length) {
tlv = cp + i;
if (!in_line) {
ND_PRINT((ndo, "\n"));
for (t = indent; t > 0; t--)
ND_PRINT((ndo, "\t"));
}
ND_TCHECK2(*tlv, 4);
if (i + 4 > length)
goto invalid;
type = EXTRACT_16BITS(tlv);
bodylen = EXTRACT_16BITS(tlv + 2);
value = tlv + 4;
ND_TCHECK2(*value, bodylen);
if (i + bodylen + 4 > length)
goto invalid;
type_mask =
(type == 0) ? RANGE_DNCP_RESERVED:
(44 <= type && type <= 511) ? RANGE_HNCP_UNASSIGNED:
(768 <= type && type <= 1023) ? RANGE_DNCP_PRIVATE_USE:
RANGE_DNCP_FUTURE_USE;
if (type == 6 || type == 7)
type_mask = RANGE_DNCP_FUTURE_USE;
/* defined types */
{
t = 0;
while (1) {
u_int key = type_values[t++].v;
if (key > 0xffff)
break;
if (key == type) {
type_mask = type;
break;
}
}
}
if (in_line) {
if (last_type_mask == type_mask) {
last_type_count++;
} else {
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
last_type_mask = type_mask;
last_type_count = 1;
}
goto skip_multiline;
}
ND_PRINT((ndo,"%s", tok2str(type_values, "Easter Egg (42)", type_mask) ));
if (type_mask > 0xffff)
ND_PRINT((ndo,": type=%u", type ));
ND_PRINT((ndo," (%u)", bodylen + 4 ));
switch (type_mask) {
case DNCP_REQUEST_NETWORK_STATE: {
if (bodylen != 0)
ND_PRINT((ndo, " %s", istr));
}
break;
case DNCP_REQUEST_NODE_STATE: {
const char *node_identifier;
if (bodylen != 4) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
ND_PRINT((ndo, " NID: %s", node_identifier));
}
break;
case DNCP_NODE_ENDPOINT: {
const char *node_identifier;
uint32_t endpoint_identifier;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
endpoint_identifier = EXTRACT_32BITS(value + 4);
ND_PRINT((ndo, " NID: %s EPID: %08x",
node_identifier,
endpoint_identifier
));
}
break;
case DNCP_NETWORK_STATE: {
uint64_t hash;
if (bodylen != 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
hash = EXTRACT_64BITS(value);
ND_PRINT((ndo, " hash: %016" PRIx64, hash));
}
break;
case DNCP_NODE_STATE: {
const char *node_identifier, *interval;
uint32_t sequence_number;
uint64_t hash;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
node_identifier = format_nid(value);
sequence_number = EXTRACT_32BITS(value + 4);
interval = format_interval(EXTRACT_32BITS(value + 8));
hash = EXTRACT_64BITS(value + 12);
ND_PRINT((ndo, " NID: %s seqno: %u %s hash: %016" PRIx64,
node_identifier,
sequence_number,
interval,
hash
));
hncp_print_rec(ndo, value+20, bodylen-20, indent+1);
}
break;
case DNCP_PEER: {
const char *peer_node_identifier;
uint32_t peer_endpoint_identifier, endpoint_identifier;
if (bodylen != 12) {
ND_PRINT((ndo, " %s", istr));
break;
}
peer_node_identifier = format_nid(value);
peer_endpoint_identifier = EXTRACT_32BITS(value + 4);
endpoint_identifier = EXTRACT_32BITS(value + 8);
ND_PRINT((ndo, " Peer-NID: %s Peer-EPID: %08x Local-EPID: %08x",
peer_node_identifier,
peer_endpoint_identifier,
endpoint_identifier
));
}
break;
case DNCP_KEEP_ALIVE_INTERVAL: {
uint32_t endpoint_identifier;
const char *interval;
if (bodylen < 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
interval = format_interval(EXTRACT_32BITS(value + 4));
ND_PRINT((ndo, " EPID: %08x Interval: %s",
endpoint_identifier,
interval
));
}
break;
case DNCP_TRUST_VERDICT: {
if (bodylen <= 36) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Verdict: %u Fingerprint: %s Common Name: ",
*value,
format_256(value + 4)));
safeputs(ndo, value + 36, bodylen - 36);
}
break;
case HNCP_HNCP_VERSION: {
uint16_t capabilities;
uint8_t M, P, H, L;
if (bodylen < 5) {
ND_PRINT((ndo, " %s", istr));
break;
}
capabilities = EXTRACT_16BITS(value + 2);
M = (uint8_t)((capabilities >> 12) & 0xf);
P = (uint8_t)((capabilities >> 8) & 0xf);
H = (uint8_t)((capabilities >> 4) & 0xf);
L = (uint8_t)(capabilities & 0xf);
ND_PRINT((ndo, " M: %u P: %u H: %u L: %u User-agent: ",
M, P, H, L
));
safeputs(ndo, value + 4, bodylen - 4);
}
break;
case HNCP_EXTERNAL_CONNECTION: {
/* Container TLV */
hncp_print_rec(ndo, value, bodylen, indent+1);
}
break;
case HNCP_DELEGATED_PREFIX: {
int l;
if (bodylen < 9 || bodylen < 9 + (value[8] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " VLSO: %s PLSO: %s Prefix: ",
format_interval(EXTRACT_32BITS(value)),
format_interval(EXTRACT_32BITS(value + 4))
));
l = print_prefix(ndo, value + 8, bodylen - 8);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
l += 8 + (-l & 3);
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_PREFIX_POLICY: {
uint8_t policy;
int l;
if (bodylen < 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
policy = value[0];
ND_PRINT((ndo, " type: "));
if (policy == 0) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Internet connectivity"));
} else if (policy >= 1 && policy <= 128) {
ND_PRINT((ndo, "Dest-Prefix: "));
l = print_prefix(ndo, value, bodylen);
if (l == -1) {
ND_PRINT((ndo, "(length is invalid)"));
break;
}
if (l < 0) {
/*
* We've already checked that we've captured the
* entire TLV, based on its length, so this will
* either be -1, meaning "the prefix length is
* greater than the longest possible address of
* that type" (i.e., > 32 for IPv4 or > 128 for
* IPv6", or -3, meaning "the prefix runs past
* the end of the TLV".
*/
ND_PRINT((ndo, " %s", istr));
break;
}
} else if (policy == 129) {
ND_PRINT((ndo, "DNS domain: "));
print_dns_label(ndo, value+1, bodylen-1, 1);
} else if (policy == 130) {
ND_PRINT((ndo, "Opaque UTF-8: "));
safeputs(ndo, value + 1, bodylen - 1);
} else if (policy == 131) {
if (bodylen != 1) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, "Restrictive assignment"));
} else if (policy >= 132) {
ND_PRINT((ndo, "Unknown (%u)", policy)); /* Reserved for future additions */
}
}
break;
case HNCP_DHCPV4_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv4_print(ndo, value, bodylen, indent+1) != 0)
goto invalid;
}
break;
case HNCP_DHCPV6_DATA: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
if (dhcpv6_print(ndo, value, bodylen, indent+1) != 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
}
break;
case HNCP_ASSIGNED_PREFIX: {
uint8_t prty;
int l;
if (bodylen < 6 || bodylen < 6 + (value[5] + 7) / 8) {
ND_PRINT((ndo, " %s", istr));
break;
}
prty = (uint8_t)(value[4] & 0xf);
ND_PRINT((ndo, " EPID: %08x Prty: %u",
EXTRACT_32BITS(value),
prty
));
ND_PRINT((ndo, " Prefix: "));
if ((l = print_prefix(ndo, value + 5, bodylen - 5)) < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
l += 5;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_NODE_ADDRESS: {
uint32_t endpoint_identifier;
const char *ip_address;
if (bodylen < 20) {
ND_PRINT((ndo, " %s", istr));
break;
}
endpoint_identifier = EXTRACT_32BITS(value);
ip_address = format_ip6addr(ndo, value + 4);
ND_PRINT((ndo, " EPID: %08x IP Address: %s",
endpoint_identifier,
ip_address
));
hncp_print_rec(ndo, value + 20, bodylen - 20, indent+1);
}
break;
case HNCP_DNS_DELEGATED_ZONE: {
const char *ip_address;
int len;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
ip_address = format_ip6addr(ndo, value);
ND_PRINT((ndo, " IP-Address: %s %c%c%c ",
ip_address,
(value[16] & 4) ? 'l' : '-',
(value[16] & 2) ? 'b' : '-',
(value[16] & 1) ? 's' : '-'
));
len = print_dns_label(ndo, value+17, bodylen-17, 1);
if (len < 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
len += 17;
len += -len & 3;
if (bodylen >= len)
hncp_print_rec(ndo, value+len, bodylen-len, indent+1);
}
break;
case HNCP_DOMAIN_NAME: {
if (bodylen == 0) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " Domain: "));
print_dns_label(ndo, value, bodylen, 1);
}
break;
case HNCP_NODE_NAME: {
u_int l;
if (bodylen < 17) {
ND_PRINT((ndo, " %s", istr));
break;
}
l = value[16];
if (bodylen < 17 + l) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " IP-Address: %s Name: ",
format_ip6addr(ndo, value)
));
if (l < 64) {
safeputchar(ndo, '"');
safeputs(ndo, value + 17, l);
safeputchar(ndo, '"');
} else {
ND_PRINT((ndo, "%s", istr));
}
l += 17;
l += -l & 3;
if (bodylen >= l)
hncp_print_rec(ndo, value + l, bodylen - l, indent+1);
}
break;
case HNCP_MANAGED_PSK: {
if (bodylen < 32) {
ND_PRINT((ndo, " %s", istr));
break;
}
ND_PRINT((ndo, " PSK: %s", format_256(value)));
hncp_print_rec(ndo, value + 32, bodylen - 32, indent+1);
}
break;
case RANGE_DNCP_RESERVED:
case RANGE_HNCP_UNASSIGNED:
case RANGE_DNCP_PRIVATE_USE:
case RANGE_DNCP_FUTURE_USE:
break;
}
skip_multiline:
i += 4 + bodylen + (-bodylen & 3);
}
print_type_in_line(ndo, last_type_mask, last_type_count, indent, &first_one);
return;
trunc:
ND_PRINT((ndo, "%s", "[|hncp]"));
return;
invalid:
ND_PRINT((ndo, "%s", istr));
return;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_329_0 |
crossvul-cpp_data_good_351_7 | /*
* card-gpk: Driver for GPK 4000 cards
*
* Copyright (C) 2002 Olaf Kirch <okir@suse.de>
*
* 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 2.1 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if HAVE_CONFIG_H
#include "config.h"
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <stdlib.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include "internal.h"
#include "cardctl.h"
#include "pkcs15.h"
#define GPK_SEL_MF 0x00
#define GPK_SEL_DF 0x01
#define GPK_SEL_EF 0x02
#define GPK_SEL_AID 0x04
#define GPK_FID_MF 0x3F00
#define GPK_FTYPE_SC 0x21
#define GPK_SIGN_RSA_MD5 0x11
#define GPK_SIGN_RSA_SHA 0x12
#define GPK_SIGN_RSA_SSL 0x18
#define GPK_VERIFY_RSA_MD5 0x21
#define GPK_VERIFY_RSA_SHA 0x22
#define GPK_AUTH_RSA_MD5 0x31
#define GPK_AUTH_RSA_SHA 0x32
#define GPK_AUTH_RSA_SSL 0x38
#define GPK_UNWRAP_RSA 0x77
#define GPK_MAX_PINS 8
#define GPK_HASH_CHUNK 62
/*
* GPK4000 private data
*/
struct gpk_private_data {
/* The GPK usually do file offsets in multiples of
* 4 bytes. This can be customized however. We
* should really query for this during gpk_init */
unsigned int offset_shift;
unsigned int offset_mask;
unsigned int locked : 1,
sample_card : 1;
/* access control bits of file most recently selected */
unsigned short int ac[3];
/* is non-zero if we should use secure messaging */
unsigned key_set : 1;
unsigned int key_reference;
u8 key[16];
/* crypto related data from set_security_env */
unsigned int sec_algorithm;
unsigned int sec_hash_len;
unsigned int sec_mod_len;
unsigned int sec_padding;
};
#define DRVDATA(card) ((struct gpk_private_data *) ((card)->drv_data))
static int gpk_get_info(sc_card_t *, int, int, u8 *, size_t);
/*
* ATRs of GPK4000 cards courtesy of libscez
*/
static struct sc_atr_table gpk_atrs[] = {
{ "3B:27:00:80:65:A2:04:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_s, 0, NULL },
{ "3B:27:00:80:65:A2:05:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sp, 0, NULL },
{ "3B:27:00:80:65:A2:0C:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_su256, 0, NULL },
{ "3B:A7:00:40:14:80:65:A2:14:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sdo, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:08:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_8K, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_16K, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:02:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
{ "3B:A7:00:40:18:80:65:A2:09:01:03:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
/*
* Driver and card ops structures
*/
static struct sc_card_operations gpk_ops, *iso_ops;
static struct sc_card_driver gpk_drv = {
"Gemplus GPK",
"gpk",
&gpk_ops,
NULL, 0, NULL
};
/*
* return 1 if this driver can handle the card
*/
static int
gpk_match_card(sc_card_t *card)
{
int i;
i = _sc_match_atr(card, gpk_atrs, &card->type);
if (i < 0) {
const u8 *hist_bytes = card->reader->atr_info.hist_bytes;
/* Gemplus GPK docs say we can use just the
* FMN and PRN fields of the historical bytes
* to recognize a GPK card
* See Table 43, pp. 188
* We'll use the first 2 bytes as well
*/
if ((card->reader->atr_info.hist_bytes_len >= 7)
&& (hist_bytes[0] == 0x80)
&& (hist_bytes[1] == 0x65)
&& (hist_bytes[2] == 0xa2)) { /* FMN */
if (hist_bytes[3] == 0x08) { /* PRN? */
card->type = SC_CARD_TYPE_GPK_GPK8000;
return 1;
}
if (hist_bytes[3] == 0x09) { /* PRN? */
card->type = SC_CARD_TYPE_GPK_GPK16000;
return 1;
}
}
return 0;
}
return 1;
}
/*
* Initialize the card struct
*/
static int
gpk_init(sc_card_t *card)
{
struct gpk_private_data *priv;
unsigned long exponent, flags, kg;
unsigned char info[13];
card->drv_data = priv = calloc(1, sizeof(*priv));
if (card->drv_data == NULL)
return SC_ERROR_OUT_OF_MEMORY;
/* read/write/update binary expect offset to be the
* number of 32 bit words.
* offset_shift is the shift value.
* offset_mask is the corresponding mask. */
priv->offset_shift = 2;
priv->offset_mask = 3;
card->cla = 0x00;
/* Set up algorithm info. GPK 16000 will do any RSA
* exponent, earlier ones are restricted to 0x10001 */
flags = SC_ALGORITHM_RSA_HASH_MD5 | SC_ALGORITHM_RSA_HASH_SHA1
| SC_ALGORITHM_RSA_HASH_MD5_SHA1;
flags |= SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_PAD_ANSI
| SC_ALGORITHM_RSA_PAD_ISO9796;
exponent = (card->type < SC_CARD_TYPE_GPK_GPK16000) ? 0x10001 : 0;
kg = (card->type >= SC_CARD_TYPE_GPK_GPK8000) ? SC_ALGORITHM_ONBOARD_KEY_GEN : 0;
_sc_card_add_rsa_alg(card, 512, flags|kg, exponent);
_sc_card_add_rsa_alg(card, 768, flags, exponent);
_sc_card_add_rsa_alg(card, 1024, flags|kg, exponent);
/* Inspect the LOCK byte */
if (gpk_get_info(card, 0x02, 0xA4, info, sizeof(info)) >= 0) {
if (info[12] & 0x40) {
priv->offset_shift = 0;
priv->offset_mask = 0;
}
if (info[12] & 0x10) {
/* DSA supported - add algo information.
* It's highly unlikely we'll ever see this.
*/
}
if (info[12] & 0x08) {
priv->locked = 1;
}
/* Sample cards use a transport key of "TEST KEYTEST KEY" */
if (!memcmp(info+5, "\x00\xff\x00", 3)) {
priv->sample_card = 1;
}
}
/* State that we have an RNG */
card->caps |= SC_CARD_CAP_RNG;
/* Make sure max send/receive size is 4 byte aligned and <256. */
card->max_recv_size = 252;
return SC_SUCCESS;
}
/*
* Card is being closed; discard any private data etc
*/
static int
gpk_finish(sc_card_t *card)
{
if (card->drv_data)
free(card->drv_data);
card->drv_data = NULL;
return 0;
}
/*
* Select a DF/EF
*/
static int
match_path(sc_card_t *card, unsigned short int **pathptr, size_t *pathlen,
int need_info)
{
unsigned short int *curptr, *ptr;
size_t curlen, len;
size_t i;
curptr = (unsigned short int *) card->cache.current_path.value;
curlen = card->cache.current_path.len;
ptr = *pathptr;
len = *pathlen;
if (curlen < 1 || len < 1)
return 0;
/* Make sure path starts with MF.
* Note the cached path should always begin with MF. */
if (ptr[0] != GPK_FID_MF || curptr[0] != GPK_FID_MF)
return 0;
for (i = 1; i < len && i < curlen; i++) {
if (ptr[i] != curptr[i])
break;
}
if (len < curlen) {
/* Caller asked us to select the DF, but the
* current file is some EF within the DF we're
* interested in. Say ACK */
if (len == 2)
goto okay;
/* Anything else won't work */
return 0;
}
/* In the case of an exact match:
* If the caller needs info on the file to be selected,
* make sure we at least select the file itself.
* If the DF matches the current DF, just return the
* FID */
if (i == len && need_info) {
if (i > 1) {
*pathptr = ptr + len - 1;
*pathlen = len - 1;
return 1;
}
/* bummer */
return 0;
}
okay:
*pathptr = ptr + i;
*pathlen = len - i;
return 1;
}
static void
ac_to_acl(unsigned int ac, sc_file_t *file, unsigned int op)
{
unsigned int npins, pin;
npins = (ac >> 14) & 3;
if (npins == 3) {
sc_file_add_acl_entry(file, op, SC_AC_NEVER,
SC_AC_KEY_REF_NONE);
return;
}
sc_file_add_acl_entry(file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE);
pin = ac & 0xFF;
if (npins >= 1)
sc_file_add_acl_entry(file, op, SC_AC_CHV, (pin >> 4) & 0xF);
if (npins == 2)
sc_file_add_acl_entry(file, op, SC_AC_CHV, pin & 0xF);
/* Check whether secure messaging key is specified */
if (ac & 0x3F00)
sc_file_add_acl_entry(file, op, SC_AC_PRO, (ac & 0x3F00) >> 8);
}
/*
* Convert ACLs requested by the application to access condition
* bits supported by the GPK. Since these do not map 1:1 there's
* some fuzz involved.
*/
static void
acl_to_ac(sc_file_t *file, unsigned int op, u8 *ac)
{
const sc_acl_entry_t *acl;
unsigned int npins = 0;
ac[0] = ac[1] = 0;
if ((acl = sc_file_get_acl_entry(file, op)) == NULL)
return;
assert(acl->method != SC_AC_UNKNOWN);
switch (acl->method) {
case SC_AC_NEVER:
ac[0] = 0xC0;
return;
case SC_AC_NONE:
return;
}
while (acl) {
if (acl->method == SC_AC_CHV) {
/* Support up to 2 PINS only */
if (++npins >= 2)
continue;
ac[1] >>= 4;
ac[1] |= acl->key_ref << 4;
ac[0] += 0x40;
}
if (acl->method == SC_AC_PRO) {
ac[0] |= acl->key_ref & 0x1f;
}
acl = acl->next;
}
}
static int
gpk_parse_fci(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *end, *next;
unsigned int tag, len;
end = buf + buflen;
for (; buf + 2 < end; buf = next) {
next = buf + 2 + buf[1];
if (next > end)
break;
tag = *buf++;
len = *buf++;
if (tag == 0x84) {
/* unknown purpose - usually the name, but
* the content looks weird, such as
* 84 0D A0 00 00 00 18 0F 00 00 01 63 00 01 04
*/
} else
if (tag == 0xC1 && len >= 2) {
/* Seems to be the file id, followed by something
* C1 04 02 00 00 00 */
file->id = (buf[0] << 8) | buf[1];
} else
if (tag == 0xC2) {
/* unknown purpose
* C2 01 01
*/
}
}
return 0;
}
static int
gpk_parse_fileinfo(sc_card_t *card,
const u8 *buf, size_t buflen,
sc_file_t *file)
{
const u8 *sp, *end, *next;
int i, rc;
memset(file, 0, sizeof(*file));
for (i = 0; i < SC_MAX_AC_OPS; i++)
sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
end = buf + buflen;
for (sp = buf; sp + 2 < end; sp = next) {
next = sp + 2 + sp[1];
if (next > end)
break;
if (sp[0] == 0x84) {
/* ignore if name is longer than what it should be */
if (sp[1] > sizeof(file->name))
continue;
memset(file->name, 0, sizeof(file->name));
memcpy(file->name, sp+2, sp[1]);
} else
if (sp[0] == 0x85) {
unsigned int ac[3], n;
if (sp + 11 + 2*3 >= end)
break;
file->id = (sp[4] << 8) | sp[5];
file->size = (sp[8] << 8) | sp[9];
file->record_length = sp[7];
/* Map ACLs. Note the third AC byte is
* valid of EFs only */
for (n = 0; n < 3; n++)
ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
/* Examine file type */
switch (sp[6] & 7) {
case 0x01: case 0x02: case 0x03: case 0x04:
case 0x05: case 0x06: case 0x07:
file->type = SC_FILE_TYPE_WORKING_EF;
file->ef_structure = sp[6] & 7;
ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
ac_to_acl(ac[2], file, SC_AC_OP_READ);
break;
case 0x00: /* 0x38 is DF */
file->type = SC_FILE_TYPE_DF;
/* Icky: the GPK uses different ACLs
* for creating data files and
* 'sensitive' i.e. key files */
ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
SC_AC_NONE, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
SC_AC_NEVER, SC_AC_KEY_REF_NONE);
break;
}
} else
if (sp[0] == 0x6f) {
/* oops - this is a directory with an IADF.
* This happens with the personalized GemSafe cards
* for instance. */
file->type = SC_FILE_TYPE_DF;
rc = gpk_parse_fci(card, sp + 2, sp[1], file);
if (rc < 0)
return rc;
}
}
if (file->record_length)
file->record_count = file->size / file->record_length;
file->magic = SC_FILE_MAGIC;
return 0;
}
static int
gpk_select(sc_card_t *card, int kind,
const u8 *buf, size_t buflen,
sc_file_t **file)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 resbuf[256];
int r;
/* If we're about to select a DF, invalidate secure messaging keys */
if (kind == GPK_SEL_MF || kind == GPK_SEL_DF) {
memset(priv->key, 0, sizeof(priv->key));
priv->key_set = 0;
}
/* do the apdu thing */
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x00;
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.ins = 0xA4;
apdu.p1 = kind;
apdu.p2 = 0;
apdu.data = buf;
apdu.datalen = buflen;
apdu.lc = apdu.datalen;
if (file) {
apdu.cse = SC_APDU_CASE_4_SHORT;
apdu.resp = resbuf;
apdu.resplen = sizeof(resbuf);
apdu.le = sizeof(resbuf);
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Nothing we can say about it... invalidate
* path cache */
if (kind == GPK_SEL_AID) {
card->cache.current_path.len = 0;
}
if (file == NULL)
return 0;
*file = sc_file_new();
r = gpk_parse_fileinfo(card, apdu.resp, apdu.resplen, *file);
if (r < 0) {
sc_file_free(*file);
*file = NULL;
}
return r;
}
static int
gpk_select_id(sc_card_t *card, int kind, unsigned int fid,
sc_file_t **file)
{
sc_path_t *cp = &card->cache.current_path;
u8 fbuf[2];
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_select_id(0x%04X, kind=%u)\n", fid, kind);
fbuf[0] = fid >> 8;
fbuf[1] = fid & 0xff;
r = gpk_select(card, kind, fbuf, 2, file);
/* Fix up the path cache.
* NB we never cache the ID of an EF, just the DF path */
if (r == 0) {
unsigned short int *path;
switch (kind) {
case GPK_SEL_MF:
cp->len = 0;
/* fallthru */
case GPK_SEL_DF:
assert(cp->len + 1 <= SC_MAX_PATH_SIZE / 2);
path = (unsigned short int *) cp->value;
path[cp->len++] = fid;
}
} else {
cp->len = 0;
}
return r;
}
static int
gpk_select_file(sc_card_t *card, const sc_path_t *path,
sc_file_t **file)
{
unsigned short int pathtmp[SC_MAX_PATH_SIZE/2];
unsigned short int *pathptr;
size_t pathlen, n;
int locked = 0, r = 0, use_relative = 0, retry = 1;
u8 leaf_type;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
/* Handle the AID case first */
if (path->type == SC_PATH_TYPE_DF_NAME) {
if (path->len > 16)
return SC_ERROR_INVALID_ARGUMENTS;
r = gpk_select(card, GPK_SEL_AID,
path->value, path->len, file);
goto done;
}
/* Now we know we're dealing with 16bit FIDs, either as
* an absolute path name (SC_PATH_TYPE_PATH) or a relative
* FID (SC_PATH_TYPE_FILE_ID)
*
* The API should really tell us whether this is a DF or EF
* we're selecting. All we can do is read tea leaves...
*/
leaf_type = GPK_SEL_EF;
try_again:
if ((path->len & 1) || path->len > sizeof(pathtmp))
return SC_ERROR_INVALID_ARGUMENTS;
pathptr = pathtmp;
for (n = 0; n < path->len; n += 2)
pathptr[n>>1] = (path->value[n] << 8)|path->value[n+1];
pathlen = path->len >> 1;
/* See whether we can skip an initial portion of the
* (absolute) path */
if (path->type == SC_PATH_TYPE_PATH) {
/* Do not retry selecting if this cannot be a DF */
if ((pathptr[0] == GPK_FID_MF && pathlen > 2)
|| (pathptr[0] != GPK_FID_MF && pathlen > 1))
retry = 0;
use_relative = match_path(card, &pathptr, &pathlen, file != 0);
if (pathlen == 0)
goto done;
} else {
/* SC_PATH_TYPE_FILEID */
if (pathlen > 1)
return SC_ERROR_INVALID_ARGUMENTS;
use_relative = 1;
}
if (pathlen == 1 && pathptr[0] == GPK_FID_MF) {
/* Select just the MF */
leaf_type = GPK_SEL_MF;
} else {
if (!locked++) {
r = sc_lock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed");
}
/* Do we need to select the MF first? */
if (!use_relative) {
r = gpk_select_id(card, GPK_SEL_MF, GPK_FID_MF, NULL);
if (r)
sc_unlock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unable to select MF");
/* Consume the MF FID if it's there */
if (pathptr[0] == GPK_FID_MF) {
pathptr++;
pathlen--;
}
if (pathlen == 0)
goto done;
}
/* Next comes a DF, if at all.
* This loop can deal with nesting levels > 1 even
* though the GPK4000 doesn't support it. */
while (pathlen > 1) {
r = gpk_select_id(card, GPK_SEL_DF, pathptr[0], NULL);
if (r)
sc_unlock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Unable to select DF");
pathptr++;
pathlen--;
}
}
/* Remaining component will be a DF or EF. How do we find out?
* All we can do is try */
r = gpk_select_id(card, leaf_type, pathptr[0], file);
if (r) {
/* Did we guess EF, and were wrong? If so, invalidate
* path cache and try again; this time aiming for a DF */
if (leaf_type == GPK_SEL_EF && retry) {
card->cache.current_path.len = 0;
leaf_type = GPK_SEL_DF;
goto try_again;
}
}
done:
if (locked)
sc_unlock(card);
return r;
}
/*
* GPK versions of {read,write,update}_binary functions.
* Required because by default the GPKs do word offsets
*/
static int
gpk_read_binary(sc_card_t *card, unsigned int offset,
u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->read_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
static int
gpk_write_binary(sc_card_t *card, unsigned int offset,
const u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->write_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
static int
gpk_update_binary(sc_card_t *card, unsigned int offset,
const u8 *buf, size_t count, unsigned long flags)
{
struct gpk_private_data *priv = DRVDATA(card);
if (offset & priv->offset_mask) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Invalid file offset (not a multiple of %d)",
priv->offset_mask + 1);
return SC_ERROR_INVALID_ARGUMENTS;
}
return iso_ops->update_binary(card, offset >> priv->offset_shift,
buf, count, flags);
}
/*
* Secure messaging
*/
static int
gpk_compute_crycks(sc_card_t *card, sc_apdu_t *apdu,
u8 *crycks1)
{
struct gpk_private_data *priv = DRVDATA(card);
u8 in[8], out[8], block[64];
unsigned int len = 0, i;
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX *ctx = NULL;
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
/* Fill block with 0x00 and then with the data. */
memset(block, 0x00, sizeof(block));
block[len++] = apdu->cla;
block[len++] = apdu->ins;
block[len++] = apdu->p1;
block[len++] = apdu->p2;
block[len++] = apdu->lc + 3;
if ((i = apdu->datalen) + len > sizeof(block))
i = sizeof(block) - len;
memcpy(block+len, apdu->data, i);
len += i;
/* Set IV */
memset(in, 0x00, 8);
EVP_EncryptInit_ex(ctx, EVP_des_ede_cbc(), NULL, priv->key, in);
for (i = 0; i < len; i += 8) {
if (!EVP_EncryptUpdate(ctx, out, &outl, &block[i], 8)) {
r = SC_ERROR_INTERNAL;
break;
}
}
EVP_CIPHER_CTX_free(ctx);
memcpy((u8 *) (apdu->data + apdu->datalen), out + 5, 3);
apdu->datalen += 3;
apdu->lc += 3;
apdu->le += 3;
if (crycks1)
memcpy(crycks1, out, 3);
sc_mem_clear(in, sizeof(in));
sc_mem_clear(out, sizeof(out));
sc_mem_clear(block, sizeof(block));
return r;
}
/*
* Verify secure messaging response
*/
static int
gpk_verify_crycks(sc_card_t *card, sc_apdu_t *apdu, u8 *crycks)
{
if (apdu->resplen < 3
|| memcmp(apdu->resp + apdu->resplen - 3, crycks, 3)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Invalid secure messaging reply\n");
return SC_ERROR_UNKNOWN_DATA_RECEIVED;
}
apdu->resplen -= 3;
return 0;
}
/*
* Create a file or directory.
* This is a bit tricky because we abuse the ef_structure
* field to transport file types that are non-standard
* (the GPK4000 has lots of bizarre file types).
*/
static int
gpk_create_file(sc_card_t *card, sc_file_t *file)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 data[28+3], crycks[3], resp[3];
size_t datalen, namelen;
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_create_file(0x%04X)\n", file->id);
/* Prepare APDU */
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x80; /* assume no secure messaging */
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.ins = 0xE0;
apdu.p2 = 0x00;
/* clear data */
memset(data, 0, sizeof(data));
datalen = 12;
/* FID */
data[0] = file->id >> 8;
data[1] = file->id & 0xFF;
/* encode ACLs */
if (file->type == SC_FILE_TYPE_DF) {
/* The GPK4000 has separate AC bits for
* creating sensitive files and creating
* data files. Since OpenSC has just the notion
* of "file" we use the same ACL for both AC words
*/
apdu.p1 = 0x01; /* create DF */
data[2] = 0x38;
acl_to_ac(file, SC_AC_OP_CREATE, data + 6);
acl_to_ac(file, SC_AC_OP_CREATE, data + 8);
if ((namelen = file->namelen) != 0) {
if (namelen > 16)
return SC_ERROR_INVALID_ARGUMENTS;
memcpy(data+datalen, file->name, namelen);
data[5] = namelen;
datalen += namelen;
}
} else {
apdu.p1 = 0x02; /* create EF */
data[2] = file->ef_structure;
data[3] = file->record_length;
data[4] = file->size >> 8;
data[5] = file->size & 0xff;
acl_to_ac(file, SC_AC_OP_UPDATE, data + 6);
acl_to_ac(file, SC_AC_OP_WRITE, data + 8);
acl_to_ac(file, SC_AC_OP_READ, data + 10);
}
apdu.data = data;
apdu.datalen = datalen;
apdu.lc = datalen;
if (priv->key_set) {
apdu.cla = 0x84;
apdu.cse = SC_APDU_CASE_4_SHORT;
r = gpk_compute_crycks(card, &apdu, crycks);
if (r)
return r;
apdu.resp = resp;
apdu.resplen = sizeof(resp); /* XXX? */
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* verify secure messaging response */
if (priv->key_set)
r = gpk_verify_crycks(card, &apdu, crycks);
return r;
}
/*
* Set the secure messaging key following a Select FileKey
*/
static int
gpk_set_filekey(const u8 *key, const u8 *challenge,
const u8 *r_rn, u8 *kats)
{
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX * ctx = NULL;
u8 out[16];
memcpy(out, key+8, 8);
memcpy(out+8, key, 8);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, key, NULL);
if (!EVP_EncryptUpdate(ctx, kats, &outl, r_rn+4, 8))
r = SC_ERROR_INTERNAL;
if (!EVP_CIPHER_CTX_cleanup(ctx))
r = SC_ERROR_INTERNAL;
if (r == SC_SUCCESS) {
EVP_CIPHER_CTX_init(ctx);
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, out, NULL);
if (!EVP_EncryptUpdate(ctx, kats+8, &outl, r_rn+4, 8))
r = SC_ERROR_INTERNAL;
if (!EVP_CIPHER_CTX_cleanup(ctx))
r = SC_ERROR_INTERNAL;
}
memset(out, 0, sizeof(out));
/* Verify Cryptogram presented by the card terminal
* XXX: what is the appropriate error code to return
* here? INVALID_ARGS doesn't seem quite right
*/
if (r == SC_SUCCESS) {
EVP_CIPHER_CTX_init(ctx);
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, kats, NULL);
if (!EVP_EncryptUpdate(ctx, out, &outl, challenge, 8))
r = SC_ERROR_INTERNAL;
if (memcmp(r_rn, out+4, 4) != 0)
r = SC_ERROR_INVALID_ARGUMENTS;
}
if (ctx)
EVP_CIPHER_CTX_free(ctx);
sc_mem_clear(out, sizeof(out));
return r;
}
/*
* Verify a key presented by the user for secure messaging
*/
static int
gpk_select_key(sc_card_t *card, int key_sfi, const u8 *buf, size_t buflen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 rnd[8], resp[258];
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
if (buflen != 16)
return SC_ERROR_INVALID_ARGUMENTS;
/* now do the SelFk */
RAND_bytes(rnd, sizeof(rnd));
memset(&apdu, 0, sizeof(apdu));
apdu.cla = 0x80;
apdu.cse = SC_APDU_CASE_4_SHORT;
apdu.ins = 0x28;
apdu.p1 = 0;
apdu.p2 = key_sfi;
apdu.data = rnd;
apdu.datalen = sizeof(rnd);
apdu.lc = apdu.datalen;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 12;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
if (apdu.resplen != 12) {
r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
} else
if ((r = gpk_set_filekey(buf, rnd, resp, priv->key)) == 0) {
priv->key_set = 1;
priv->key_reference = key_sfi;
}
sc_mem_clear(resp, sizeof(resp));
return r;
}
/*
* Select a security environment (Set Crypto Context in GPK docs).
* When we get here, the PK file has already been selected.
*
* Issue: the GPK distinguishes between "signing" and
* "card internal authentication". I don't know whether this
* makes any difference in practice...
*
* Issue: it seems that sc_compute_signature() does not hash
* the data for the caller. So what is the purpose of HASH_SHA
* and other flags?
*/
static int
gpk_set_security_env(sc_card_t *card,
const sc_security_env_t *env,
int se_num)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
unsigned int context, algorithm;
unsigned int file_id;
u8 sysrec[7];
int r;
/* According to several sources from GemPlus, they don't
* have off the shelf cards that do DSA. So I won't bother
* with implementing this stuff here. */
algorithm = SC_ALGORITHM_RSA;
if (env->flags & SC_SEC_ENV_ALG_PRESENT)
algorithm = env->algorithm;
if (algorithm != SC_ALGORITHM_RSA) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Algorithm not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
priv->sec_algorithm = algorithm;
/* If there's a key reference, it must be 0 */
if ((env->flags & SC_SEC_ENV_KEY_REF_PRESENT)
&& (env->key_ref_len != 1 || env->key_ref[0] != 0)) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unknown key referenced.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* Right now, the OpenSC flags do not support any padding
* other than PKCS#1. */
if (env->flags & SC_ALGORITHM_RSA_PAD_PKCS1)
priv->sec_padding = 0;
else if (env->flags & SC_ALGORITHM_RSA_PAD_ANSI)
priv->sec_padding = 1;
else if (env->flags & SC_ALGORITHM_RSA_PAD_ISO9796)
priv->sec_padding = 2;
else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Padding algorithm not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
switch (env->operation) {
case SC_SEC_OPERATION_SIGN:
/* Again, the following may not make any difference
* because we don't do any hashing on-card. But
* what the hell, we have all those nice macros,
* so why not use them :)
*/
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
context = GPK_SIGN_RSA_SHA;
priv->sec_hash_len = 20;
} else
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5_SHA1) {
context = GPK_SIGN_RSA_SSL;
priv->sec_hash_len = 36;
} else
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5) {
context = GPK_SIGN_RSA_MD5;
priv->sec_hash_len = 16;
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported signature algorithm");
return SC_ERROR_NOT_SUPPORTED;
}
break;
case SC_SEC_OPERATION_DECIPHER:
context = GPK_UNWRAP_RSA;
break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Crypto operation not supported.\n");
return SC_ERROR_NOT_SUPPORTED;
}
/* Get the file ID */
if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) {
if (env->file_ref.len != 2) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference: invalid length.\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
file_id = (env->file_ref.value[0] << 8)
| env->file_ref.value[1];
} else {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "File reference missing.\n");
return SC_ERROR_INVALID_ARGUMENTS;
}
/* Select the PK file. The caller has already selected
* the DF. */
r = gpk_select_id(card, GPK_SEL_EF, file_id, NULL);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to select PK file");
/* Read the sys record of the PK file to find out the key length */
r = sc_read_record(card, 1, sysrec, sizeof(sysrec),
SC_RECORD_BY_REC_NR);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to read PK sysrec");
if (r != 7 || sysrec[0] != 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "First record of file is not the sysrec");
return SC_ERROR_OBJECT_NOT_VALID;
}
if (sysrec[5] != 0x00) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Public key is not an RSA key");
return SC_ERROR_OBJECT_NOT_VALID;
}
switch (sysrec[1]) {
case 0x00: priv->sec_mod_len = 512 / 8; break;
case 0x10: priv->sec_mod_len = 768 / 8; break;
case 0x11: priv->sec_mod_len = 1024 / 8; break;
default:
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "Unsupported modulus length");
return SC_ERROR_OBJECT_NOT_VALID;
}
/* Now do SelectCryptoContext */
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0x80;
apdu.ins = 0xA6;
apdu.p1 = file_id & 0x1f;
apdu.p2 = context;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Restore security environment
* Not sure what this is supposed to do.
*/
static int
gpk_restore_security_env(sc_card_t *card, int se_num)
{
return 0;
}
/*
* Revert buffer (needed for all GPK crypto operations because
* they want LSB byte order internally
*/
static int
reverse(u8 *out, size_t outlen, const u8 *in, size_t inlen)
{
if (inlen > outlen)
return SC_ERROR_BUFFER_TOO_SMALL;
outlen = inlen;
while (inlen--)
*out++ = in[inlen];
return outlen;
}
/*
* Use the card's on-board hashing functions to hash some data
*/
#ifdef dontuse
static int
gpk_hash(sc_card_t *card, const u8 *data, size_t datalen)
{
sc_apdu_t apdu;
unsigned int count, chain, len;
int r;
chain = 0x01;
for (count = 0; count < datalen; count += len) {
unsigned char buffer[GPK_HASH_CHUNK+2];
if ((len = datalen - count) > GPK_HASH_CHUNK)
len = GPK_HASH_CHUNK;
else
chain |= 0x10;
buffer[0] = 0x55;
buffer[1] = len;
memcpy(buffer+2, data + count, len);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xDA;
apdu.p1 = chain;
apdu.p2 = len;
apdu.lc = len + 2;
apdu.data= buffer;
apdu.datalen = len + 2;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
chain = 0;
}
return 0;
}
#endif
/*
* Send the hashed data to the card.
*/
static int
gpk_init_hashed(sc_card_t *card, const u8 *digest, unsigned int len)
{
sc_apdu_t apdu;
u8 tsegid[64];
int r;
r = reverse(tsegid, sizeof(tsegid), digest, len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xEA;
apdu.lc = len;
apdu.data= tsegid;
apdu.datalen = len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Compute a signature.
* Note we hash everything manually and send it to the card.
*/
static int
gpk_compute_signature(sc_card_t *card, const u8 *data,
size_t data_len, u8 * out, size_t outlen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 cardsig[1024/8];
int r;
if (data_len > priv->sec_mod_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
data_len, priv->sec_mod_len);
return SC_ERROR_INTERNAL;
}
if (sizeof(cardsig) < priv->sec_mod_len)
return SC_ERROR_BUFFER_TOO_SMALL;
r = gpk_init_hashed(card, data, data_len);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to send hash to card");
/* Now sign the hash.
* The GPK has Internal Authenticate and PK_Sign. I am not
* sure what the difference between the two is. */
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x86;
apdu.p2 = priv->sec_padding;
apdu.resp= cardsig;
apdu.resplen = sizeof(cardsig);
apdu.le = priv->sec_mod_len;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* The GPK returns the signature as little endian numbers.
* Need to revert these */
r = reverse(out, outlen, cardsig, apdu.resplen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse signature");
return r;
}
/*
* Decrypt some RSA encrypted piece of data.
* Due to legal restrictions, the GPK will not let you see the
* full cleartext block, just the last N bytes.
* The GPK documentation refers to N as the MaxSessionKey size,
* probably because this feature limits the maximum size of an
* SSL session key you will be able to decrypt using this card.
*/
static int
gpk_decipher(sc_card_t *card, const u8 *in, size_t inlen,
u8 *out, size_t outlen)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 buffer[256];
int r;
if (inlen != priv->sec_mod_len) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
inlen, priv->sec_mod_len);
return SC_ERROR_INVALID_ARGUMENTS;
}
/* First revert the cryptogram */
r = reverse(buffer, sizeof(buffer), in, inlen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Cryptogram too large");
in = buffer;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x1C, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.lc = inlen;
apdu.data = in;
apdu.datalen = inlen;
apdu.le = 256; /* give me all you got :) */
apdu.resp = buffer;
apdu.resplen = sizeof(buffer);
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Reverse the data we got back */
r = reverse(out, outlen, buffer, apdu.resplen);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
return r;
}
/*
* Erase card
*/
static int
gpk_erase_card(sc_card_t *card)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
u8 offset;
int r;
SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
switch (card->type) {
case SC_CARD_TYPE_GPK_GPK4000_su256:
case SC_CARD_TYPE_GPK_GPK4000_sdo:
offset = 0x6B; /* courtesy gemplus hotline */
break;
case SC_CARD_TYPE_GPK_GPK4000_s:
offset = 7;
break;
case SC_CARD_TYPE_GPK_GPK8000:
case SC_CARD_TYPE_GPK_GPK8000_8K:
case SC_CARD_TYPE_GPK_GPK8000_16K:
case SC_CARD_TYPE_GPK_GPK16000:
offset = 0;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0xDB;
apdu.ins = 0xDE;
apdu.p2 = offset;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
priv->key_set = 0;
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
}
/*
* Lock a file Access Condition.
*
* File must be selected, and we assume that any authentication
* that needs to be presented in order to allow this operation
* have been presented (ACs from the DF; AC1 for sensitive files,
* AC2 for normal files).
*/
static int
gpk_lock(sc_card_t *card, struct sc_cardctl_gpk_lock *args)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_file_t *file = args->file;
sc_apdu_t apdu;
u8 data[8], crycks[3], resp[3];
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_lock(0x%04X, %u)\n", file->id, args->operation);
memset(data, 0, sizeof(data));
data[0] = file->id >> 8;
data[1] = file->id;
switch (args->operation) {
case SC_AC_OP_UPDATE:
data[2] = 0x40; break;
case SC_AC_OP_WRITE:
data[3] = 0x40; break;
case SC_AC_OP_READ:
data[4] = 0x40; break;
default:
return SC_ERROR_INVALID_ARGUMENTS;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x16;
apdu.p1 = (file->type == SC_FILE_TYPE_DF)? 1 : 2;
apdu.p2 = 0;
apdu.lc = 5;
apdu.datalen = 5;
apdu.data = data;
if (priv->key_set) {
apdu.cla = 0x84;
apdu.cse = SC_APDU_CASE_4_SHORT;
r = gpk_compute_crycks(card, &apdu, crycks);
if (r)
return r;
apdu.resp = resp;
apdu.resplen = sizeof(resp); /* XXX? */
}
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
if (priv->key_set)
r = gpk_verify_crycks(card, &apdu, crycks);
return r;
}
/*
* Initialize the private portion of a public key file
*/
static int
gpk_pkfile_init(sc_card_t *card, struct sc_cardctl_gpk_pkinit *args)
{
sc_apdu_t apdu;
int r;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_pkfile_init(%u)\n", args->privlen);
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_1;
apdu.cla = 0x80;
apdu.ins = 0x12;
apdu.p1 = args->file->id & 0x1F;
apdu.p2 = args->privlen / 4;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
/*
* Initialize the private portion of a public key file
*/
static int
gpk_generate_key(sc_card_t *card, struct sc_cardctl_gpk_genkey *args)
{
sc_apdu_t apdu;
int r;
u8 buffer[256];
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"gpk_generate_key(%u)\n", args->privlen);
if (args->privlen != 512 && args->privlen != 1024) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
"Key generation not supported for key length %d",
args->privlen);
return SC_ERROR_NOT_SUPPORTED;
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xD2;
apdu.p1 = 0x80 | (args->fid & 0x1F);
apdu.p2 = (args->privlen == 1024) ? 0x11 : 0;
apdu.le = args->privlen / 8 + 2;
apdu.resp = buffer;
apdu.resplen = 256;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
/* Return the public key, inverted.
* The first two bytes must be stripped off. */
if (args->pubkey_len && apdu.resplen > 2) {
r = reverse(args->pubkey, args->pubkey_len,
buffer + 2, apdu.resplen - 2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Failed to reverse buffer");
args->pubkey_len = r;
}
return r;
}
/*
* Store a private key component
*/
static int
gpk_pkfile_load(sc_card_t *card, struct sc_cardctl_gpk_pkload *args)
{
struct gpk_private_data *priv = DRVDATA(card);
sc_apdu_t apdu;
unsigned int n;
u8 temp[256];
int r = SC_SUCCESS, outl;
EVP_CIPHER_CTX * ctx;
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "gpk_pkfile_load(fid=%04x, len=%d, datalen=%d)\n",
args->file->id, args->len, args->datalen);
ctx = EVP_CIPHER_CTX_new();
if (ctx == NULL)
return SC_ERROR_INTERNAL;
if (0) {
sc_log_hex(card->ctx, "Sending (cleartext)",
args->data, args->datalen);
}
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_3_SHORT;
apdu.cla = 0x80;
apdu.ins = 0x18;
apdu.p1 = args->file->id & 0x1F;
apdu.p2 = args->len;
apdu.lc = args->datalen;
/* encrypt the private key material */
assert(args->datalen <= sizeof(temp));
if (!priv->key_set) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "No secure messaging key set!\n");
return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
}
EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, priv->key, NULL);
for (n = 0; n < args->datalen; n += 8) {
if (!EVP_EncryptUpdate(ctx, temp+n, &outl, args->data + n, 8)) {
r = SC_ERROR_INTERNAL;
break;
}
}
if (ctx)
EVP_CIPHER_CTX_free(ctx);
if (r != SC_SUCCESS)
return SC_ERROR_INTERNAL;
apdu.data = temp;
apdu.datalen = args->datalen;
/* Forget the key. The card seems to forget it, too :) */
priv->key_set = 0;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_NORMAL, r);
}
/*
* This function lets pkcs15init query for the transport key
*/
static int
gpk_get_default_key(sc_card_t *card, struct sc_cardctl_default_key *data)
{
if (data->method == SC_AC_PRO && data->key_ref == 1) {
if (data->len < 16)
return SC_ERROR_BUFFER_TOO_SMALL;
memcpy(data->key_data, "TEST KEYTEST KEY", 16);
data->len = 16;
return 0;
}
return SC_ERROR_NO_DEFAULT_KEY;
}
/*
* GetInfo call
*/
static int gpk_get_info(sc_card_t *card, int p1, int p2, u8 *buf,
size_t buflen)
{
sc_apdu_t apdu;
int r, retry = 0;
/* We may have to retry the get info command. It
* returns 6B00 if a previous command returned a 61xx response,
* but the host failed to collect the results.
*
* Note the additional sc_lock/sc_unlock pair, which
* is required to prevent sc_transmit_apdu from
* calling logout(), which in turn does a SELECT MF
* without collecting the response :)
*/
r = sc_lock(card);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "sc_lock() failed");
do {
memset(&apdu, 0, sizeof(apdu));
apdu.cse = SC_APDU_CASE_2_SHORT;
apdu.cla = 0x80;
apdu.ins = 0xC0;
apdu.p1 = p1;
apdu.p2 = p2;
apdu.le = buflen;
apdu.resp = buf;
apdu.resplen = buflen;
if ((r = sc_transmit_apdu(card, &apdu)) < 0) {
sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, "APDU transmit failed: %s",
sc_strerror(r));
sc_unlock(card);
return r;
}
} while (apdu.sw1 == 0x6B && apdu.sw2 == 0x00 && retry++ < 1);
sc_unlock(card);
r = sc_check_sw(card, apdu.sw1, apdu.sw2);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "Card returned error");
return r;
}
static int gpk_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
{
int r;
u8 rbuf[10];
sc_apdu_t apdu;
if (card->type != SC_CARD_TYPE_GPK_GPK16000)
return SC_ERROR_NOT_SUPPORTED;
if (!serial)
return SC_ERROR_INVALID_ARGUMENTS;
/* see if we have cached serial number */
if (card->serialnr.len) {
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
/* get serial number via Get CSN */
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xb8, 0x00, 0x00);
apdu.cla |= 0x80;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 8;
apdu.lc = 0;
apdu.datalen = 0;
r = sc_transmit_apdu(card, &apdu);
SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, "APDU transmit failed");
if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
return SC_ERROR_INTERNAL;
/* cache serial number */
memcpy(card->serialnr.value, apdu.resp, apdu.resplen);
card->serialnr.len = apdu.resplen;
/* copy and return serial number */
memcpy(serial, &card->serialnr, sizeof(*serial));
return SC_SUCCESS;
}
/*
* Dispatch card_ctl calls
*/
static int
gpk_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
{
switch (cmd) {
case SC_CARDCTL_ERASE_CARD:
return gpk_erase_card(card);
case SC_CARDCTL_GET_DEFAULT_KEY:
return gpk_get_default_key(card,
(struct sc_cardctl_default_key *) ptr);
case SC_CARDCTL_GPK_VARIANT:
*(int *) ptr = card->type;
return 0;
case SC_CARDCTL_GPK_LOCK:
return gpk_lock(card, (struct sc_cardctl_gpk_lock *) ptr);
case SC_CARDCTL_GPK_PKINIT:
return gpk_pkfile_init(card,
(struct sc_cardctl_gpk_pkinit *) ptr);
case SC_CARDCTL_GPK_PKLOAD:
return gpk_pkfile_load(card,
(struct sc_cardctl_gpk_pkload *) ptr);
case SC_CARDCTL_GPK_IS_LOCKED:
*(int *) ptr = DRVDATA(card)->locked;
return 0;
case SC_CARDCTL_GPK_GENERATE_KEY:
return gpk_generate_key(card,
(struct sc_cardctl_gpk_genkey *) ptr);
case SC_CARDCTL_GET_SERIALNR:
return gpk_get_serialnr(card, (sc_serial_number_t *) ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
static int
gpk_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu, struct sc_pin_cmd_data *data)
{
static u8 sbuf[8];
int r;
if (data->pin_type != SC_AC_CHV)
return SC_ERROR_INVALID_ARGUMENTS;
/* XXX deal with secure messaging here */
memset(apdu, 0, sizeof(*apdu));
apdu->cse = SC_APDU_CASE_3_SHORT;
data->flags |= SC_PIN_CMD_NEED_PADDING;
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
/* Copy PIN to buffer and pad */
data->pin1.encoding = SC_PIN_ENCODING_ASCII;
data->pin1.pad_length = 8;
data->pin1.pad_char = 0x00;
data->pin1.offset = 5;
r = sc_build_pin(sbuf, 8, &data->pin1, 1);
if (r < 0)
return r;
apdu->cla = 0x00;
apdu->ins = 0x20;
apdu->p1 = 0x00;
break;
case SC_PIN_CMD_CHANGE:
case SC_PIN_CMD_UNBLOCK:
/* Copy PINs to buffer, BCD-encoded, and pad */
data->pin1.encoding = SC_PIN_ENCODING_BCD;
data->pin1.pad_length = 8;
data->pin1.pad_char = 0x00;
data->pin1.offset = 5;
data->pin2.encoding = SC_PIN_ENCODING_BCD;
data->pin2.pad_length = 8;
data->pin2.pad_char = 0x00;
data->pin2.offset = 5 + 4;
if ((r = sc_build_pin(sbuf, 4, &data->pin1, 1)) < 0
|| (r = sc_build_pin(sbuf + 4, 4, &data->pin2, 1)) < 0)
return r;
apdu->cla = 0x80;
apdu->ins = 0x24;
apdu->p1 = (data->cmd == SC_PIN_CMD_CHANGE)? 0x00 : 0x01;
break;
default:
return SC_ERROR_NOT_SUPPORTED;
}
apdu->p2 = data->pin_reference & 7;
apdu->lc = 8;
apdu->datalen = 8;
apdu->data = sbuf;
return 0;
}
static int
gpk_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
{
sc_apdu_t apdu;
int r;
/* Special case - External Authenticate */
if (data->cmd == SC_PIN_CMD_VERIFY
&& data->pin_type == SC_AC_PRO)
return gpk_select_key(card,
data->pin_reference,
data->pin1.data,
data->pin1.len);
r = gpk_build_pin_apdu(card, &apdu, data);
if (r < 0)
return r;
data->apdu = &apdu;
return iso_ops->pin_cmd(card, data, tries_left);
}
/*
* Initialize the driver struct
*/
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv;
iso_drv = sc_get_iso7816_driver();
iso_ops = iso_drv->ops;
gpk_ops = *iso_ops;
gpk_ops.match_card = gpk_match_card;
gpk_ops.init = gpk_init;
gpk_ops.finish = gpk_finish;
gpk_ops.select_file = gpk_select_file;
gpk_ops.read_binary = gpk_read_binary;
gpk_ops.write_binary = gpk_write_binary;
gpk_ops.update_binary = gpk_update_binary;
gpk_ops.create_file = gpk_create_file;
/* gpk_ops.check_sw = gpk_check_sw; */
gpk_ops.card_ctl = gpk_card_ctl;
gpk_ops.set_security_env= gpk_set_security_env;
gpk_ops.restore_security_env= gpk_restore_security_env;
gpk_ops.compute_signature= gpk_compute_signature;
gpk_ops.decipher = gpk_decipher;
gpk_ops.pin_cmd = gpk_pin_cmd;
return &gpk_drv;
}
struct sc_card_driver *
sc_get_gpk_driver(void)
{
return sc_get_driver();
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_351_7 |
crossvul-cpp_data_good_5481_1 | /* $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);
}
}
/* Add 3 padding bytes for extractContigSamplesShifted32bits */
if( tile_buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size.");
exit(-1);
}
tilebuf = _TIFFmalloc(tile_buffsize + 3);
if (tilebuf == 0)
return 0;
tilebuf[tile_buffsize] = 0;
tilebuf[tile_buffsize+1] = 0;
tilebuf[tile_buffsize+2] = 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, §_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;
uint32 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, bytes_per_sample, bytes_per_pixel, shift_width, result = 1;
uint32 j;
int32 bytes_read = 0;
uint16 bps, planar;
uint32 nstrips;
uint32 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;
uint32 nstrips = 0, ntiles = 0;
uint16 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)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
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, §ions[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;
if( bytes_per_pixel > sizeof(swapbuff) )
{
TIFFError("reverseSamplesBytes","bytes_per_pixel too large");
return (1);
}
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-125/c/good_5481_1 |
crossvul-cpp_data_bad_4831_1 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2013 Conifer Software. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// read_words.c
// This module provides entropy word decoding functions using
// a variation on the Rice method. This was introduced in version 3.93
// because it allows splitting the data into a "lossy" stream and a
// "correction" stream in a very efficient manner and is therefore ideal
// for the "hybrid" mode. For 4.0, the efficiency of this method was
// significantly improved by moving away from the normal Rice restriction of
// using powers of two for the modulus divisions and now the method can be
// used for both hybrid and pure lossless encoding.
// Samples are divided by median probabilities at 5/7 (71.43%), 10/49 (20.41%),
// and 20/343 (5.83%). Each zone has 3.5 times fewer samples than the
// previous. Using standard Rice coding on this data would result in 1.4
// bits per sample average (not counting sign bit). However, there is a
// very simple encoding that is over 99% efficient with this data and
// results in about 1.22 bits per sample.
#include <stdlib.h>
#include <string.h>
#include "wavpack_local.h"
#if defined (HAVE___BUILTIN_CTZ) || defined (_WIN64)
#define USE_CTZ_OPTIMIZATION // use ctz intrinsic (or Windows equivalent) to count trailing ones
#else
#define USE_NEXT8_OPTIMIZATION // optimization using a table to count trailing ones
#endif
#define USE_BITMASK_TABLES // use tables instead of shifting for certain masking operations
///////////////////////////// local table storage ////////////////////////////
#ifdef USE_NEXT8_OPTIMIZATION
static const char ones_count_table [] = {
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,
0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,8
};
#endif
///////////////////////////// executable code ////////////////////////////////
static uint32_t __inline read_code (Bitstream *bs, uint32_t maxcode);
// Read the next word from the bitstream "wvbits" and return the value. This
// function can be used for hybrid or lossless streams, but since an
// optimized version is available for lossless this function would normally
// be used for hybrid only. If a hybrid lossless stream is being read then
// the "correction" offset is written at the specified pointer. A return value
// of WORD_EOF indicates that the end of the bitstream was reached (all 1s) or
// some other error occurred.
int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction)
{
register struct entropy_data *c = wps->w.c + chan;
uint32_t ones_count, low, mid, high;
int32_t value;
int sign;
if (!wps->wvbits.ptr)
return WORD_EOF;
if (correction)
*correction = 0;
if (!(wps->w.c [0].median [0] & ~1) && !wps->w.holding_zero && !wps->w.holding_one && !(wps->w.c [1].median [0] & ~1)) {
uint32_t mask;
int cbits;
if (wps->w.zeros_acc) {
if (--wps->w.zeros_acc) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
return 0;
}
}
else {
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
wps->w.zeros_acc = cbits;
else {
for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
wps->w.zeros_acc |= mask;
wps->w.zeros_acc |= mask;
}
if (wps->w.zeros_acc) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
CLEAR (wps->w.c [0].median);
CLEAR (wps->w.c [1].median);
return 0;
}
}
}
if (wps->w.holding_zero)
ones_count = wps->w.holding_zero = 0;
else {
#ifdef USE_CTZ_OPTIMIZATION
while (wps->wvbits.bc < LIMIT_ONES) {
if (++(wps->wvbits.ptr) == wps->wvbits.end)
wps->wvbits.wrap (&wps->wvbits);
wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc;
wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;
}
#ifdef _WIN32
_BitScanForward (&ones_count, ~wps->wvbits.sr);
#else
ones_count = __builtin_ctz (~wps->wvbits.sr);
#endif
if (ones_count >= LIMIT_ONES) {
wps->wvbits.bc -= ones_count;
wps->wvbits.sr >>= ones_count;
for (; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
wps->wvbits.bc -= ones_count + 1;
wps->wvbits.sr >>= ones_count + 1;
}
#elif defined (USE_NEXT8_OPTIMIZATION)
int next8;
if (wps->wvbits.bc < 8) {
if (++(wps->wvbits.ptr) == wps->wvbits.end)
wps->wvbits.wrap (&wps->wvbits);
next8 = (wps->wvbits.sr |= *(wps->wvbits.ptr) << wps->wvbits.bc) & 0xff;
wps->wvbits.bc += sizeof (*(wps->wvbits.ptr)) * 8;
}
else
next8 = wps->wvbits.sr & 0xff;
if (next8 == 0xff) {
wps->wvbits.bc -= 8;
wps->wvbits.sr >>= 8;
for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
wps->wvbits.bc -= (ones_count = ones_count_table [next8]) + 1;
wps->wvbits.sr >>= ones_count + 1;
}
#else
for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (&wps->wvbits); ++ones_count);
if (ones_count >= LIMIT_ONES) {
uint32_t mask;
int cbits;
if (ones_count == (LIMIT_ONES + 1))
return WORD_EOF;
for (cbits = 0; cbits < 33 && getbit (&wps->wvbits); ++cbits);
if (cbits == 33)
return WORD_EOF;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (&wps->wvbits))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
#endif
if (wps->w.holding_one) {
wps->w.holding_one = ones_count & 1;
ones_count = (ones_count >> 1) + 1;
}
else {
wps->w.holding_one = ones_count & 1;
ones_count >>= 1;
}
wps->w.holding_zero = ~wps->w.holding_one & 1;
}
if ((wps->wphdr.flags & HYBRID_FLAG) && !chan)
update_error_limit (wps);
if (ones_count == 0) {
low = 0;
high = GET_MED (0) - 1;
DEC_MED0 ();
}
else {
low = GET_MED (0);
INC_MED0 ();
if (ones_count == 1) {
high = low + GET_MED (1) - 1;
DEC_MED1 ();
}
else {
low += GET_MED (1);
INC_MED1 ();
if (ones_count == 2) {
high = low + GET_MED (2) - 1;
DEC_MED2 ();
}
else {
low += (ones_count - 2) * GET_MED (2);
high = low + GET_MED (2) - 1;
INC_MED2 ();
}
}
}
low &= 0x7fffffff;
high &= 0x7fffffff;
mid = (high + low + 1) >> 1;
if (!c->error_limit)
mid = read_code (&wps->wvbits, high - low) + low;
else while (high - low > c->error_limit) {
if (getbit (&wps->wvbits))
mid = (high + (low = mid) + 1) >> 1;
else
mid = ((high = mid - 1) + low + 1) >> 1;
}
sign = getbit (&wps->wvbits);
if (bs_is_open (&wps->wvcbits) && c->error_limit) {
value = read_code (&wps->wvcbits, high - low) + low;
if (correction)
*correction = sign ? (mid - value) : (value - mid);
}
if (wps->wphdr.flags & HYBRID_BITRATE) {
c->slow_level -= (c->slow_level + SLO) >> SLS;
c->slow_level += wp_log2 (mid);
}
return sign ? ~mid : mid;
}
// This is an optimized version of get_word() that is used for lossless only
// (error_limit == 0). Also, rather than obtaining a single sample, it can be
// used to obtain an entire buffer of either mono or stereo samples.
int32_t get_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples)
{
struct entropy_data *c = wps->w.c;
uint32_t ones_count, low, high;
Bitstream *bs = &wps->wvbits;
int32_t csamples;
#ifdef USE_NEXT8_OPTIMIZATION
int32_t next8;
#endif
if (nsamples && !bs->ptr) {
memset (buffer, 0, (wps->wphdr.flags & MONO_DATA) ? nsamples * 4 : nsamples * 8);
return nsamples;
}
if (!(wps->wphdr.flags & MONO_DATA))
nsamples *= 2;
for (csamples = 0; csamples < nsamples; ++csamples) {
if (!(wps->wphdr.flags & MONO_DATA))
c = wps->w.c + (csamples & 1);
if (wps->w.holding_zero) {
wps->w.holding_zero = 0;
low = read_code (bs, GET_MED (0) - 1);
DEC_MED0 ();
buffer [csamples] = (getbit (bs)) ? ~low : low;
if (++csamples == nsamples)
break;
if (!(wps->wphdr.flags & MONO_DATA))
c = wps->w.c + (csamples & 1);
}
if (wps->w.c [0].median [0] < 2 && !wps->w.holding_one && wps->w.c [1].median [0] < 2) {
uint32_t mask;
int cbits;
if (wps->w.zeros_acc) {
if (--wps->w.zeros_acc) {
buffer [csamples] = 0;
continue;
}
}
else {
for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);
if (cbits == 33)
break;
if (cbits < 2)
wps->w.zeros_acc = cbits;
else {
for (mask = 1, wps->w.zeros_acc = 0; --cbits; mask <<= 1)
if (getbit (bs))
wps->w.zeros_acc |= mask;
wps->w.zeros_acc |= mask;
}
if (wps->w.zeros_acc) {
CLEAR (wps->w.c [0].median);
CLEAR (wps->w.c [1].median);
buffer [csamples] = 0;
continue;
}
}
}
#ifdef USE_CTZ_OPTIMIZATION
while (bs->bc < LIMIT_ONES) {
if (++(bs->ptr) == bs->end)
bs->wrap (bs);
bs->sr |= *(bs->ptr) << bs->bc;
bs->bc += sizeof (*(bs->ptr)) * 8;
}
#ifdef _WIN32
_BitScanForward (&ones_count, ~wps->wvbits.sr);
#else
ones_count = __builtin_ctz (~wps->wvbits.sr);
#endif
if (ones_count >= LIMIT_ONES) {
bs->bc -= ones_count;
bs->sr >>= ones_count;
for (; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
break;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);
if (cbits == 33)
break;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (bs))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
bs->bc -= ones_count + 1;
bs->sr >>= ones_count + 1;
}
#elif defined (USE_NEXT8_OPTIMIZATION)
if (bs->bc < 8) {
if (++(bs->ptr) == bs->end)
bs->wrap (bs);
next8 = (bs->sr |= *(bs->ptr) << bs->bc) & 0xff;
bs->bc += sizeof (*(bs->ptr)) * 8;
}
else
next8 = bs->sr & 0xff;
if (next8 == 0xff) {
bs->bc -= 8;
bs->sr >>= 8;
for (ones_count = 8; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count);
if (ones_count == (LIMIT_ONES + 1))
break;
if (ones_count == LIMIT_ONES) {
uint32_t mask;
int cbits;
for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);
if (cbits == 33)
break;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (bs))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
}
else {
bs->bc -= (ones_count = ones_count_table [next8]) + 1;
bs->sr >>= ones_count + 1;
}
#else
for (ones_count = 0; ones_count < (LIMIT_ONES + 1) && getbit (bs); ++ones_count);
if (ones_count >= LIMIT_ONES) {
uint32_t mask;
int cbits;
if (ones_count == (LIMIT_ONES + 1))
break;
for (cbits = 0; cbits < 33 && getbit (bs); ++cbits);
if (cbits == 33)
break;
if (cbits < 2)
ones_count = cbits;
else {
for (mask = 1, ones_count = 0; --cbits; mask <<= 1)
if (getbit (bs))
ones_count |= mask;
ones_count |= mask;
}
ones_count += LIMIT_ONES;
}
#endif
low = wps->w.holding_one;
wps->w.holding_one = ones_count & 1;
wps->w.holding_zero = ~ones_count & 1;
ones_count = (ones_count >> 1) + low;
if (ones_count == 0) {
low = 0;
high = GET_MED (0) - 1;
DEC_MED0 ();
}
else {
low = GET_MED (0);
INC_MED0 ();
if (ones_count == 1) {
high = low + GET_MED (1) - 1;
DEC_MED1 ();
}
else {
low += GET_MED (1);
INC_MED1 ();
if (ones_count == 2) {
high = low + GET_MED (2) - 1;
DEC_MED2 ();
}
else {
low += (ones_count - 2) * GET_MED (2);
high = low + GET_MED (2) - 1;
INC_MED2 ();
}
}
}
low += read_code (bs, high - low);
buffer [csamples] = (getbit (bs)) ? ~low : low;
}
return (wps->wphdr.flags & MONO_DATA) ? csamples : (csamples / 2);
}
// Read a single unsigned value from the specified bitstream with a value
// from 0 to maxcode. If there are exactly a power of two number of possible
// codes then this will read a fixed number of bits; otherwise it reads the
// minimum number of bits and then determines whether another bit is needed
// to define the code.
static uint32_t __inline read_code (Bitstream *bs, uint32_t maxcode)
{
unsigned long local_sr;
uint32_t extras, code;
int bitcount;
if (maxcode < 2)
return maxcode ? getbit (bs) : 0;
bitcount = count_bits (maxcode);
#ifdef USE_BITMASK_TABLES
extras = bitset [bitcount] - maxcode - 1;
#else
extras = (1 << bitcount) - maxcode - 1;
#endif
local_sr = bs->sr;
while (bs->bc < bitcount) {
if (++(bs->ptr) == bs->end)
bs->wrap (bs);
local_sr |= (long)*(bs->ptr) << bs->bc;
bs->bc += sizeof (*(bs->ptr)) * 8;
}
#ifdef USE_BITMASK_TABLES
if ((code = local_sr & bitmask [bitcount - 1]) >= extras)
#else
if ((code = local_sr & ((1 << (bitcount - 1)) - 1)) >= extras)
#endif
code = (code << 1) - extras + ((local_sr >> (bitcount - 1)) & 1);
else
bitcount--;
if (sizeof (local_sr) < 8 && bs->bc > sizeof (local_sr) * 8) {
bs->bc -= bitcount;
bs->sr = *(bs->ptr) >> (sizeof (*(bs->ptr)) * 8 - bs->bc);
}
else {
bs->bc -= bitcount;
bs->sr = local_sr >> bitcount;
}
return code;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4831_1 |
crossvul-cpp_data_good_2689_0 | /*
* Copyright (c) 1993, 1994, 1995, 1996
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: White Board printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
static const char tstr[] = "[|wb]";
/* XXX need to add byte-swapping macros! */
/* XXX - you mean like the ones in "extract.h"? */
/*
* Largest packet size. Everything should fit within this space.
* For instance, multiline objects are sent piecewise.
*/
#define MAXFRAMESIZE 1024
/*
* Multiple drawing ops can be sent in one packet. Each one starts on a
* an even multiple of DOP_ALIGN bytes, which must be a power of two.
*/
#define DOP_ALIGN 4
#define DOP_ROUNDUP(x) ((((int)(x)) + (DOP_ALIGN - 1)) & ~(DOP_ALIGN - 1))
#define DOP_NEXT(d)\
((const struct dophdr *)((const u_char *)(d) + \
DOP_ROUNDUP(EXTRACT_16BITS(&(d)->dh_len) + sizeof(*(d)))))
/*
* Format of the whiteboard packet header.
* The transport level header.
*/
struct pkt_hdr {
uint32_t ph_src; /* site id of source */
uint32_t ph_ts; /* time stamp (for skew computation) */
uint16_t ph_version; /* version number */
u_char ph_type; /* message type */
u_char ph_flags; /* message flags */
};
/* Packet types */
#define PT_DRAWOP 0 /* drawing operation */
#define PT_ID 1 /* announcement packet */
#define PT_RREQ 2 /* repair request */
#define PT_RREP 3 /* repair reply */
#define PT_KILL 4 /* terminate participation */
#define PT_PREQ 5 /* page vector request */
#define PT_PREP 7 /* page vector reply */
#ifdef PF_USER
#undef PF_USER /* {Digital,Tru64} UNIX define this, alas */
#endif
/* flags */
#define PF_USER 0x01 /* hint that packet has interactive data */
#define PF_VIS 0x02 /* only visible ops wanted */
struct PageID {
uint32_t p_sid; /* session id of initiator */
uint32_t p_uid; /* page number */
};
struct dophdr {
uint32_t dh_ts; /* sender's timestamp */
uint16_t dh_len; /* body length */
u_char dh_flags;
u_char dh_type; /* body type */
/* body follows */
};
/*
* Drawing op sub-types.
*/
#define DT_RECT 2
#define DT_LINE 3
#define DT_ML 4
#define DT_DEL 5
#define DT_XFORM 6
#define DT_ELL 7
#define DT_CHAR 8
#define DT_STR 9
#define DT_NOP 10
#define DT_PSCODE 11
#define DT_PSCOMP 12
#define DT_REF 13
#define DT_SKIP 14
#define DT_HOLE 15
#define DT_MAXTYPE 15
/*
* A drawing operation.
*/
struct pkt_dop {
struct PageID pd_page; /* page that operations apply to */
uint32_t pd_sseq; /* start sequence number */
uint32_t pd_eseq; /* end sequence number */
/* drawing ops follow */
};
/*
* A repair request.
*/
struct pkt_rreq {
uint32_t pr_id; /* source id of drawops to be repaired */
struct PageID pr_page; /* page of drawops */
uint32_t pr_sseq; /* start seqno */
uint32_t pr_eseq; /* end seqno */
};
/*
* A repair reply.
*/
struct pkt_rrep {
uint32_t pr_id; /* original site id of ops */
struct pkt_dop pr_dop;
/* drawing ops follow */
};
struct id_off {
uint32_t id;
uint32_t off;
};
struct pgstate {
uint32_t slot;
struct PageID page;
uint16_t nid;
uint16_t rsvd;
/* seqptr's */
};
/*
* An announcement packet.
*/
struct pkt_id {
uint32_t pi_mslot;
struct PageID pi_mpage; /* current page */
struct pgstate pi_ps;
/* seqptr's */
/* null-terminated site name */
};
struct pkt_preq {
struct PageID pp_page;
uint32_t pp_low;
uint32_t pp_high;
};
struct pkt_prep {
uint32_t pp_n; /* size of pageid array */
/* pgstate's follow */
};
static int
wb_id(netdissect_options *ndo,
const struct pkt_id *id, u_int len)
{
int i;
const char *cp;
const struct id_off *io;
char c;
int nid;
ND_PRINT((ndo, " wb-id:"));
if (len < sizeof(*id) || !ND_TTEST(*id))
return (-1);
len -= sizeof(*id);
ND_PRINT((ndo, " %u/%s:%u (max %u/%s:%u) ",
EXTRACT_32BITS(&id->pi_ps.slot),
ipaddr_string(ndo, &id->pi_ps.page.p_sid),
EXTRACT_32BITS(&id->pi_ps.page.p_uid),
EXTRACT_32BITS(&id->pi_mslot),
ipaddr_string(ndo, &id->pi_mpage.p_sid),
EXTRACT_32BITS(&id->pi_mpage.p_uid)));
nid = EXTRACT_16BITS(&id->pi_ps.nid);
len -= sizeof(*io) * nid;
io = (const struct id_off *)(id + 1);
cp = (const char *)(io + nid);
if (ND_TTEST2(cp, len)) {
ND_PRINT((ndo, "\""));
fn_print(ndo, (const u_char *)cp, (const u_char *)cp + len);
ND_PRINT((ndo, "\""));
}
c = '<';
for (i = 0; i < nid && ND_TTEST(*io); ++io, ++i) {
ND_PRINT((ndo, "%c%s:%u",
c, ipaddr_string(ndo, &io->id), EXTRACT_32BITS(&io->off)));
c = ',';
}
if (i >= nid) {
ND_PRINT((ndo, ">"));
return (0);
}
return (-1);
}
static int
wb_rreq(netdissect_options *ndo,
const struct pkt_rreq *rreq, u_int len)
{
ND_PRINT((ndo, " wb-rreq:"));
if (len < sizeof(*rreq) || !ND_TTEST(*rreq))
return (-1);
ND_PRINT((ndo, " please repair %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rreq->pr_id),
ipaddr_string(ndo, &rreq->pr_page.p_sid),
EXTRACT_32BITS(&rreq->pr_page.p_uid),
EXTRACT_32BITS(&rreq->pr_sseq),
EXTRACT_32BITS(&rreq->pr_eseq)));
return (0);
}
static int
wb_preq(netdissect_options *ndo,
const struct pkt_preq *preq, u_int len)
{
ND_PRINT((ndo, " wb-preq:"));
if (len < sizeof(*preq) || !ND_TTEST(*preq))
return (-1);
ND_PRINT((ndo, " need %u/%s:%u",
EXTRACT_32BITS(&preq->pp_low),
ipaddr_string(ndo, &preq->pp_page.p_sid),
EXTRACT_32BITS(&preq->pp_page.p_uid)));
return (0);
}
static int
wb_prep(netdissect_options *ndo,
const struct pkt_prep *prep, u_int len)
{
int n;
const struct pgstate *ps;
const u_char *ep = ndo->ndo_snapend;
ND_PRINT((ndo, " wb-prep:"));
if (len < sizeof(*prep) || !ND_TTEST(*prep))
return (-1);
n = EXTRACT_32BITS(&prep->pp_n);
ps = (const struct pgstate *)(prep + 1);
while (--n >= 0 && ND_TTEST(*ps)) {
const struct id_off *io, *ie;
char c = '<';
ND_PRINT((ndo, " %u/%s:%u",
EXTRACT_32BITS(&ps->slot),
ipaddr_string(ndo, &ps->page.p_sid),
EXTRACT_32BITS(&ps->page.p_uid)));
io = (const struct id_off *)(ps + 1);
for (ie = io + ps->nid; io < ie && ND_TTEST(*io); ++io) {
ND_PRINT((ndo, "%c%s:%u", c, ipaddr_string(ndo, &io->id),
EXTRACT_32BITS(&io->off)));
c = ',';
}
ND_PRINT((ndo, ">"));
ps = (const struct pgstate *)io;
}
return ((const u_char *)ps <= ep? 0 : -1);
}
static const char *dopstr[] = {
"dop-0!",
"dop-1!",
"RECT",
"LINE",
"ML",
"DEL",
"XFORM",
"ELL",
"CHAR",
"STR",
"NOP",
"PSCODE",
"PSCOMP",
"REF",
"SKIP",
"HOLE",
};
static int
wb_dops(netdissect_options *ndo, const struct pkt_dop *dop,
uint32_t ss, uint32_t es)
{
const struct dophdr *dh = (const struct dophdr *)((const u_char *)dop + sizeof(*dop));
ND_PRINT((ndo, " <"));
for ( ; ss <= es; ++ss) {
int t;
if (!ND_TTEST(*dh)) {
ND_PRINT((ndo, "%s", tstr));
break;
}
t = dh->dh_type;
if (t > DT_MAXTYPE)
ND_PRINT((ndo, " dop-%d!", t));
else {
ND_PRINT((ndo, " %s", dopstr[t]));
if (t == DT_SKIP || t == DT_HOLE) {
uint32_t ts = EXTRACT_32BITS(&dh->dh_ts);
ND_PRINT((ndo, "%d", ts - ss + 1));
if (ss > ts || ts > es) {
ND_PRINT((ndo, "[|]"));
if (ts < ss)
return (0);
}
ss = ts;
}
}
dh = DOP_NEXT(dh);
}
ND_PRINT((ndo, " >"));
return (0);
}
static int
wb_rrep(netdissect_options *ndo,
const struct pkt_rrep *rrep, u_int len)
{
const struct pkt_dop *dop = &rrep->pr_dop;
ND_PRINT((ndo, " wb-rrep:"));
if (len < sizeof(*rrep) || !ND_TTEST(*rrep))
return (-1);
len -= sizeof(*rrep);
ND_PRINT((ndo, " for %s %s:%u<%u:%u>",
ipaddr_string(ndo, &rrep->pr_id),
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
static int
wb_drawop(netdissect_options *ndo,
const struct pkt_dop *dop, u_int len)
{
ND_PRINT((ndo, " wb-dop:"));
if (len < sizeof(*dop) || !ND_TTEST(*dop))
return (-1);
len -= sizeof(*dop);
ND_PRINT((ndo, " %s:%u<%u:%u>",
ipaddr_string(ndo, &dop->pd_page.p_sid),
EXTRACT_32BITS(&dop->pd_page.p_uid),
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
if (ndo->ndo_vflag)
return (wb_dops(ndo, dop,
EXTRACT_32BITS(&dop->pd_sseq),
EXTRACT_32BITS(&dop->pd_eseq)));
return (0);
}
/*
* Print whiteboard multicast packets.
*/
void
wb_print(netdissect_options *ndo,
register const void *hdr, register u_int len)
{
register const struct pkt_hdr *ph;
ph = (const struct pkt_hdr *)hdr;
if (len < sizeof(*ph) || !ND_TTEST(*ph)) {
ND_PRINT((ndo, "%s", tstr));
return;
}
len -= sizeof(*ph);
if (ph->ph_flags)
ND_PRINT((ndo, "*"));
switch (ph->ph_type) {
case PT_KILL:
ND_PRINT((ndo, " wb-kill"));
return;
case PT_ID:
if (wb_id(ndo, (const struct pkt_id *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_RREQ:
if (wb_rreq(ndo, (const struct pkt_rreq *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_RREP:
if (wb_rrep(ndo, (const struct pkt_rrep *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_DRAWOP:
if (wb_drawop(ndo, (const struct pkt_dop *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_PREQ:
if (wb_preq(ndo, (const struct pkt_preq *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
case PT_PREP:
if (wb_prep(ndo, (const struct pkt_prep *)(ph + 1), len) >= 0)
return;
ND_PRINT((ndo, "%s", tstr));
break;
default:
ND_PRINT((ndo, " wb-%d!", ph->ph_type));
return;
}
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2689_0 |
crossvul-cpp_data_bad_1283_0 | /*
* This file includes functions to transform a concrete syntax tree (CST) to
* an abstract syntax tree (AST). The main function is Ta3AST_FromNode().
*
*/
#include "Python.h"
#include "Python-ast.h"
#include "node.h"
#include "ast.h"
#include "token.h"
#include "pythonrun.h"
#include <assert.h>
// VS 2010 doesn't have <stdbool.h>...
typedef int bool;
#define false 0
#define true 1
#ifndef _PyObject_FastCall
static PyObject *
_PyObject_FastCall(PyObject *func, PyObject *const *args, int nargs)
{
PyObject *t, *res;
int i;
t = PyTuple_New(nargs);
if (t == NULL) {
return NULL;
}
for (i = 0; i < nargs; i++) {
if (PyTuple_SetItem(t, i, args[i]) < 0) {
Py_DECREF(t);
return NULL;
}
}
res = PyObject_CallObject(func, t);
Py_DECREF(t);
return res;
}
#endif
#if PY_MINOR_VERSION < 6
#define _PyUnicode_EqualToASCIIString(a, b) (PyUnicode_CompareWithASCIIString((a), (b)) == 0)
static PyObject *
_PyBytes_DecodeEscape(const char *s,
Py_ssize_t len,
const char *errors,
Py_ssize_t unicode,
const char *recode_encoding,
const char **first_invalid_escape)
{
*first_invalid_escape = NULL;
return PyBytes_DecodeEscape(s, len, errors, unicode, recode_encoding);
}
PyObject *
_PyUnicode_DecodeUnicodeEscape(const char *s,
Py_ssize_t size,
const char *errors,
const char **first_invalid_escape)
{
*first_invalid_escape = NULL;
return PyUnicode_DecodeUnicodeEscape(s, size, errors);
}
#endif
static int validate_stmts(asdl_seq *);
static int validate_exprs(asdl_seq *, expr_context_ty, int);
static int validate_nonempty_seq(asdl_seq *, const char *, const char *);
static int validate_stmt(stmt_ty);
static int validate_expr(expr_ty, expr_context_ty);
void
_Ta3Parser_UpdateFlags(PyCompilerFlags *flags, int *iflags, int feature_version);
node *
Ta3Parser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
int start, int flags);
static int
validate_comprehension(asdl_seq *gens)
{
int i;
if (!asdl_seq_LEN(gens)) {
PyErr_SetString(PyExc_ValueError, "comprehension with no generators");
return 0;
}
for (i = 0; i < asdl_seq_LEN(gens); i++) {
comprehension_ty comp = asdl_seq_GET(gens, i);
if (!validate_expr(comp->target, Store) ||
!validate_expr(comp->iter, Load) ||
!validate_exprs(comp->ifs, Load, 0))
return 0;
}
return 1;
}
static int
validate_slice(slice_ty slice)
{
switch (slice->kind) {
case Slice_kind:
return (!slice->v.Slice.lower || validate_expr(slice->v.Slice.lower, Load)) &&
(!slice->v.Slice.upper || validate_expr(slice->v.Slice.upper, Load)) &&
(!slice->v.Slice.step || validate_expr(slice->v.Slice.step, Load));
case ExtSlice_kind: {
int i;
if (!validate_nonempty_seq(slice->v.ExtSlice.dims, "dims", "ExtSlice"))
return 0;
for (i = 0; i < asdl_seq_LEN(slice->v.ExtSlice.dims); i++)
if (!validate_slice(asdl_seq_GET(slice->v.ExtSlice.dims, i)))
return 0;
return 1;
}
case Index_kind:
return validate_expr(slice->v.Index.value, Load);
default:
PyErr_SetString(PyExc_SystemError, "unknown slice node");
return 0;
}
}
static int
validate_keywords(asdl_seq *keywords)
{
int i;
for (i = 0; i < asdl_seq_LEN(keywords); i++)
if (!validate_expr(((keyword_ty)asdl_seq_GET(keywords, i))->value, Load))
return 0;
return 1;
}
static int
validate_args(asdl_seq *args)
{
int i;
for (i = 0; i < asdl_seq_LEN(args); i++) {
arg_ty arg = asdl_seq_GET(args, i);
if (arg->annotation && !validate_expr(arg->annotation, Load))
return 0;
}
return 1;
}
static const char *
expr_context_name(expr_context_ty ctx)
{
switch (ctx) {
case Load:
return "Load";
case Store:
return "Store";
case Del:
return "Del";
case AugLoad:
return "AugLoad";
case AugStore:
return "AugStore";
case Param:
return "Param";
default:
abort();
}
}
static int
validate_arguments(arguments_ty args)
{
if (!validate_args(args->args))
return 0;
if (args->vararg && args->vararg->annotation
&& !validate_expr(args->vararg->annotation, Load)) {
return 0;
}
if (!validate_args(args->kwonlyargs))
return 0;
if (args->kwarg && args->kwarg->annotation
&& !validate_expr(args->kwarg->annotation, Load)) {
return 0;
}
if (asdl_seq_LEN(args->defaults) > asdl_seq_LEN(args->args)) {
PyErr_SetString(PyExc_ValueError, "more positional defaults than args on arguments");
return 0;
}
if (asdl_seq_LEN(args->kw_defaults) != asdl_seq_LEN(args->kwonlyargs)) {
PyErr_SetString(PyExc_ValueError, "length of kwonlyargs is not the same as "
"kw_defaults on arguments");
return 0;
}
return validate_exprs(args->defaults, Load, 0) && validate_exprs(args->kw_defaults, Load, 1);
}
static int
validate_constant(PyObject *value)
{
if (value == Py_None || value == Py_Ellipsis)
return 1;
if (PyLong_CheckExact(value)
|| PyFloat_CheckExact(value)
|| PyComplex_CheckExact(value)
|| PyBool_Check(value)
|| PyUnicode_CheckExact(value)
|| PyBytes_CheckExact(value))
return 1;
if (PyTuple_CheckExact(value) || PyFrozenSet_CheckExact(value)) {
PyObject *it;
it = PyObject_GetIter(value);
if (it == NULL)
return 0;
while (1) {
PyObject *item = PyIter_Next(it);
if (item == NULL) {
if (PyErr_Occurred()) {
Py_DECREF(it);
return 0;
}
break;
}
if (!validate_constant(item)) {
Py_DECREF(it);
Py_DECREF(item);
return 0;
}
Py_DECREF(item);
}
Py_DECREF(it);
return 1;
}
return 0;
}
static int
validate_expr(expr_ty exp, expr_context_ty ctx)
{
int check_ctx = 1;
expr_context_ty actual_ctx;
/* First check expression context. */
switch (exp->kind) {
case Attribute_kind:
actual_ctx = exp->v.Attribute.ctx;
break;
case Subscript_kind:
actual_ctx = exp->v.Subscript.ctx;
break;
case Starred_kind:
actual_ctx = exp->v.Starred.ctx;
break;
case Name_kind:
actual_ctx = exp->v.Name.ctx;
break;
case List_kind:
actual_ctx = exp->v.List.ctx;
break;
case Tuple_kind:
actual_ctx = exp->v.Tuple.ctx;
break;
default:
if (ctx != Load) {
PyErr_Format(PyExc_ValueError, "expression which can't be "
"assigned to in %s context", expr_context_name(ctx));
return 0;
}
check_ctx = 0;
/* set actual_ctx to prevent gcc warning */
actual_ctx = 0;
}
if (check_ctx && actual_ctx != ctx) {
PyErr_Format(PyExc_ValueError, "expression must have %s context but has %s instead",
expr_context_name(ctx), expr_context_name(actual_ctx));
return 0;
}
/* Now validate expression. */
switch (exp->kind) {
case BoolOp_kind:
if (asdl_seq_LEN(exp->v.BoolOp.values) < 2) {
PyErr_SetString(PyExc_ValueError, "BoolOp with less than 2 values");
return 0;
}
return validate_exprs(exp->v.BoolOp.values, Load, 0);
case BinOp_kind:
return validate_expr(exp->v.BinOp.left, Load) &&
validate_expr(exp->v.BinOp.right, Load);
case UnaryOp_kind:
return validate_expr(exp->v.UnaryOp.operand, Load);
case Lambda_kind:
return validate_arguments(exp->v.Lambda.args) &&
validate_expr(exp->v.Lambda.body, Load);
case IfExp_kind:
return validate_expr(exp->v.IfExp.test, Load) &&
validate_expr(exp->v.IfExp.body, Load) &&
validate_expr(exp->v.IfExp.orelse, Load);
case Dict_kind:
if (asdl_seq_LEN(exp->v.Dict.keys) != asdl_seq_LEN(exp->v.Dict.values)) {
PyErr_SetString(PyExc_ValueError,
"Dict doesn't have the same number of keys as values");
return 0;
}
/* null_ok=1 for keys expressions to allow dict unpacking to work in
dict literals, i.e. ``{**{a:b}}`` */
return validate_exprs(exp->v.Dict.keys, Load, /*null_ok=*/ 1) &&
validate_exprs(exp->v.Dict.values, Load, /*null_ok=*/ 0);
case Set_kind:
return validate_exprs(exp->v.Set.elts, Load, 0);
#define COMP(NAME) \
case NAME ## _kind: \
return validate_comprehension(exp->v.NAME.generators) && \
validate_expr(exp->v.NAME.elt, Load);
COMP(ListComp)
COMP(SetComp)
COMP(GeneratorExp)
#undef COMP
case DictComp_kind:
return validate_comprehension(exp->v.DictComp.generators) &&
validate_expr(exp->v.DictComp.key, Load) &&
validate_expr(exp->v.DictComp.value, Load);
case Yield_kind:
return !exp->v.Yield.value || validate_expr(exp->v.Yield.value, Load);
case YieldFrom_kind:
return validate_expr(exp->v.YieldFrom.value, Load);
case Await_kind:
return validate_expr(exp->v.Await.value, Load);
case Compare_kind:
if (!asdl_seq_LEN(exp->v.Compare.comparators)) {
PyErr_SetString(PyExc_ValueError, "Compare with no comparators");
return 0;
}
if (asdl_seq_LEN(exp->v.Compare.comparators) !=
asdl_seq_LEN(exp->v.Compare.ops)) {
PyErr_SetString(PyExc_ValueError, "Compare has a different number "
"of comparators and operands");
return 0;
}
return validate_exprs(exp->v.Compare.comparators, Load, 0) &&
validate_expr(exp->v.Compare.left, Load);
case Call_kind:
return validate_expr(exp->v.Call.func, Load) &&
validate_exprs(exp->v.Call.args, Load, 0) &&
validate_keywords(exp->v.Call.keywords);
case Constant_kind:
if (!validate_constant(exp->v.Constant.value)) {
PyErr_Format(PyExc_TypeError,
"got an invalid type in Constant: %s",
Py_TYPE(exp->v.Constant.value)->tp_name);
return 0;
}
return 1;
case Num_kind: {
PyObject *n = exp->v.Num.n;
if (!PyLong_CheckExact(n) && !PyFloat_CheckExact(n) &&
!PyComplex_CheckExact(n)) {
PyErr_SetString(PyExc_TypeError, "non-numeric type in Num");
return 0;
}
return 1;
}
case Str_kind: {
PyObject *s = exp->v.Str.s;
if (!PyUnicode_CheckExact(s)) {
PyErr_SetString(PyExc_TypeError, "non-string type in Str");
return 0;
}
return 1;
}
case JoinedStr_kind:
return validate_exprs(exp->v.JoinedStr.values, Load, 0);
case FormattedValue_kind:
if (validate_expr(exp->v.FormattedValue.value, Load) == 0)
return 0;
if (exp->v.FormattedValue.format_spec)
return validate_expr(exp->v.FormattedValue.format_spec, Load);
return 1;
case Bytes_kind: {
PyObject *b = exp->v.Bytes.s;
if (!PyBytes_CheckExact(b)) {
PyErr_SetString(PyExc_TypeError, "non-bytes type in Bytes");
return 0;
}
return 1;
}
case Attribute_kind:
return validate_expr(exp->v.Attribute.value, Load);
case Subscript_kind:
return validate_slice(exp->v.Subscript.slice) &&
validate_expr(exp->v.Subscript.value, Load);
case Starred_kind:
return validate_expr(exp->v.Starred.value, ctx);
case List_kind:
return validate_exprs(exp->v.List.elts, ctx, 0);
case Tuple_kind:
return validate_exprs(exp->v.Tuple.elts, ctx, 0);
/* These last cases don't have any checking. */
case Name_kind:
case NameConstant_kind:
case Ellipsis_kind:
return 1;
default:
PyErr_SetString(PyExc_SystemError, "unexpected expression");
return 0;
}
}
static int
validate_nonempty_seq(asdl_seq *seq, const char *what, const char *owner)
{
if (asdl_seq_LEN(seq))
return 1;
PyErr_Format(PyExc_ValueError, "empty %s on %s", what, owner);
return 0;
}
static int
validate_assignlist(asdl_seq *targets, expr_context_ty ctx)
{
return validate_nonempty_seq(targets, "targets", ctx == Del ? "Delete" : "Assign") &&
validate_exprs(targets, ctx, 0);
}
static int
validate_body(asdl_seq *body, const char *owner)
{
return validate_nonempty_seq(body, "body", owner) && validate_stmts(body);
}
static int
validate_stmt(stmt_ty stmt)
{
int i;
switch (stmt->kind) {
case FunctionDef_kind:
return validate_body(stmt->v.FunctionDef.body, "FunctionDef") &&
validate_arguments(stmt->v.FunctionDef.args) &&
validate_exprs(stmt->v.FunctionDef.decorator_list, Load, 0) &&
(!stmt->v.FunctionDef.returns ||
validate_expr(stmt->v.FunctionDef.returns, Load));
case ClassDef_kind:
return validate_body(stmt->v.ClassDef.body, "ClassDef") &&
validate_exprs(stmt->v.ClassDef.bases, Load, 0) &&
validate_keywords(stmt->v.ClassDef.keywords) &&
validate_exprs(stmt->v.ClassDef.decorator_list, Load, 0);
case Return_kind:
return !stmt->v.Return.value || validate_expr(stmt->v.Return.value, Load);
case Delete_kind:
return validate_assignlist(stmt->v.Delete.targets, Del);
case Assign_kind:
return validate_assignlist(stmt->v.Assign.targets, Store) &&
validate_expr(stmt->v.Assign.value, Load);
case AugAssign_kind:
return validate_expr(stmt->v.AugAssign.target, Store) &&
validate_expr(stmt->v.AugAssign.value, Load);
case AnnAssign_kind:
if (stmt->v.AnnAssign.target->kind != Name_kind &&
stmt->v.AnnAssign.simple) {
PyErr_SetString(PyExc_TypeError,
"AnnAssign with simple non-Name target");
return 0;
}
return validate_expr(stmt->v.AnnAssign.target, Store) &&
(!stmt->v.AnnAssign.value ||
validate_expr(stmt->v.AnnAssign.value, Load)) &&
validate_expr(stmt->v.AnnAssign.annotation, Load);
case For_kind:
return validate_expr(stmt->v.For.target, Store) &&
validate_expr(stmt->v.For.iter, Load) &&
validate_body(stmt->v.For.body, "For") &&
validate_stmts(stmt->v.For.orelse);
case AsyncFor_kind:
return validate_expr(stmt->v.AsyncFor.target, Store) &&
validate_expr(stmt->v.AsyncFor.iter, Load) &&
validate_body(stmt->v.AsyncFor.body, "AsyncFor") &&
validate_stmts(stmt->v.AsyncFor.orelse);
case While_kind:
return validate_expr(stmt->v.While.test, Load) &&
validate_body(stmt->v.While.body, "While") &&
validate_stmts(stmt->v.While.orelse);
case If_kind:
return validate_expr(stmt->v.If.test, Load) &&
validate_body(stmt->v.If.body, "If") &&
validate_stmts(stmt->v.If.orelse);
case With_kind:
if (!validate_nonempty_seq(stmt->v.With.items, "items", "With"))
return 0;
for (i = 0; i < asdl_seq_LEN(stmt->v.With.items); i++) {
withitem_ty item = asdl_seq_GET(stmt->v.With.items, i);
if (!validate_expr(item->context_expr, Load) ||
(item->optional_vars && !validate_expr(item->optional_vars, Store)))
return 0;
}
return validate_body(stmt->v.With.body, "With");
case AsyncWith_kind:
if (!validate_nonempty_seq(stmt->v.AsyncWith.items, "items", "AsyncWith"))
return 0;
for (i = 0; i < asdl_seq_LEN(stmt->v.AsyncWith.items); i++) {
withitem_ty item = asdl_seq_GET(stmt->v.AsyncWith.items, i);
if (!validate_expr(item->context_expr, Load) ||
(item->optional_vars && !validate_expr(item->optional_vars, Store)))
return 0;
}
return validate_body(stmt->v.AsyncWith.body, "AsyncWith");
case Raise_kind:
if (stmt->v.Raise.exc) {
return validate_expr(stmt->v.Raise.exc, Load) &&
(!stmt->v.Raise.cause || validate_expr(stmt->v.Raise.cause, Load));
}
if (stmt->v.Raise.cause) {
PyErr_SetString(PyExc_ValueError, "Raise with cause but no exception");
return 0;
}
return 1;
case Try_kind:
if (!validate_body(stmt->v.Try.body, "Try"))
return 0;
if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
!asdl_seq_LEN(stmt->v.Try.finalbody)) {
PyErr_SetString(PyExc_ValueError, "Try has neither except handlers nor finalbody");
return 0;
}
if (!asdl_seq_LEN(stmt->v.Try.handlers) &&
asdl_seq_LEN(stmt->v.Try.orelse)) {
PyErr_SetString(PyExc_ValueError, "Try has orelse but no except handlers");
return 0;
}
for (i = 0; i < asdl_seq_LEN(stmt->v.Try.handlers); i++) {
excepthandler_ty handler = asdl_seq_GET(stmt->v.Try.handlers, i);
if ((handler->v.ExceptHandler.type &&
!validate_expr(handler->v.ExceptHandler.type, Load)) ||
!validate_body(handler->v.ExceptHandler.body, "ExceptHandler"))
return 0;
}
return (!asdl_seq_LEN(stmt->v.Try.finalbody) ||
validate_stmts(stmt->v.Try.finalbody)) &&
(!asdl_seq_LEN(stmt->v.Try.orelse) ||
validate_stmts(stmt->v.Try.orelse));
case Assert_kind:
return validate_expr(stmt->v.Assert.test, Load) &&
(!stmt->v.Assert.msg || validate_expr(stmt->v.Assert.msg, Load));
case Import_kind:
return validate_nonempty_seq(stmt->v.Import.names, "names", "Import");
case ImportFrom_kind:
if (stmt->v.ImportFrom.level < 0) {
PyErr_SetString(PyExc_ValueError, "Negative ImportFrom level");
return 0;
}
return validate_nonempty_seq(stmt->v.ImportFrom.names, "names", "ImportFrom");
case Global_kind:
return validate_nonempty_seq(stmt->v.Global.names, "names", "Global");
case Nonlocal_kind:
return validate_nonempty_seq(stmt->v.Nonlocal.names, "names", "Nonlocal");
case Expr_kind:
return validate_expr(stmt->v.Expr.value, Load);
case AsyncFunctionDef_kind:
return validate_body(stmt->v.AsyncFunctionDef.body, "AsyncFunctionDef") &&
validate_arguments(stmt->v.AsyncFunctionDef.args) &&
validate_exprs(stmt->v.AsyncFunctionDef.decorator_list, Load, 0) &&
(!stmt->v.AsyncFunctionDef.returns ||
validate_expr(stmt->v.AsyncFunctionDef.returns, Load));
case Pass_kind:
case Break_kind:
case Continue_kind:
return 1;
default:
PyErr_SetString(PyExc_SystemError, "unexpected statement");
return 0;
}
}
static int
validate_stmts(asdl_seq *seq)
{
int i;
for (i = 0; i < asdl_seq_LEN(seq); i++) {
stmt_ty stmt = asdl_seq_GET(seq, i);
if (stmt) {
if (!validate_stmt(stmt))
return 0;
}
else {
PyErr_SetString(PyExc_ValueError,
"None disallowed in statement list");
return 0;
}
}
return 1;
}
static int
validate_exprs(asdl_seq *exprs, expr_context_ty ctx, int null_ok)
{
int i;
for (i = 0; i < asdl_seq_LEN(exprs); i++) {
expr_ty expr = asdl_seq_GET(exprs, i);
if (expr) {
if (!validate_expr(expr, ctx))
return 0;
}
else if (!null_ok) {
PyErr_SetString(PyExc_ValueError,
"None disallowed in expression list");
return 0;
}
}
return 1;
}
int
Ta3AST_Validate(mod_ty mod)
{
int res = 0;
switch (mod->kind) {
case Module_kind:
res = validate_stmts(mod->v.Module.body);
break;
case Interactive_kind:
res = validate_stmts(mod->v.Interactive.body);
break;
case Expression_kind:
res = validate_expr(mod->v.Expression.body, Load);
break;
case Suite_kind:
PyErr_SetString(PyExc_ValueError, "Suite is not valid in the CPython compiler");
break;
default:
PyErr_SetString(PyExc_SystemError, "impossible module node");
res = 0;
break;
}
return res;
}
/* This is done here, so defines like "test" don't interfere with AST use above. */
#include "grammar.h"
#include "parsetok.h"
#include "graminit.h"
/* Data structure used internally */
struct compiling {
PyArena *c_arena; /* Arena for allocating memory. */
PyObject *c_filename; /* filename */
PyObject *c_normalize; /* Normalization function from unicodedata. */
int c_feature_version; /* Latest minior version of Python for allowed features */
};
static asdl_seq *seq_for_testlist(struct compiling *, const node *);
static expr_ty ast_for_expr(struct compiling *, const node *);
static stmt_ty ast_for_stmt(struct compiling *, const node *);
static asdl_seq *ast_for_suite(struct compiling *c, const node *n);
static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
expr_context_ty);
static expr_ty ast_for_testlist(struct compiling *, const node *);
static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
static stmt_ty ast_for_with_stmt(struct compiling *, const node *, bool);
static stmt_ty ast_for_for_stmt(struct compiling *, const node *, bool);
/* Note different signature for ast_for_call */
static expr_ty ast_for_call(struct compiling *, const node *, expr_ty, bool);
static PyObject *parsenumber(struct compiling *, const char *);
static expr_ty parsestrplus(struct compiling *, const node *n);
#define COMP_GENEXP 0
#define COMP_LISTCOMP 1
#define COMP_SETCOMP 2
static int
init_normalization(struct compiling *c)
{
PyObject *m = PyImport_ImportModuleNoBlock("unicodedata");
if (!m)
return 0;
c->c_normalize = PyObject_GetAttrString(m, "normalize");
Py_DECREF(m);
if (!c->c_normalize)
return 0;
return 1;
}
static identifier
new_identifier(const char *n, struct compiling *c)
{
PyObject *id = PyUnicode_DecodeUTF8(n, strlen(n), NULL);
if (!id)
return NULL;
/* PyUnicode_DecodeUTF8 should always return a ready string. */
assert(PyUnicode_IS_READY(id));
/* Check whether there are non-ASCII characters in the
identifier; if so, normalize to NFKC. */
if (!PyUnicode_IS_ASCII(id)) {
PyObject *id2;
PyObject *form;
PyObject *args[2];
_Py_IDENTIFIER(NFKC);
if (!c->c_normalize && !init_normalization(c)) {
Py_DECREF(id);
return NULL;
}
form = _PyUnicode_FromId(&PyId_NFKC);
if (form == NULL) {
Py_DECREF(id);
return NULL;
}
args[0] = form;
args[1] = id;
id2 = _PyObject_FastCall(c->c_normalize, args, 2);
Py_DECREF(id);
if (!id2)
return NULL;
if (!PyUnicode_Check(id2)) {
PyErr_Format(PyExc_TypeError,
"unicodedata.normalize() must return a string, not "
"%.200s",
Py_TYPE(id2)->tp_name);
Py_DECREF(id2);
return NULL;
}
id = id2;
}
PyUnicode_InternInPlace(&id);
if (PyArena_AddPyObject(c->c_arena, id) < 0) {
Py_DECREF(id);
return NULL;
}
return id;
}
#define NEW_IDENTIFIER(n) new_identifier(STR(n), c)
static string
new_type_comment(const char *s, struct compiling *c)
{
PyObject *res = PyUnicode_DecodeUTF8(s, strlen(s), NULL);
if (!res)
return NULL;
if (PyArena_AddPyObject(c->c_arena, res) < 0) {
Py_DECREF(res);
return NULL;
}
return res;
}
#define NEW_TYPE_COMMENT(n) new_type_comment(STR(n), c)
static int
ast_error(struct compiling *c, const node *n, const char *errmsg)
{
PyObject *value, *errstr, *loc, *tmp;
loc = PyErr_ProgramTextObject(c->c_filename, LINENO(n));
if (!loc) {
Py_INCREF(Py_None);
loc = Py_None;
}
tmp = Py_BuildValue("(OiiN)", c->c_filename, LINENO(n), n->n_col_offset, loc);
if (!tmp)
return 0;
errstr = PyUnicode_FromString(errmsg);
if (!errstr) {
Py_DECREF(tmp);
return 0;
}
value = PyTuple_Pack(2, errstr, tmp);
Py_DECREF(errstr);
Py_DECREF(tmp);
if (value) {
PyErr_SetObject(PyExc_SyntaxError, value);
Py_DECREF(value);
}
return 0;
}
/* num_stmts() returns number of contained statements.
Use this routine to determine how big a sequence is needed for
the statements in a parse tree. Its raison d'etre is this bit of
grammar:
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
A simple_stmt can contain multiple small_stmt elements joined
by semicolons. If the arg is a simple_stmt, the number of
small_stmt elements is returned.
*/
static int
num_stmts(const node *n)
{
int i, l;
node *ch;
switch (TYPE(n)) {
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE)
return 0;
else
return num_stmts(CHILD(n, 0));
case file_input:
l = 0;
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == stmt)
l += num_stmts(ch);
}
return l;
case stmt:
return num_stmts(CHILD(n, 0));
case compound_stmt:
return 1;
case simple_stmt:
return NCH(n) / 2; /* Divide by 2 to remove count of semi-colons */
case suite:
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
if (NCH(n) == 1)
return num_stmts(CHILD(n, 0));
else {
i = 2;
l = 0;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++)
l += num_stmts(CHILD(n, i));
return l;
}
default: {
char buf[128];
sprintf(buf, "Non-statement found: %d %d",
TYPE(n), NCH(n));
Py_FatalError(buf);
}
}
abort();
}
/* Transform the CST rooted at node * to the appropriate AST
*/
mod_ty
Ta3AST_FromNodeObject(const node *n, PyCompilerFlags *flags,
PyObject *filename, int feature_version,
PyArena *arena)
{
int i, j, k, num;
asdl_seq *stmts = NULL;
asdl_seq *type_ignores = NULL;
stmt_ty s;
node *ch;
struct compiling c;
mod_ty res = NULL;
asdl_seq *argtypes = NULL;
expr_ty ret, arg;
c.c_arena = arena;
/* borrowed reference */
c.c_filename = filename;
c.c_normalize = NULL;
c.c_feature_version = feature_version;
if (TYPE(n) == encoding_decl)
n = CHILD(n, 0);
k = 0;
switch (TYPE(n)) {
case file_input:
stmts = _Ta3_asdl_seq_new(num_stmts(n), arena);
if (!stmts)
goto out;
for (i = 0; i < NCH(n) - 1; i++) {
ch = CHILD(n, i);
if (TYPE(ch) == NEWLINE)
continue;
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
s = ast_for_stmt(&c, ch);
if (!s)
goto out;
asdl_seq_SET(stmts, k++, s);
}
else {
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < num; j++) {
s = ast_for_stmt(&c, CHILD(ch, j * 2));
if (!s)
goto out;
asdl_seq_SET(stmts, k++, s);
}
}
}
/* Type ignores are stored under the ENDMARKER in file_input. */
ch = CHILD(n, NCH(n) - 1);
REQ(ch, ENDMARKER);
num = NCH(ch);
type_ignores = _Ta3_asdl_seq_new(num, arena);
if (!type_ignores)
goto out;
for (i = 0; i < num; i++) {
type_ignore_ty ti = TypeIgnore(LINENO(CHILD(ch, i)), arena);
if (!ti)
goto out;
asdl_seq_SET(type_ignores, i, ti);
}
res = Module(stmts, type_ignores, arena);
break;
case eval_input: {
expr_ty testlist_ast;
/* XXX Why not comp_for here? */
testlist_ast = ast_for_testlist(&c, CHILD(n, 0));
if (!testlist_ast)
goto out;
res = Expression(testlist_ast, arena);
break;
}
case single_input:
if (TYPE(CHILD(n, 0)) == NEWLINE) {
stmts = _Ta3_asdl_seq_new(1, arena);
if (!stmts)
goto out;
asdl_seq_SET(stmts, 0, Pass(n->n_lineno, n->n_col_offset,
arena));
if (!asdl_seq_GET(stmts, 0))
goto out;
res = Interactive(stmts, arena);
}
else {
n = CHILD(n, 0);
num = num_stmts(n);
stmts = _Ta3_asdl_seq_new(num, arena);
if (!stmts)
goto out;
if (num == 1) {
s = ast_for_stmt(&c, n);
if (!s)
goto out;
asdl_seq_SET(stmts, 0, s);
}
else {
/* Only a simple_stmt can contain multiple statements. */
REQ(n, simple_stmt);
for (i = 0; i < NCH(n); i += 2) {
if (TYPE(CHILD(n, i)) == NEWLINE)
break;
s = ast_for_stmt(&c, CHILD(n, i));
if (!s)
goto out;
asdl_seq_SET(stmts, i / 2, s);
}
}
res = Interactive(stmts, arena);
}
break;
case func_type_input:
n = CHILD(n, 0);
REQ(n, func_type);
if (TYPE(CHILD(n, 1)) == typelist) {
ch = CHILD(n, 1);
/* this is overly permissive -- we don't pay any attention to
* stars on the args -- just parse them into an ordered list */
num = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test)
num++;
}
argtypes = _Ta3_asdl_seq_new(num, arena);
j = 0;
for (i = 0; i < NCH(ch); i++) {
if (TYPE(CHILD(ch, i)) == test) {
arg = ast_for_expr(&c, CHILD(ch, i));
if (!arg)
goto out;
asdl_seq_SET(argtypes, j++, arg);
}
}
}
else
argtypes = _Ta3_asdl_seq_new(0, arena);
ret = ast_for_expr(&c, CHILD(n, NCH(n) - 1));
if (!ret)
goto out;
res = FunctionType(argtypes, ret, arena);
break;
default:
PyErr_Format(PyExc_SystemError,
"invalid node %d for Ta3AST_FromNode", TYPE(n));
goto out;
}
out:
if (c.c_normalize) {
Py_DECREF(c.c_normalize);
}
return res;
}
mod_ty
Ta3AST_FromNode(const node *n, PyCompilerFlags *flags, const char *filename_str,
int feature_version, PyArena *arena)
{
mod_ty mod;
PyObject *filename;
filename = PyUnicode_DecodeFSDefault(filename_str);
if (filename == NULL)
return NULL;
mod = Ta3AST_FromNodeObject(n, flags, filename, feature_version, arena);
Py_DECREF(filename);
return mod;
}
/* Return the AST repr. of the operator represented as syntax (|, ^, etc.)
*/
static operator_ty
get_operator(struct compiling *c, const node *n)
{
switch (TYPE(n)) {
case VBAR:
return BitOr;
case CIRCUMFLEX:
return BitXor;
case AMPER:
return BitAnd;
case LEFTSHIFT:
return LShift;
case RIGHTSHIFT:
return RShift;
case PLUS:
return Add;
case MINUS:
return Sub;
case STAR:
return Mult;
case AT:
if (c->c_feature_version < 5) {
ast_error(c, n,
"The '@' operator is only supported in Python 3.5 and greater");
return (operator_ty)0;
}
return MatMult;
case SLASH:
return Div;
case DOUBLESLASH:
return FloorDiv;
case PERCENT:
return Mod;
default:
return (operator_ty)0;
}
}
static const char * const FORBIDDEN[] = {
"None",
"True",
"False",
NULL,
};
static int
forbidden_name(struct compiling *c, identifier name, const node *n,
int full_checks)
{
assert(PyUnicode_Check(name));
if (_PyUnicode_EqualToASCIIString(name, "__debug__")) {
ast_error(c, n, "assignment to keyword");
return 1;
}
if (full_checks) {
const char * const *p;
for (p = FORBIDDEN; *p; p++) {
if (_PyUnicode_EqualToASCIIString(name, *p)) {
ast_error(c, n, "assignment to keyword");
return 1;
}
}
}
return 0;
}
/* Set the context ctx for expr_ty e, recursively traversing e.
Only sets context for expr kinds that "can appear in assignment context"
(according to ../Parser/Python.asdl). For other expr kinds, it sets
an appropriate syntax error and returns false.
*/
static int
set_context(struct compiling *c, expr_ty e, expr_context_ty ctx, const node *n)
{
asdl_seq *s = NULL;
/* If a particular expression type can't be used for assign / delete,
set expr_name to its name and an error message will be generated.
*/
const char* expr_name = NULL;
/* The ast defines augmented store and load contexts, but the
implementation here doesn't actually use them. The code may be
a little more complex than necessary as a result. It also means
that expressions in an augmented assignment have a Store context.
Consider restructuring so that augmented assignment uses
set_context(), too.
*/
assert(ctx != AugStore && ctx != AugLoad);
switch (e->kind) {
case Attribute_kind:
e->v.Attribute.ctx = ctx;
if (ctx == Store && forbidden_name(c, e->v.Attribute.attr, n, 1))
return 0;
break;
case Subscript_kind:
e->v.Subscript.ctx = ctx;
break;
case Starred_kind:
e->v.Starred.ctx = ctx;
if (!set_context(c, e->v.Starred.value, ctx, n))
return 0;
break;
case Name_kind:
if (ctx == Store) {
if (forbidden_name(c, e->v.Name.id, n, 0))
return 0; /* forbidden_name() calls ast_error() */
}
e->v.Name.ctx = ctx;
break;
case List_kind:
e->v.List.ctx = ctx;
s = e->v.List.elts;
break;
case Tuple_kind:
e->v.Tuple.ctx = ctx;
s = e->v.Tuple.elts;
break;
case Lambda_kind:
expr_name = "lambda";
break;
case Call_kind:
expr_name = "function call";
break;
case BoolOp_kind:
case BinOp_kind:
case UnaryOp_kind:
expr_name = "operator";
break;
case GeneratorExp_kind:
expr_name = "generator expression";
break;
case Yield_kind:
case YieldFrom_kind:
expr_name = "yield expression";
break;
case Await_kind:
expr_name = "await expression";
break;
case ListComp_kind:
expr_name = "list comprehension";
break;
case SetComp_kind:
expr_name = "set comprehension";
break;
case DictComp_kind:
expr_name = "dict comprehension";
break;
case Dict_kind:
case Set_kind:
case Num_kind:
case Str_kind:
case Bytes_kind:
case JoinedStr_kind:
case FormattedValue_kind:
expr_name = "literal";
break;
case NameConstant_kind:
expr_name = "keyword";
break;
case Ellipsis_kind:
expr_name = "Ellipsis";
break;
case Compare_kind:
expr_name = "comparison";
break;
case IfExp_kind:
expr_name = "conditional expression";
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected expression in assignment %d (line %d)",
e->kind, e->lineno);
return 0;
}
/* Check for error string set by switch */
if (expr_name) {
char buf[300];
PyOS_snprintf(buf, sizeof(buf),
"can't %s %s",
ctx == Store ? "assign to" : "delete",
expr_name);
return ast_error(c, n, buf);
}
/* If the LHS is a list or tuple, we need to set the assignment
context for all the contained elements.
*/
if (s) {
int i;
for (i = 0; i < asdl_seq_LEN(s); i++) {
if (!set_context(c, (expr_ty)asdl_seq_GET(s, i), ctx, n))
return 0;
}
}
return 1;
}
static operator_ty
ast_for_augassign(struct compiling *c, const node *n)
{
REQ(n, augassign);
n = CHILD(n, 0);
switch (STR(n)[0]) {
case '+':
return Add;
case '-':
return Sub;
case '/':
if (STR(n)[1] == '/')
return FloorDiv;
else
return Div;
case '%':
return Mod;
case '<':
return LShift;
case '>':
return RShift;
case '&':
return BitAnd;
case '^':
return BitXor;
case '|':
return BitOr;
case '*':
if (STR(n)[1] == '*')
return Pow;
else
return Mult;
case '@':
if (c->c_feature_version < 5) {
ast_error(c, n,
"The '@' operator is only supported in Python 3.5 and greater");
return (operator_ty)0;
}
return MatMult;
default:
PyErr_Format(PyExc_SystemError, "invalid augassign: %s", STR(n));
return (operator_ty)0;
}
}
static cmpop_ty
ast_for_comp_op(struct compiling *c, const node *n)
{
/* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'
|'is' 'not'
*/
REQ(n, comp_op);
if (NCH(n) == 1) {
n = CHILD(n, 0);
switch (TYPE(n)) {
case LESS:
return Lt;
case GREATER:
return Gt;
case EQEQUAL: /* == */
return Eq;
case LESSEQUAL:
return LtE;
case GREATEREQUAL:
return GtE;
case NOTEQUAL:
return NotEq;
case NAME:
if (strcmp(STR(n), "in") == 0)
return In;
if (strcmp(STR(n), "is") == 0)
return Is;
/* fall through */
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s",
STR(n));
return (cmpop_ty)0;
}
}
else if (NCH(n) == 2) {
/* handle "not in" and "is not" */
switch (TYPE(CHILD(n, 0))) {
case NAME:
if (strcmp(STR(CHILD(n, 1)), "in") == 0)
return NotIn;
if (strcmp(STR(CHILD(n, 0)), "is") == 0)
return IsNot;
/* fall through */
default:
PyErr_Format(PyExc_SystemError, "invalid comp_op: %s %s",
STR(CHILD(n, 0)), STR(CHILD(n, 1)));
return (cmpop_ty)0;
}
}
PyErr_Format(PyExc_SystemError, "invalid comp_op: has %d children",
NCH(n));
return (cmpop_ty)0;
}
static asdl_seq *
seq_for_testlist(struct compiling *c, const node *n)
{
/* testlist: test (',' test)* [',']
testlist_star_expr: test|star_expr (',' test|star_expr)* [',']
*/
asdl_seq *seq;
expr_ty expression;
int i;
assert(TYPE(n) == testlist || TYPE(n) == testlist_star_expr || TYPE(n) == testlist_comp);
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
const node *ch = CHILD(n, i);
assert(TYPE(ch) == test || TYPE(ch) == test_nocond || TYPE(ch) == star_expr);
expression = ast_for_expr(c, ch);
if (!expression)
return NULL;
assert(i / 2 < seq->size);
asdl_seq_SET(seq, i / 2, expression);
}
return seq;
}
static arg_ty
ast_for_arg(struct compiling *c, const node *n)
{
identifier name;
expr_ty annotation = NULL;
node *ch;
arg_ty ret;
assert(TYPE(n) == tfpdef || TYPE(n) == vfpdef);
ch = CHILD(n, 0);
name = NEW_IDENTIFIER(ch);
if (!name)
return NULL;
if (forbidden_name(c, name, ch, 0))
return NULL;
if (NCH(n) == 3 && TYPE(CHILD(n, 1)) == COLON) {
annotation = ast_for_expr(c, CHILD(n, 2));
if (!annotation)
return NULL;
}
ret = arg(name, annotation, NULL, LINENO(n), n->n_col_offset, c->c_arena);
if (!ret)
return NULL;
return ret;
}
/* returns -1 if failed to handle keyword only arguments
returns new position to keep processing if successful
(',' tfpdef ['=' test])*
^^^
start pointing here
*/
static int
handle_keywordonly_args(struct compiling *c, const node *n, int start,
asdl_seq *kwonlyargs, asdl_seq *kwdefaults)
{
PyObject *argname;
node *ch;
expr_ty expression, annotation;
arg_ty arg = NULL;
int i = start;
int j = 0; /* index for kwdefaults and kwonlyargs */
if (kwonlyargs == NULL) {
ast_error(c, CHILD(n, start), "named arguments must follow bare *");
return -1;
}
assert(kwdefaults != NULL);
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case vfpdef:
case tfpdef:
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
goto error;
asdl_seq_SET(kwdefaults, j, expression);
i += 2; /* '=' and test */
}
else { /* setting NULL if no default value exists */
asdl_seq_SET(kwdefaults, j, NULL);
}
if (NCH(ch) == 3) {
/* ch is NAME ':' test */
annotation = ast_for_expr(c, CHILD(ch, 2));
if (!annotation)
goto error;
}
else {
annotation = NULL;
}
ch = CHILD(ch, 0);
argname = NEW_IDENTIFIER(ch);
if (!argname)
goto error;
if (forbidden_name(c, argname, ch, 0))
goto error;
arg = arg(argname, annotation, NULL, LINENO(ch), ch->n_col_offset,
c->c_arena);
if (!arg)
goto error;
asdl_seq_SET(kwonlyargs, j++, arg);
i += 1; /* the name */
if (TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
/* arg will be equal to the last argument processed */
arg->type_comment = NEW_TYPE_COMMENT(ch);
if (!arg->type_comment)
goto error;
i += 1;
break;
case DOUBLESTAR:
return i;
default:
ast_error(c, ch, "unexpected node");
goto error;
}
}
return i;
error:
return -1;
}
/* Create AST for argument list. */
static arguments_ty
ast_for_arguments(struct compiling *c, const node *n)
{
/* This function handles both typedargslist (function definition)
and varargslist (lambda definition).
parameters: '(' [typedargslist] ')'
typedargslist: (tfpdef ['=' test] (',' tfpdef ['=' test])* [',' [
'*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
| '**' tfpdef [',']]]
| '*' [tfpdef] (',' tfpdef ['=' test])* [',' ['**' tfpdef [',']]]
| '**' tfpdef [','])
tfpdef: NAME [':' test]
varargslist: (vfpdef ['=' test] (',' vfpdef ['=' test])* [',' [
'*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
| '**' vfpdef [',']]]
| '*' [vfpdef] (',' vfpdef ['=' test])* [',' ['**' vfpdef [',']]]
| '**' vfpdef [',']
)
vfpdef: NAME
*/
int i, j, k, nposargs = 0, nkwonlyargs = 0;
int nposdefaults = 0, found_default = 0;
asdl_seq *posargs, *posdefaults, *kwonlyargs, *kwdefaults;
arg_ty vararg = NULL, kwarg = NULL;
arg_ty arg = NULL;
node *ch;
if (TYPE(n) == parameters) {
if (NCH(n) == 2) /* () as argument list */
return arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
n = CHILD(n, 1);
}
assert(TYPE(n) == typedargslist || TYPE(n) == varargslist);
/* First count the number of positional args & defaults. The
variable i is the loop index for this for loop and the next.
The next loop picks up where the first leaves off.
*/
for (i = 0; i < NCH(n); i++) {
ch = CHILD(n, i);
if (TYPE(ch) == STAR) {
/* skip star */
i++;
if (i < NCH(n) && /* skip argument following star */
(TYPE(CHILD(n, i)) == tfpdef ||
TYPE(CHILD(n, i)) == vfpdef)) {
i++;
}
break;
}
if (TYPE(ch) == DOUBLESTAR) break;
if (TYPE(ch) == vfpdef || TYPE(ch) == tfpdef) nposargs++;
if (TYPE(ch) == EQUAL) nposdefaults++;
}
/* count the number of keyword only args &
defaults for keyword only args */
for ( ; i < NCH(n); ++i) {
ch = CHILD(n, i);
if (TYPE(ch) == DOUBLESTAR) break;
if (TYPE(ch) == tfpdef || TYPE(ch) == vfpdef) nkwonlyargs++;
}
posargs = (nposargs ? _Ta3_asdl_seq_new(nposargs, c->c_arena) : NULL);
if (!posargs && nposargs)
return NULL;
kwonlyargs = (nkwonlyargs ?
_Ta3_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
if (!kwonlyargs && nkwonlyargs)
return NULL;
posdefaults = (nposdefaults ?
_Ta3_asdl_seq_new(nposdefaults, c->c_arena) : NULL);
if (!posdefaults && nposdefaults)
return NULL;
/* The length of kwonlyargs and kwdefaults are same
since we set NULL as default for keyword only argument w/o default
- we have sequence data structure, but no dictionary */
kwdefaults = (nkwonlyargs ?
_Ta3_asdl_seq_new(nkwonlyargs, c->c_arena) : NULL);
if (!kwdefaults && nkwonlyargs)
return NULL;
/* tfpdef: NAME [':' test]
vfpdef: NAME
*/
i = 0;
j = 0; /* index for defaults */
k = 0; /* index for args */
while (i < NCH(n)) {
ch = CHILD(n, i);
switch (TYPE(ch)) {
case tfpdef:
case vfpdef:
/* XXX Need to worry about checking if TYPE(CHILD(n, i+1)) is
anything other than EQUAL or a comma? */
/* XXX Should NCH(n) check be made a separate check? */
if (i + 1 < NCH(n) && TYPE(CHILD(n, i + 1)) == EQUAL) {
expr_ty expression = ast_for_expr(c, CHILD(n, i + 2));
if (!expression)
return NULL;
assert(posdefaults != NULL);
asdl_seq_SET(posdefaults, j++, expression);
i += 2;
found_default = 1;
}
else if (found_default) {
ast_error(c, n,
"non-default argument follows default argument");
return NULL;
}
arg = ast_for_arg(c, ch);
if (!arg)
return NULL;
asdl_seq_SET(posargs, k++, arg);
i += 1; /* the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case STAR:
if (i+1 >= NCH(n) ||
(i+2 == NCH(n) && (TYPE(CHILD(n, i+1)) == COMMA
|| TYPE(CHILD(n, i+1)) == TYPE_COMMENT))) {
ast_error(c, CHILD(n, i),
"named arguments must follow bare *");
return NULL;
}
ch = CHILD(n, i+1); /* tfpdef or COMMA */
if (TYPE(ch) == COMMA) {
int res = 0;
i += 2; /* now follows keyword only arguments */
if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) {
ast_error(c, CHILD(n, i),
"bare * has associated type comment");
return NULL;
}
res = handle_keywordonly_args(c, n, i,
kwonlyargs, kwdefaults);
if (res == -1) return NULL;
i = res; /* res has new position to process */
}
else {
vararg = ast_for_arg(c, ch);
if (!vararg)
return NULL;
i += 2; /* the star and the name */
if (i < NCH(n) && TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
if (i < NCH(n) && TYPE(CHILD(n, i)) == TYPE_COMMENT) {
vararg->type_comment = NEW_TYPE_COMMENT(CHILD(n, i));
if (!vararg->type_comment)
return NULL;
i += 1;
}
if (i < NCH(n) && (TYPE(CHILD(n, i)) == tfpdef
|| TYPE(CHILD(n, i)) == vfpdef)) {
int res = 0;
res = handle_keywordonly_args(c, n, i,
kwonlyargs, kwdefaults);
if (res == -1) return NULL;
i = res; /* res has new position to process */
}
}
break;
case DOUBLESTAR:
ch = CHILD(n, i+1); /* tfpdef */
assert(TYPE(ch) == tfpdef || TYPE(ch) == vfpdef);
kwarg = ast_for_arg(c, ch);
if (!kwarg)
return NULL;
i += 2; /* the double star and the name */
if (TYPE(CHILD(n, i)) == COMMA)
i += 1; /* the comma, if present */
break;
case TYPE_COMMENT:
assert(i);
if (kwarg)
arg = kwarg;
/* arg will be equal to the last argument processed */
arg->type_comment = NEW_TYPE_COMMENT(ch);
if (!arg->type_comment)
return NULL;
i += 1;
break;
default:
PyErr_Format(PyExc_SystemError,
"unexpected node in varargslist: %d @ %d",
TYPE(ch), i);
return NULL;
}
}
return arguments(posargs, vararg, kwonlyargs, kwdefaults, kwarg, posdefaults, c->c_arena);
}
static expr_ty
ast_for_dotted_name(struct compiling *c, const node *n)
{
expr_ty e;
identifier id;
int lineno, col_offset;
int i;
REQ(n, dotted_name);
lineno = LINENO(n);
col_offset = n->n_col_offset;
id = NEW_IDENTIFIER(CHILD(n, 0));
if (!id)
return NULL;
e = Name(id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
for (i = 2; i < NCH(n); i+=2) {
id = NEW_IDENTIFIER(CHILD(n, i));
if (!id)
return NULL;
e = Attribute(e, id, Load, lineno, col_offset, c->c_arena);
if (!e)
return NULL;
}
return e;
}
static expr_ty
ast_for_decorator(struct compiling *c, const node *n)
{
/* decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE */
expr_ty d = NULL;
expr_ty name_expr;
REQ(n, decorator);
REQ(CHILD(n, 0), AT);
REQ(RCHILD(n, -1), NEWLINE);
name_expr = ast_for_dotted_name(c, CHILD(n, 1));
if (!name_expr)
return NULL;
if (NCH(n) == 3) { /* No arguments */
d = name_expr;
name_expr = NULL;
}
else if (NCH(n) == 5) { /* Call with no arguments */
d = Call(name_expr, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
if (!d)
return NULL;
name_expr = NULL;
}
else {
d = ast_for_call(c, CHILD(n, 3), name_expr, true);
if (!d)
return NULL;
name_expr = NULL;
}
return d;
}
static asdl_seq*
ast_for_decorators(struct compiling *c, const node *n)
{
asdl_seq* decorator_seq;
expr_ty d;
int i;
REQ(n, decorators);
decorator_seq = _Ta3_asdl_seq_new(NCH(n), c->c_arena);
if (!decorator_seq)
return NULL;
for (i = 0; i < NCH(n); i++) {
d = ast_for_decorator(c, CHILD(n, i));
if (!d)
return NULL;
asdl_seq_SET(decorator_seq, i, d);
}
return decorator_seq;
}
static stmt_ty
ast_for_funcdef_impl(struct compiling *c, const node *n0,
asdl_seq *decorator_seq, bool is_async)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' [TYPE_COMMENT] suite */
const node * const n = is_async ? CHILD(n0, 1) : n0;
identifier name;
arguments_ty args;
asdl_seq *body;
expr_ty returns = NULL;
int name_i = 1;
node *tc;
string type_comment = NULL;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async functions are only supported in Python 3.5 and greater");
return NULL;
}
REQ(n, funcdef);
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
if (forbidden_name(c, name, CHILD(n, name_i), 0))
return NULL;
args = ast_for_arguments(c, CHILD(n, name_i + 1));
if (!args)
return NULL;
if (TYPE(CHILD(n, name_i+2)) == RARROW) {
returns = ast_for_expr(c, CHILD(n, name_i + 3));
if (!returns)
return NULL;
name_i += 2;
}
if (TYPE(CHILD(n, name_i + 3)) == TYPE_COMMENT) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, name_i + 3));
if (!type_comment)
return NULL;
name_i += 1;
}
body = ast_for_suite(c, CHILD(n, name_i + 3));
if (!body)
return NULL;
if (NCH(CHILD(n, name_i + 3)) > 1) {
/* Check if the suite has a type comment in it. */
tc = CHILD(CHILD(n, name_i + 3), 1);
if (TYPE(tc) == TYPE_COMMENT) {
if (type_comment != NULL) {
ast_error(c, n, "Cannot have two type comments on def");
return NULL;
}
type_comment = NEW_TYPE_COMMENT(tc);
if (!type_comment)
return NULL;
}
}
if (is_async)
return AsyncFunctionDef(name, args, body, decorator_seq, returns,
type_comment, LINENO(n0), n0->n_col_offset, c->c_arena);
else
return FunctionDef(name, args, body, decorator_seq, returns,
type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_async_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* async_funcdef: 'async' funcdef */
REQ(n, async_funcdef);
REQ(CHILD(n, 0), ASYNC);
REQ(CHILD(n, 1), funcdef);
return ast_for_funcdef_impl(c, n, decorator_seq,
true /* is_async */);
}
static stmt_ty
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' NAME parameters ['->' test] ':' suite */
return ast_for_funcdef_impl(c, n, decorator_seq,
false /* is_async */);
}
static stmt_ty
ast_for_async_stmt(struct compiling *c, const node *n)
{
/* async_stmt: 'async' (funcdef | with_stmt | for_stmt) */
REQ(n, async_stmt);
REQ(CHILD(n, 0), ASYNC);
switch (TYPE(CHILD(n, 1))) {
case funcdef:
return ast_for_funcdef_impl(c, n, NULL,
true /* is_async */);
case with_stmt:
return ast_for_with_stmt(c, n,
true /* is_async */);
case for_stmt:
return ast_for_for_stmt(c, n,
true /* is_async */);
default:
PyErr_Format(PyExc_SystemError,
"invalid async stament: %s",
STR(CHILD(n, 1)));
return NULL;
}
}
static stmt_ty
ast_for_decorated(struct compiling *c, const node *n)
{
/* decorated: decorators (classdef | funcdef | async_funcdef) */
stmt_ty thing = NULL;
asdl_seq *decorator_seq = NULL;
REQ(n, decorated);
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
assert(TYPE(CHILD(n, 1)) == funcdef ||
TYPE(CHILD(n, 1)) == async_funcdef ||
TYPE(CHILD(n, 1)) == classdef);
if (TYPE(CHILD(n, 1)) == funcdef) {
thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == classdef) {
thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == async_funcdef) {
thing = ast_for_async_funcdef(c, CHILD(n, 1), decorator_seq);
}
/* we count the decorators in when talking about the class' or
* function's line number */
if (thing) {
thing->lineno = LINENO(n);
thing->col_offset = n->n_col_offset;
}
return thing;
}
static expr_ty
ast_for_lambdef(struct compiling *c, const node *n)
{
/* lambdef: 'lambda' [varargslist] ':' test
lambdef_nocond: 'lambda' [varargslist] ':' test_nocond */
arguments_ty args;
expr_ty expression;
if (NCH(n) == 3) {
args = arguments(NULL, NULL, NULL, NULL, NULL, NULL, c->c_arena);
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
}
else {
args = ast_for_arguments(c, CHILD(n, 1));
if (!args)
return NULL;
expression = ast_for_expr(c, CHILD(n, 3));
if (!expression)
return NULL;
}
return Lambda(args, expression, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_ifexpr(struct compiling *c, const node *n)
{
/* test: or_test 'if' or_test 'else' test */
expr_ty expression, body, orelse;
assert(NCH(n) == 5);
body = ast_for_expr(c, CHILD(n, 0));
if (!body)
return NULL;
expression = ast_for_expr(c, CHILD(n, 2));
if (!expression)
return NULL;
orelse = ast_for_expr(c, CHILD(n, 4));
if (!orelse)
return NULL;
return IfExp(expression, body, orelse, LINENO(n), n->n_col_offset,
c->c_arena);
}
/*
Count the number of 'for' loops in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_fors(struct compiling *c, const node *n)
{
int n_fors = 0;
count_comp_for:
n_fors++;
REQ(n, comp_for);
if (NCH(n) == 2) {
REQ(CHILD(n, 0), ASYNC);
n = CHILD(n, 1);
}
else if (NCH(n) == 1) {
n = CHILD(n, 0);
}
else {
goto error;
}
if (NCH(n) == (5)) {
n = CHILD(n, 4);
}
else {
return n_fors;
}
count_comp_iter:
REQ(n, comp_iter);
n = CHILD(n, 0);
if (TYPE(n) == comp_for)
goto count_comp_for;
else if (TYPE(n) == comp_if) {
if (NCH(n) == 3) {
n = CHILD(n, 2);
goto count_comp_iter;
}
else
return n_fors;
}
error:
/* Should never be reached */
PyErr_SetString(PyExc_SystemError,
"logic error in count_comp_fors");
return -1;
}
/* Count the number of 'if' statements in a comprehension.
Helper for ast_for_comprehension().
*/
static int
count_comp_ifs(struct compiling *c, const node *n)
{
int n_ifs = 0;
while (1) {
REQ(n, comp_iter);
if (TYPE(CHILD(n, 0)) == comp_for)
return n_ifs;
n = CHILD(n, 0);
REQ(n, comp_if);
n_ifs++;
if (NCH(n) == 2)
return n_ifs;
n = CHILD(n, 2);
}
}
static asdl_seq *
ast_for_comprehension(struct compiling *c, const node *n)
{
int i, n_fors;
asdl_seq *comps;
n_fors = count_comp_fors(c, n);
if (n_fors == -1)
return NULL;
comps = _Ta3_asdl_seq_new(n_fors, c->c_arena);
if (!comps)
return NULL;
for (i = 0; i < n_fors; i++) {
comprehension_ty comp;
asdl_seq *t;
expr_ty expression, first;
node *for_ch;
node *sync_n;
int is_async = 0;
REQ(n, comp_for);
if (NCH(n) == 2) {
is_async = 1;
REQ(CHILD(n, 0), ASYNC);
sync_n = CHILD(n, 1);
}
else {
sync_n = CHILD(n, 0);
}
REQ(sync_n, sync_comp_for);
/* Async comprehensions only allowed in Python 3.6 and greater */
if (is_async && c->c_feature_version < 6) {
ast_error(c, n,
"Async comprehensions are only supported in Python 3.6 and greater");
return NULL;
}
for_ch = CHILD(sync_n, 1);
t = ast_for_exprlist(c, for_ch, Store);
if (!t)
return NULL;
expression = ast_for_expr(c, CHILD(sync_n, 3));
if (!expression)
return NULL;
/* Check the # of children rather than the length of t, since
(x for x, in ...) has 1 element in t, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(t, 0);
if (NCH(for_ch) == 1)
comp = comprehension(first, expression, NULL,
is_async, c->c_arena);
else
comp = comprehension(Tuple(t, Store, first->lineno,
first->col_offset, c->c_arena),
expression, NULL, is_async, c->c_arena);
if (!comp)
return NULL;
if (NCH(sync_n) == 5) {
int j, n_ifs;
asdl_seq *ifs;
n = CHILD(sync_n, 4);
n_ifs = count_comp_ifs(c, n);
if (n_ifs == -1)
return NULL;
ifs = _Ta3_asdl_seq_new(n_ifs, c->c_arena);
if (!ifs)
return NULL;
for (j = 0; j < n_ifs; j++) {
REQ(n, comp_iter);
n = CHILD(n, 0);
REQ(n, comp_if);
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
asdl_seq_SET(ifs, j, expression);
if (NCH(n) == 3)
n = CHILD(n, 2);
}
/* on exit, must guarantee that n is a comp_for */
if (TYPE(n) == comp_iter)
n = CHILD(n, 0);
comp->ifs = ifs;
}
asdl_seq_SET(comps, i, comp);
}
return comps;
}
static expr_ty
ast_for_itercomp(struct compiling *c, const node *n, int type)
{
/* testlist_comp: (test|star_expr)
* ( comp_for | (',' (test|star_expr))* [','] ) */
expr_ty elt;
asdl_seq *comps;
node *ch;
assert(NCH(n) > 1);
ch = CHILD(n, 0);
elt = ast_for_expr(c, ch);
if (!elt)
return NULL;
if (elt->kind == Starred_kind) {
ast_error(c, ch, "iterable unpacking cannot be used in comprehension");
return NULL;
}
comps = ast_for_comprehension(c, CHILD(n, 1));
if (!comps)
return NULL;
if (type == COMP_GENEXP)
return GeneratorExp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_LISTCOMP)
return ListComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else if (type == COMP_SETCOMP)
return SetComp(elt, comps, LINENO(n), n->n_col_offset, c->c_arena);
else
/* Should never happen */
return NULL;
}
/* Fills in the key, value pair corresponding to the dict element. In case
* of an unpacking, key is NULL. *i is advanced by the number of ast
* elements. Iff successful, nonzero is returned.
*/
static int
ast_for_dictelement(struct compiling *c, const node *n, int *i,
expr_ty *key, expr_ty *value)
{
expr_ty expression;
if (TYPE(CHILD(n, *i)) == DOUBLESTAR) {
assert(NCH(n) - *i >= 2);
expression = ast_for_expr(c, CHILD(n, *i + 1));
if (!expression)
return 0;
*key = NULL;
*value = expression;
*i += 2;
}
else {
assert(NCH(n) - *i >= 3);
expression = ast_for_expr(c, CHILD(n, *i));
if (!expression)
return 0;
*key = expression;
REQ(CHILD(n, *i + 1), COLON);
expression = ast_for_expr(c, CHILD(n, *i + 2));
if (!expression)
return 0;
*value = expression;
*i += 3;
}
return 1;
}
static expr_ty
ast_for_dictcomp(struct compiling *c, const node *n)
{
expr_ty key, value;
asdl_seq *comps;
int i = 0;
if (!ast_for_dictelement(c, n, &i, &key, &value))
return NULL;
assert(key);
assert(NCH(n) - i >= 1);
comps = ast_for_comprehension(c, CHILD(n, i));
if (!comps)
return NULL;
return DictComp(key, value, comps, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_dictdisplay(struct compiling *c, const node *n)
{
int i;
int j;
int size;
asdl_seq *keys, *values;
size = (NCH(n) + 1) / 3; /* +1 in case no trailing comma */
keys = _Ta3_asdl_seq_new(size, c->c_arena);
if (!keys)
return NULL;
values = _Ta3_asdl_seq_new(size, c->c_arena);
if (!values)
return NULL;
j = 0;
for (i = 0; i < NCH(n); i++) {
expr_ty key, value;
if (!ast_for_dictelement(c, n, &i, &key, &value))
return NULL;
asdl_seq_SET(keys, j, key);
asdl_seq_SET(values, j, value);
j++;
}
keys->size = j;
values->size = j;
return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_genexp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp) || TYPE(n) == (argument));
return ast_for_itercomp(c, n, COMP_GENEXP);
}
static expr_ty
ast_for_listcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (testlist_comp));
return ast_for_itercomp(c, n, COMP_LISTCOMP);
}
static expr_ty
ast_for_setcomp(struct compiling *c, const node *n)
{
assert(TYPE(n) == (dictorsetmaker));
return ast_for_itercomp(c, n, COMP_SETCOMP);
}
static expr_ty
ast_for_setdisplay(struct compiling *c, const node *n)
{
int i;
int size;
asdl_seq *elts;
assert(TYPE(n) == (dictorsetmaker));
size = (NCH(n) + 1) / 2; /* +1 in case no trailing comma */
elts = _Ta3_asdl_seq_new(size, c->c_arena);
if (!elts)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty expression;
expression = ast_for_expr(c, CHILD(n, i));
if (!expression)
return NULL;
asdl_seq_SET(elts, i / 2, expression);
}
return Set(elts, LINENO(n), n->n_col_offset, c->c_arena);
}
static expr_ty
ast_for_atom(struct compiling *c, const node *n)
{
/* atom: '(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']'
| '{' [dictmaker|testlist_comp] '}' | NAME | NUMBER | STRING+
| '...' | 'None' | 'True' | 'False'
*/
node *ch = CHILD(n, 0);
switch (TYPE(ch)) {
case NAME: {
PyObject *name;
const char *s = STR(ch);
size_t len = strlen(s);
if (len >= 4 && len <= 5) {
if (!strcmp(s, "None"))
return NameConstant(Py_None, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "True"))
return NameConstant(Py_True, LINENO(n), n->n_col_offset, c->c_arena);
if (!strcmp(s, "False"))
return NameConstant(Py_False, LINENO(n), n->n_col_offset, c->c_arena);
}
name = new_identifier(s, c);
if (!name)
return NULL;
/* All names start in Load context, but may later be changed. */
return Name(name, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
case STRING: {
expr_ty str = parsestrplus(c, n);
if (!str) {
const char *errtype = NULL;
if (PyErr_ExceptionMatches(PyExc_UnicodeError))
errtype = "unicode error";
else if (PyErr_ExceptionMatches(PyExc_ValueError))
errtype = "value error";
if (errtype) {
char buf[128];
const char *s = NULL;
PyObject *type, *value, *tback, *errstr;
PyErr_Fetch(&type, &value, &tback);
errstr = PyObject_Str(value);
if (errstr)
s = PyUnicode_AsUTF8(errstr);
if (s) {
PyOS_snprintf(buf, sizeof(buf), "(%s) %s", errtype, s);
} else {
PyErr_Clear();
PyOS_snprintf(buf, sizeof(buf), "(%s) unknown error", errtype);
}
Py_XDECREF(errstr);
ast_error(c, n, buf);
Py_DECREF(type);
Py_XDECREF(value);
Py_XDECREF(tback);
}
return NULL;
}
return str;
}
case NUMBER: {
PyObject *pynum;
const char *s = STR(ch);
/* Underscores in numeric literals are only allowed in Python 3.6 or greater */
/* Check for underscores here rather than in parse_number so we can report a line number on error */
if (c->c_feature_version < 6 && strchr(s, '_') != NULL) {
ast_error(c, ch,
"Underscores in numeric literals are only supported in Python 3.6 and greater");
return NULL;
}
pynum = parsenumber(c, STR(ch));
if (!pynum)
return NULL;
if (PyArena_AddPyObject(c->c_arena, pynum) < 0) {
Py_DECREF(pynum);
return NULL;
}
return Num(pynum, LINENO(n), n->n_col_offset, c->c_arena);
}
case ELLIPSIS: /* Ellipsis */
return Ellipsis(LINENO(n), n->n_col_offset, c->c_arena);
case LPAR: /* some parenthesized expressions */
ch = CHILD(n, 1);
if (TYPE(ch) == RPAR)
return Tuple(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (TYPE(ch) == yield_expr)
return ast_for_expr(c, ch);
/* testlist_comp: test ( comp_for | (',' test)* [','] ) */
if ((NCH(ch) > 1) && (TYPE(CHILD(ch, 1)) == comp_for))
return ast_for_genexp(c, ch);
return ast_for_testlist(c, ch);
case LSQB: /* list (or list comprehension) */
ch = CHILD(n, 1);
if (TYPE(ch) == RSQB)
return List(NULL, Load, LINENO(n), n->n_col_offset, c->c_arena);
REQ(ch, testlist_comp);
if (NCH(ch) == 1 || TYPE(CHILD(ch, 1)) == COMMA) {
asdl_seq *elts = seq_for_testlist(c, ch);
if (!elts)
return NULL;
return List(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
else
return ast_for_listcomp(c, ch);
case LBRACE: {
/* dictorsetmaker: ( ((test ':' test | '**' test)
* (comp_for | (',' (test ':' test | '**' test))* [','])) |
* ((test | '*' test)
* (comp_for | (',' (test | '*' test))* [','])) ) */
expr_ty res;
ch = CHILD(n, 1);
if (TYPE(ch) == RBRACE) {
/* It's an empty dict. */
return Dict(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
int is_dict = (TYPE(CHILD(ch, 0)) == DOUBLESTAR);
if (NCH(ch) == 1 ||
(NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == COMMA)) {
/* It's a set display. */
res = ast_for_setdisplay(c, ch);
}
else if (NCH(ch) > 1 &&
TYPE(CHILD(ch, 1)) == comp_for) {
/* It's a set comprehension. */
res = ast_for_setcomp(c, ch);
}
else if (NCH(ch) > 3 - is_dict &&
TYPE(CHILD(ch, 3 - is_dict)) == comp_for) {
/* It's a dictionary comprehension. */
if (is_dict) {
ast_error(c, n, "dict unpacking cannot be used in "
"dict comprehension");
return NULL;
}
res = ast_for_dictcomp(c, ch);
}
else {
/* It's a dictionary display. */
res = ast_for_dictdisplay(c, ch);
}
if (res) {
res->lineno = LINENO(n);
res->col_offset = n->n_col_offset;
}
return res;
}
}
default:
PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch));
return NULL;
}
}
static slice_ty
ast_for_slice(struct compiling *c, const node *n)
{
node *ch;
expr_ty lower = NULL, upper = NULL, step = NULL;
REQ(n, subscript);
/*
subscript: test | [test] ':' [test] [sliceop]
sliceop: ':' [test]
*/
ch = CHILD(n, 0);
if (NCH(n) == 1 && TYPE(ch) == test) {
/* 'step' variable hold no significance in terms of being used over
other vars */
step = ast_for_expr(c, ch);
if (!step)
return NULL;
return Index(step, c->c_arena);
}
if (TYPE(ch) == test) {
lower = ast_for_expr(c, ch);
if (!lower)
return NULL;
}
/* If there's an upper bound it's in the second or third position. */
if (TYPE(ch) == COLON) {
if (NCH(n) > 1) {
node *n2 = CHILD(n, 1);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
} else if (NCH(n) > 2) {
node *n2 = CHILD(n, 2);
if (TYPE(n2) == test) {
upper = ast_for_expr(c, n2);
if (!upper)
return NULL;
}
}
ch = CHILD(n, NCH(n) - 1);
if (TYPE(ch) == sliceop) {
if (NCH(ch) != 1) {
ch = CHILD(ch, 1);
if (TYPE(ch) == test) {
step = ast_for_expr(c, ch);
if (!step)
return NULL;
}
}
}
return Slice(lower, upper, step, c->c_arena);
}
static expr_ty
ast_for_binop(struct compiling *c, const node *n)
{
/* Must account for a sequence of expressions.
How should A op B op C by represented?
BinOp(BinOp(A, op, B), op, C).
*/
int i, nops;
expr_ty expr1, expr2, result;
operator_ty newoperator;
expr1 = ast_for_expr(c, CHILD(n, 0));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 2));
if (!expr2)
return NULL;
newoperator = get_operator(c, CHILD(n, 1));
if (!newoperator)
return NULL;
result = BinOp(expr1, newoperator, expr2, LINENO(n), n->n_col_offset,
c->c_arena);
if (!result)
return NULL;
nops = (NCH(n) - 1) / 2;
for (i = 1; i < nops; i++) {
expr_ty tmp_result, tmp;
const node* next_oper = CHILD(n, i * 2 + 1);
newoperator = get_operator(c, next_oper);
if (!newoperator)
return NULL;
tmp = ast_for_expr(c, CHILD(n, i * 2 + 2));
if (!tmp)
return NULL;
tmp_result = BinOp(result, newoperator, tmp,
LINENO(next_oper), next_oper->n_col_offset,
c->c_arena);
if (!tmp_result)
return NULL;
result = tmp_result;
}
return result;
}
static expr_ty
ast_for_trailer(struct compiling *c, const node *n, expr_ty left_expr)
{
/* trailer: '(' [arglist] ')' | '[' subscriptlist ']' | '.' NAME
subscriptlist: subscript (',' subscript)* [',']
subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop]
*/
REQ(n, trailer);
if (TYPE(CHILD(n, 0)) == LPAR) {
if (NCH(n) == 2)
return Call(left_expr, NULL, NULL, LINENO(n),
n->n_col_offset, c->c_arena);
else
return ast_for_call(c, CHILD(n, 1), left_expr, true);
}
else if (TYPE(CHILD(n, 0)) == DOT) {
PyObject *attr_id = NEW_IDENTIFIER(CHILD(n, 1));
if (!attr_id)
return NULL;
return Attribute(left_expr, attr_id, Load,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
REQ(CHILD(n, 0), LSQB);
REQ(CHILD(n, 2), RSQB);
n = CHILD(n, 1);
if (NCH(n) == 1) {
slice_ty slc = ast_for_slice(c, CHILD(n, 0));
if (!slc)
return NULL;
return Subscript(left_expr, slc, Load, LINENO(n), n->n_col_offset,
c->c_arena);
}
else {
/* The grammar is ambiguous here. The ambiguity is resolved
by treating the sequence as a tuple literal if there are
no slice features.
*/
int j;
slice_ty slc;
expr_ty e;
int simple = 1;
asdl_seq *slices, *elts;
slices = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!slices)
return NULL;
for (j = 0; j < NCH(n); j += 2) {
slc = ast_for_slice(c, CHILD(n, j));
if (!slc)
return NULL;
if (slc->kind != Index_kind)
simple = 0;
asdl_seq_SET(slices, j / 2, slc);
}
if (!simple) {
return Subscript(left_expr, ExtSlice(slices, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* extract Index values and put them in a Tuple */
elts = _Ta3_asdl_seq_new(asdl_seq_LEN(slices), c->c_arena);
if (!elts)
return NULL;
for (j = 0; j < asdl_seq_LEN(slices); ++j) {
slc = (slice_ty)asdl_seq_GET(slices, j);
assert(slc->kind == Index_kind && slc->v.Index.value);
asdl_seq_SET(elts, j, slc->v.Index.value);
}
e = Tuple(elts, Load, LINENO(n), n->n_col_offset, c->c_arena);
if (!e)
return NULL;
return Subscript(left_expr, Index(e, c->c_arena),
Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
}
static expr_ty
ast_for_factor(struct compiling *c, const node *n)
{
expr_ty expression;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
switch (TYPE(CHILD(n, 0))) {
case PLUS:
return UnaryOp(UAdd, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case MINUS:
return UnaryOp(USub, expression, LINENO(n), n->n_col_offset,
c->c_arena);
case TILDE:
return UnaryOp(Invert, expression, LINENO(n),
n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError, "unhandled factor: %d",
TYPE(CHILD(n, 0)));
return NULL;
}
static expr_ty
ast_for_atom_expr(struct compiling *c, const node *n)
{
int i, nch, start = 0;
expr_ty e, tmp;
REQ(n, atom_expr);
nch = NCH(n);
if (TYPE(CHILD(n, 0)) == AWAIT) {
if (c->c_feature_version < 5) {
ast_error(c, n,
"Await expressions are only supported in Python 3.5 and greater");
return NULL;
}
start = 1;
assert(nch > 1);
}
e = ast_for_atom(c, CHILD(n, start));
if (!e)
return NULL;
if (nch == 1)
return e;
if (start && nch == 2) {
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
for (i = start + 1; i < nch; i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) != trailer)
break;
tmp = ast_for_trailer(c, ch, e);
if (!tmp)
return NULL;
tmp->lineno = e->lineno;
tmp->col_offset = e->col_offset;
e = tmp;
}
if (start) {
/* there was an 'await' */
return Await(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else {
return e;
}
}
static expr_ty
ast_for_power(struct compiling *c, const node *n)
{
/* power: atom trailer* ('**' factor)*
*/
expr_ty e;
REQ(n, power);
e = ast_for_atom_expr(c, CHILD(n, 0));
if (!e)
return NULL;
if (NCH(n) == 1)
return e;
if (TYPE(CHILD(n, NCH(n) - 1)) == factor) {
expr_ty f = ast_for_expr(c, CHILD(n, NCH(n) - 1));
if (!f)
return NULL;
e = BinOp(e, Pow, f, LINENO(n), n->n_col_offset, c->c_arena);
}
return e;
}
static expr_ty
ast_for_starred(struct compiling *c, const node *n)
{
expr_ty tmp;
REQ(n, star_expr);
tmp = ast_for_expr(c, CHILD(n, 1));
if (!tmp)
return NULL;
/* The Load context is changed later. */
return Starred(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
/* Do not name a variable 'expr'! Will cause a compile error.
*/
static expr_ty
ast_for_expr(struct compiling *c, const node *n)
{
/* handle the full range of simple expressions
test: or_test ['if' or_test 'else' test] | lambdef
test_nocond: or_test | lambdef_nocond
or_test: and_test ('or' and_test)*
and_test: not_test ('and' not_test)*
not_test: 'not' not_test | comparison
comparison: expr (comp_op expr)*
expr: xor_expr ('|' xor_expr)*
xor_expr: and_expr ('^' and_expr)*
and_expr: shift_expr ('&' shift_expr)*
shift_expr: arith_expr (('<<'|'>>') arith_expr)*
arith_expr: term (('+'|'-') term)*
term: factor (('*'|'@'|'/'|'%'|'//') factor)*
factor: ('+'|'-'|'~') factor | power
power: atom_expr ['**' factor]
atom_expr: ['await'] atom trailer*
yield_expr: 'yield' [yield_arg]
*/
asdl_seq *seq;
int i;
loop:
switch (TYPE(n)) {
case test:
case test_nocond:
if (TYPE(CHILD(n, 0)) == lambdef ||
TYPE(CHILD(n, 0)) == lambdef_nocond)
return ast_for_lambdef(c, CHILD(n, 0));
else if (NCH(n) > 1)
return ast_for_ifexpr(c, n);
/* Fallthrough */
case or_test:
case and_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
expr_ty e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
}
if (!strcmp(STR(CHILD(n, 1)), "and"))
return BoolOp(And, seq, LINENO(n), n->n_col_offset,
c->c_arena);
assert(!strcmp(STR(CHILD(n, 1)), "or"));
return BoolOp(Or, seq, LINENO(n), n->n_col_offset, c->c_arena);
case not_test:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return UnaryOp(Not, expression, LINENO(n), n->n_col_offset,
c->c_arena);
}
case comparison:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
expr_ty expression;
asdl_int_seq *ops;
asdl_seq *cmps;
ops = _Ta3_asdl_int_seq_new(NCH(n) / 2, c->c_arena);
if (!ops)
return NULL;
cmps = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!cmps) {
return NULL;
}
for (i = 1; i < NCH(n); i += 2) {
cmpop_ty newoperator;
newoperator = ast_for_comp_op(c, CHILD(n, i));
if (!newoperator) {
return NULL;
}
expression = ast_for_expr(c, CHILD(n, i + 1));
if (!expression) {
return NULL;
}
asdl_seq_SET(ops, i / 2, newoperator);
asdl_seq_SET(cmps, i / 2, expression);
}
expression = ast_for_expr(c, CHILD(n, 0));
if (!expression) {
return NULL;
}
return Compare(expression, ops, cmps, LINENO(n),
n->n_col_offset, c->c_arena);
}
break;
case star_expr:
return ast_for_starred(c, n);
/* The next five cases all handle BinOps. The main body of code
is the same in each case, but the switch turned inside out to
reuse the code for each type of operator.
*/
case expr:
case xor_expr:
case and_expr:
case shift_expr:
case arith_expr:
case term:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_binop(c, n);
case yield_expr: {
node *an = NULL;
node *en = NULL;
int is_from = 0;
expr_ty exp = NULL;
if (NCH(n) > 1)
an = CHILD(n, 1); /* yield_arg */
if (an) {
en = CHILD(an, NCH(an) - 1);
if (NCH(an) == 2) {
is_from = 1;
exp = ast_for_expr(c, en);
}
else
exp = ast_for_testlist(c, en);
if (!exp)
return NULL;
}
if (is_from)
return YieldFrom(exp, LINENO(n), n->n_col_offset, c->c_arena);
return Yield(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case factor:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
return ast_for_factor(c, n);
case power:
return ast_for_power(c, n);
default:
PyErr_Format(PyExc_SystemError, "unhandled expr: %d", TYPE(n));
return NULL;
}
/* should never get here unless if error is set */
return NULL;
}
static expr_ty
ast_for_call(struct compiling *c, const node *n, expr_ty func, bool allowgen)
{
/*
arglist: argument (',' argument)* [',']
argument: ( test [comp_for] | '*' test | test '=' test | '**' test )
*/
int i, nargs, nkeywords;
int ndoublestars;
asdl_seq *args;
asdl_seq *keywords;
REQ(n, arglist);
nargs = 0;
nkeywords = 0;
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
if (NCH(ch) == 1)
nargs++;
else if (TYPE(CHILD(ch, 1)) == comp_for) {
nargs++;
if (!allowgen) {
ast_error(c, ch, "invalid syntax");
return NULL;
}
if (NCH(n) > 1) {
ast_error(c, ch, "Generator expression must be parenthesized");
return NULL;
}
}
else if (TYPE(CHILD(ch, 0)) == STAR)
nargs++;
else
/* TYPE(CHILD(ch, 0)) == DOUBLESTAR or keyword argument */
nkeywords++;
}
}
args = _Ta3_asdl_seq_new(nargs, c->c_arena);
if (!args)
return NULL;
keywords = _Ta3_asdl_seq_new(nkeywords, c->c_arena);
if (!keywords)
return NULL;
nargs = 0; /* positional arguments + iterable argument unpackings */
nkeywords = 0; /* keyword arguments + keyword argument unpackings */
ndoublestars = 0; /* just keyword argument unpackings */
for (i = 0; i < NCH(n); i++) {
node *ch = CHILD(n, i);
if (TYPE(ch) == argument) {
expr_ty e;
node *chch = CHILD(ch, 0);
if (NCH(ch) == 1) {
/* a positional argument */
if (nkeywords) {
if (ndoublestars) {
ast_error(c, chch,
"positional argument follows "
"keyword argument unpacking");
}
else {
ast_error(c, chch,
"positional argument follows "
"keyword argument");
}
return NULL;
}
e = ast_for_expr(c, chch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else if (TYPE(chch) == STAR) {
/* an iterable argument unpacking */
expr_ty starred;
if (ndoublestars) {
ast_error(c, chch,
"iterable argument unpacking follows "
"keyword argument unpacking");
return NULL;
}
e = ast_for_expr(c, CHILD(ch, 1));
if (!e)
return NULL;
starred = Starred(e, Load, LINENO(chch),
chch->n_col_offset,
c->c_arena);
if (!starred)
return NULL;
asdl_seq_SET(args, nargs++, starred);
}
else if (TYPE(chch) == DOUBLESTAR) {
/* a keyword argument unpacking */
keyword_ty kw;
i++;
e = ast_for_expr(c, CHILD(ch, 1));
if (!e)
return NULL;
kw = keyword(NULL, e, c->c_arena);
asdl_seq_SET(keywords, nkeywords++, kw);
ndoublestars++;
}
else if (TYPE(CHILD(ch, 1)) == comp_for) {
/* the lone generator expression */
e = ast_for_genexp(c, ch);
if (!e)
return NULL;
asdl_seq_SET(args, nargs++, e);
}
else {
/* a keyword argument */
keyword_ty kw;
identifier key, tmp;
int k;
/* chch is test, but must be an identifier? */
e = ast_for_expr(c, chch);
if (!e)
return NULL;
/* f(lambda x: x[0] = 3) ends up getting parsed with
* LHS test = lambda x: x[0], and RHS test = 3.
* SF bug 132313 points out that complaining about a keyword
* then is very confusing.
*/
if (e->kind == Lambda_kind) {
ast_error(c, chch,
"lambda cannot contain assignment");
return NULL;
}
else if (e->kind != Name_kind) {
ast_error(c, chch,
"keyword can't be an expression");
return NULL;
}
else if (forbidden_name(c, e->v.Name.id, ch, 1)) {
return NULL;
}
key = e->v.Name.id;
for (k = 0; k < nkeywords; k++) {
tmp = ((keyword_ty)asdl_seq_GET(keywords, k))->arg;
if (tmp && !PyUnicode_Compare(tmp, key)) {
ast_error(c, chch,
"keyword argument repeated");
return NULL;
}
}
e = ast_for_expr(c, CHILD(ch, 2));
if (!e)
return NULL;
kw = keyword(key, e, c->c_arena);
if (!kw)
return NULL;
asdl_seq_SET(keywords, nkeywords++, kw);
}
}
}
return Call(func, args, keywords, func->lineno, func->col_offset, c->c_arena);
}
static expr_ty
ast_for_testlist(struct compiling *c, const node* n)
{
/* testlist_comp: test (comp_for | (',' test)* [',']) */
/* testlist: test (',' test)* [','] */
assert(NCH(n) > 0);
if (TYPE(n) == testlist_comp) {
if (NCH(n) > 1)
assert(TYPE(CHILD(n, 1)) != comp_for);
}
else {
assert(TYPE(n) == testlist ||
TYPE(n) == testlist_star_expr);
}
if (NCH(n) == 1)
return ast_for_expr(c, CHILD(n, 0));
else {
asdl_seq *tmp = seq_for_testlist(c, n);
if (!tmp)
return NULL;
return Tuple(tmp, Load, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static stmt_ty
ast_for_expr_stmt(struct compiling *c, const node *n)
{
int num;
REQ(n, expr_stmt);
/* expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))* [TYPE_COMMENT])
annassign: ':' test ['=' test]
testlist_star_expr: (test|star_expr) (',' test|star_expr)* [',']
augassign: '+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^='
| '<<=' | '>>=' | '**=' | '//='
test: ... here starts the operator precedence dance
*/
num = NCH(n);
if (num == 1 || (num == 2 && TYPE(CHILD(n, 1)) == TYPE_COMMENT)) {
expr_ty e = ast_for_testlist(c, CHILD(n, 0));
if (!e)
return NULL;
return Expr(e, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == augassign) {
expr_ty expr1, expr2;
operator_ty newoperator;
node *ch = CHILD(n, 0);
expr1 = ast_for_testlist(c, ch);
if (!expr1)
return NULL;
if(!set_context(c, expr1, Store, ch))
return NULL;
/* set_context checks that most expressions are not the left side.
Augmented assignments can only have a name, a subscript, or an
attribute on the left, though, so we have to explicitly check for
those. */
switch (expr1->kind) {
case Name_kind:
case Attribute_kind:
case Subscript_kind:
break;
default:
ast_error(c, ch, "illegal expression for augmented assignment");
return NULL;
}
ch = CHILD(n, 2);
if (TYPE(ch) == testlist)
expr2 = ast_for_testlist(c, ch);
else
expr2 = ast_for_expr(c, ch);
if (!expr2)
return NULL;
newoperator = ast_for_augassign(c, CHILD(n, 1));
if (!newoperator)
return NULL;
return AugAssign(expr1, newoperator, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (TYPE(CHILD(n, 1)) == annassign) {
expr_ty expr1, expr2, expr3;
node *ch = CHILD(n, 0);
node *deep, *ann = CHILD(n, 1);
int simple = 1;
/* AnnAssigns are only allowed in Python 3.6 or greater */
if (c->c_feature_version < 6) {
ast_error(c, ch,
"Variable annotation syntax is only supported in Python 3.6 and greater");
return NULL;
}
/* we keep track of parens to qualify (x) as expression not name */
deep = ch;
while (NCH(deep) == 1) {
deep = CHILD(deep, 0);
}
if (NCH(deep) > 0 && TYPE(CHILD(deep, 0)) == LPAR) {
simple = 0;
}
expr1 = ast_for_testlist(c, ch);
if (!expr1) {
return NULL;
}
switch (expr1->kind) {
case Name_kind:
if (forbidden_name(c, expr1->v.Name.id, n, 0)) {
return NULL;
}
expr1->v.Name.ctx = Store;
break;
case Attribute_kind:
if (forbidden_name(c, expr1->v.Attribute.attr, n, 1)) {
return NULL;
}
expr1->v.Attribute.ctx = Store;
break;
case Subscript_kind:
expr1->v.Subscript.ctx = Store;
break;
case List_kind:
ast_error(c, ch,
"only single target (not list) can be annotated");
return NULL;
case Tuple_kind:
ast_error(c, ch,
"only single target (not tuple) can be annotated");
return NULL;
default:
ast_error(c, ch,
"illegal target for annotation");
return NULL;
}
if (expr1->kind != Name_kind) {
simple = 0;
}
ch = CHILD(ann, 1);
expr2 = ast_for_expr(c, ch);
if (!expr2) {
return NULL;
}
if (NCH(ann) == 2) {
return AnnAssign(expr1, expr2, NULL, simple,
LINENO(n), n->n_col_offset, c->c_arena);
}
else {
ch = CHILD(ann, 3);
expr3 = ast_for_expr(c, ch);
if (!expr3) {
return NULL;
}
return AnnAssign(expr1, expr2, expr3, simple,
LINENO(n), n->n_col_offset, c->c_arena);
}
}
else {
int i, nch_minus_type, has_type_comment;
asdl_seq *targets;
node *value;
expr_ty expression;
string type_comment;
/* a normal assignment */
REQ(CHILD(n, 1), EQUAL);
has_type_comment = TYPE(CHILD(n, num - 1)) == TYPE_COMMENT;
nch_minus_type = num - has_type_comment;
targets = _Ta3_asdl_seq_new(nch_minus_type / 2, c->c_arena);
if (!targets)
return NULL;
for (i = 0; i < nch_minus_type - 2; i += 2) {
expr_ty e;
node *ch = CHILD(n, i);
if (TYPE(ch) == yield_expr) {
ast_error(c, ch, "assignment to yield expression not possible");
return NULL;
}
e = ast_for_testlist(c, ch);
if (!e)
return NULL;
/* set context to assign */
if (!set_context(c, e, Store, CHILD(n, i)))
return NULL;
asdl_seq_SET(targets, i / 2, e);
}
value = CHILD(n, nch_minus_type - 1);
if (TYPE(value) == testlist_star_expr)
expression = ast_for_testlist(c, value);
else
expression = ast_for_expr(c, value);
if (!expression)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, nch_minus_type));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
return Assign(targets, expression, type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
}
static asdl_seq *
ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
{
asdl_seq *seq;
int i;
expr_ty e;
REQ(n, exprlist);
seq = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!seq)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
e = ast_for_expr(c, CHILD(n, i));
if (!e)
return NULL;
asdl_seq_SET(seq, i / 2, e);
if (context && !set_context(c, e, context, CHILD(n, i)))
return NULL;
}
return seq;
}
static stmt_ty
ast_for_del_stmt(struct compiling *c, const node *n)
{
asdl_seq *expr_list;
/* del_stmt: 'del' exprlist */
REQ(n, del_stmt);
expr_list = ast_for_exprlist(c, CHILD(n, 1), Del);
if (!expr_list)
return NULL;
return Delete(expr_list, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_flow_stmt(struct compiling *c, const node *n)
{
/*
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
| yield_stmt
break_stmt: 'break'
continue_stmt: 'continue'
return_stmt: 'return' [testlist]
yield_stmt: yield_expr
yield_expr: 'yield' testlist | 'yield' 'from' test
raise_stmt: 'raise' [test [',' test [',' test]]]
*/
node *ch;
REQ(n, flow_stmt);
ch = CHILD(n, 0);
switch (TYPE(ch)) {
case break_stmt:
return Break(LINENO(n), n->n_col_offset, c->c_arena);
case continue_stmt:
return Continue(LINENO(n), n->n_col_offset, c->c_arena);
case yield_stmt: { /* will reduce to yield_expr */
expr_ty exp = ast_for_expr(c, CHILD(ch, 0));
if (!exp)
return NULL;
return Expr(exp, LINENO(n), n->n_col_offset, c->c_arena);
}
case return_stmt:
if (NCH(ch) == 1)
return Return(NULL, LINENO(n), n->n_col_offset, c->c_arena);
else {
expr_ty expression = ast_for_testlist(c, CHILD(ch, 1));
if (!expression)
return NULL;
return Return(expression, LINENO(n), n->n_col_offset, c->c_arena);
}
case raise_stmt:
if (NCH(ch) == 1)
return Raise(NULL, NULL, LINENO(n), n->n_col_offset, c->c_arena);
else if (NCH(ch) >= 2) {
expr_ty cause = NULL;
expr_ty expression = ast_for_expr(c, CHILD(ch, 1));
if (!expression)
return NULL;
if (NCH(ch) == 4) {
cause = ast_for_expr(c, CHILD(ch, 3));
if (!cause)
return NULL;
}
return Raise(expression, cause, LINENO(n), n->n_col_offset, c->c_arena);
}
/* fall through */
default:
PyErr_Format(PyExc_SystemError,
"unexpected flow_stmt: %d", TYPE(ch));
return NULL;
}
}
static alias_ty
alias_for_import_name(struct compiling *c, const node *n, int store)
{
/*
import_as_name: NAME ['as' NAME]
dotted_as_name: dotted_name ['as' NAME]
dotted_name: NAME ('.' NAME)*
*/
identifier str, name;
loop:
switch (TYPE(n)) {
case import_as_name: {
node *name_node = CHILD(n, 0);
str = NULL;
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
if (NCH(n) == 3) {
node *str_node = CHILD(n, 2);
str = NEW_IDENTIFIER(str_node);
if (!str)
return NULL;
if (store && forbidden_name(c, str, str_node, 0))
return NULL;
}
else {
if (forbidden_name(c, name, name_node, 0))
return NULL;
}
return alias(name, str, c->c_arena);
}
case dotted_as_name:
if (NCH(n) == 1) {
n = CHILD(n, 0);
goto loop;
}
else {
node *asname_node = CHILD(n, 2);
alias_ty a = alias_for_import_name(c, CHILD(n, 0), 0);
if (!a)
return NULL;
assert(!a->asname);
a->asname = NEW_IDENTIFIER(asname_node);
if (!a->asname)
return NULL;
if (forbidden_name(c, a->asname, asname_node, 0))
return NULL;
return a;
}
break;
case dotted_name:
if (NCH(n) == 1) {
node *name_node = CHILD(n, 0);
name = NEW_IDENTIFIER(name_node);
if (!name)
return NULL;
if (store && forbidden_name(c, name, name_node, 0))
return NULL;
return alias(name, NULL, c->c_arena);
}
else {
/* Create a string of the form "a.b.c" */
int i;
size_t len;
char *s;
PyObject *uni;
len = 0;
for (i = 0; i < NCH(n); i += 2)
/* length of string plus one for the dot */
len += strlen(STR(CHILD(n, i))) + 1;
len--; /* the last name doesn't have a dot */
str = PyBytes_FromStringAndSize(NULL, len);
if (!str)
return NULL;
s = PyBytes_AS_STRING(str);
if (!s)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
char *sch = STR(CHILD(n, i));
strcpy(s, STR(CHILD(n, i)));
s += strlen(sch);
*s++ = '.';
}
--s;
*s = '\0';
uni = PyUnicode_DecodeUTF8(PyBytes_AS_STRING(str),
PyBytes_GET_SIZE(str),
NULL);
Py_DECREF(str);
if (!uni)
return NULL;
str = uni;
PyUnicode_InternInPlace(&str);
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
}
break;
case STAR:
str = PyUnicode_InternFromString("*");
if (!str)
return NULL;
if (PyArena_AddPyObject(c->c_arena, str) < 0) {
Py_DECREF(str);
return NULL;
}
return alias(str, NULL, c->c_arena);
default:
PyErr_Format(PyExc_SystemError,
"unexpected import name: %d", TYPE(n));
return NULL;
}
PyErr_SetString(PyExc_SystemError, "unhandled import name condition");
return NULL;
}
static stmt_ty
ast_for_import_stmt(struct compiling *c, const node *n)
{
/*
import_stmt: import_name | import_from
import_name: 'import' dotted_as_names
import_from: 'from' (('.' | '...')* dotted_name | ('.' | '...')+)
'import' ('*' | '(' import_as_names ')' | import_as_names)
*/
int lineno;
int col_offset;
int i;
asdl_seq *aliases;
REQ(n, import_stmt);
lineno = LINENO(n);
col_offset = n->n_col_offset;
n = CHILD(n, 0);
if (TYPE(n) == import_name) {
n = CHILD(n, 1);
REQ(n, dotted_as_names);
aliases = _Ta3_asdl_seq_new((NCH(n) + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
return Import(aliases, lineno, col_offset, c->c_arena);
}
else if (TYPE(n) == import_from) {
int n_children;
int idx, ndots = 0;
alias_ty mod = NULL;
identifier modname = NULL;
/* Count the number of dots (for relative imports) and check for the
optional module name */
for (idx = 1; idx < NCH(n); idx++) {
if (TYPE(CHILD(n, idx)) == dotted_name) {
mod = alias_for_import_name(c, CHILD(n, idx), 0);
if (!mod)
return NULL;
idx++;
break;
} else if (TYPE(CHILD(n, idx)) == ELLIPSIS) {
/* three consecutive dots are tokenized as one ELLIPSIS */
ndots += 3;
continue;
} else if (TYPE(CHILD(n, idx)) != DOT) {
break;
}
ndots++;
}
idx++; /* skip over the 'import' keyword */
switch (TYPE(CHILD(n, idx))) {
case STAR:
/* from ... import * */
n = CHILD(n, idx);
n_children = 1;
break;
case LPAR:
/* from ... import (x, y, z) */
n = CHILD(n, idx + 1);
n_children = NCH(n);
break;
case import_as_names:
/* from ... import x, y, z */
n = CHILD(n, idx);
n_children = NCH(n);
if (n_children % 2 == 0) {
ast_error(c, n, "trailing comma not allowed without"
" surrounding parentheses");
return NULL;
}
break;
default:
ast_error(c, n, "Unexpected node-type in from-import");
return NULL;
}
aliases = _Ta3_asdl_seq_new((n_children + 1) / 2, c->c_arena);
if (!aliases)
return NULL;
/* handle "from ... import *" special b/c there's no children */
if (TYPE(n) == STAR) {
alias_ty import_alias = alias_for_import_name(c, n, 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, 0, import_alias);
}
else {
for (i = 0; i < NCH(n); i += 2) {
alias_ty import_alias = alias_for_import_name(c, CHILD(n, i), 1);
if (!import_alias)
return NULL;
asdl_seq_SET(aliases, i / 2, import_alias);
}
}
if (mod != NULL)
modname = mod->name;
return ImportFrom(modname, aliases, ndots, lineno, col_offset,
c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unknown import statement: starts with command '%s'",
STR(CHILD(n, 0)));
return NULL;
}
static stmt_ty
ast_for_global_stmt(struct compiling *c, const node *n)
{
/* global_stmt: 'global' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, global_stmt);
s = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Global(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_nonlocal_stmt(struct compiling *c, const node *n)
{
/* nonlocal_stmt: 'nonlocal' NAME (',' NAME)* */
identifier name;
asdl_seq *s;
int i;
REQ(n, nonlocal_stmt);
s = _Ta3_asdl_seq_new(NCH(n) / 2, c->c_arena);
if (!s)
return NULL;
for (i = 1; i < NCH(n); i += 2) {
name = NEW_IDENTIFIER(CHILD(n, i));
if (!name)
return NULL;
asdl_seq_SET(s, i / 2, name);
}
return Nonlocal(s, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_assert_stmt(struct compiling *c, const node *n)
{
/* assert_stmt: 'assert' test [',' test] */
REQ(n, assert_stmt);
if (NCH(n) == 2) {
expr_ty expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
return Assert(expression, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (NCH(n) == 4) {
expr_ty expr1, expr2;
expr1 = ast_for_expr(c, CHILD(n, 1));
if (!expr1)
return NULL;
expr2 = ast_for_expr(c, CHILD(n, 3));
if (!expr2)
return NULL;
return Assert(expr1, expr2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"improper number of parts to 'assert' statement: %d",
NCH(n));
return NULL;
}
static asdl_seq *
ast_for_suite(struct compiling *c, const node *n)
{
/* suite: simple_stmt | NEWLINE [TYPE_COMMENT NEWLINE] INDENT stmt+ DEDENT */
asdl_seq *seq;
stmt_ty s;
int i, total, num, end, pos = 0;
node *ch;
REQ(n, suite);
total = num_stmts(n);
seq = _Ta3_asdl_seq_new(total, c->c_arena);
if (!seq)
return NULL;
if (TYPE(CHILD(n, 0)) == simple_stmt) {
n = CHILD(n, 0);
/* simple_stmt always ends with a NEWLINE,
and may have a trailing SEMI
*/
end = NCH(n) - 1;
if (TYPE(CHILD(n, end - 1)) == SEMI)
end--;
/* loop by 2 to skip semi-colons */
for (i = 0; i < end; i += 2) {
ch = CHILD(n, i);
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
else {
i = 2;
if (TYPE(CHILD(n, 1)) == TYPE_COMMENT)
i += 2;
for (; i < (NCH(n) - 1); i++) {
ch = CHILD(n, i);
REQ(ch, stmt);
num = num_stmts(ch);
if (num == 1) {
/* small_stmt or compound_stmt with only one child */
s = ast_for_stmt(c, ch);
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
else {
int j;
ch = CHILD(ch, 0);
REQ(ch, simple_stmt);
for (j = 0; j < NCH(ch); j += 2) {
/* statement terminates with a semi-colon ';' */
if (NCH(CHILD(ch, j)) == 0) {
assert((j + 1) == NCH(ch));
break;
}
s = ast_for_stmt(c, CHILD(ch, j));
if (!s)
return NULL;
asdl_seq_SET(seq, pos++, s);
}
}
}
}
assert(pos == seq->size);
return seq;
}
static stmt_ty
ast_for_if_stmt(struct compiling *c, const node *n)
{
/* if_stmt: 'if' test ':' suite ('elif' test ':' suite)*
['else' ':' suite]
*/
char *s;
REQ(n, if_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, NULL, LINENO(n), n->n_col_offset,
c->c_arena);
}
s = STR(CHILD(n, 4));
/* s[2], the third character in the string, will be
's' for el_s_e, or
'i' for el_i_f
*/
if (s[2] == 's') {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return If(expression, seq1, seq2, LINENO(n), n->n_col_offset,
c->c_arena);
}
else if (s[2] == 'i') {
int i, n_elif, has_else = 0;
expr_ty expression;
asdl_seq *suite_seq;
asdl_seq *orelse = NULL;
n_elif = NCH(n) - 4;
/* must reference the child n_elif+1 since 'else' token is third,
not fourth, child from the end. */
if (TYPE(CHILD(n, (n_elif + 1))) == NAME
&& STR(CHILD(n, (n_elif + 1)))[2] == 's') {
has_else = 1;
n_elif -= 3;
}
n_elif /= 4;
if (has_else) {
asdl_seq *suite_seq2;
orelse = _Ta3_asdl_seq_new(1, c->c_arena);
if (!orelse)
return NULL;
expression = ast_for_expr(c, CHILD(n, NCH(n) - 6));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, NCH(n) - 4));
if (!suite_seq)
return NULL;
suite_seq2 = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!suite_seq2)
return NULL;
asdl_seq_SET(orelse, 0,
If(expression, suite_seq, suite_seq2,
LINENO(CHILD(n, NCH(n) - 6)),
CHILD(n, NCH(n) - 6)->n_col_offset,
c->c_arena));
/* the just-created orelse handled the last elif */
n_elif--;
}
for (i = 0; i < n_elif; i++) {
int off = 5 + (n_elif - i - 1) * 4;
asdl_seq *newobj = _Ta3_asdl_seq_new(1, c->c_arena);
if (!newobj)
return NULL;
expression = ast_for_expr(c, CHILD(n, off));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, off + 2));
if (!suite_seq)
return NULL;
asdl_seq_SET(newobj, 0,
If(expression, suite_seq, orelse,
LINENO(CHILD(n, off)),
CHILD(n, off)->n_col_offset, c->c_arena));
orelse = newobj;
}
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return If(expression, suite_seq, orelse,
LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"unexpected token in 'if' statement: %s", s);
return NULL;
}
static stmt_ty
ast_for_while_stmt(struct compiling *c, const node *n)
{
/* while_stmt: 'while' test ':' suite ['else' ':' suite] */
REQ(n, while_stmt);
if (NCH(n) == 4) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 3));
if (!suite_seq)
return NULL;
return While(expression, suite_seq, NULL, LINENO(n), n->n_col_offset, c->c_arena);
}
else if (NCH(n) == 7) {
expr_ty expression;
asdl_seq *seq1, *seq2;
expression = ast_for_expr(c, CHILD(n, 1));
if (!expression)
return NULL;
seq1 = ast_for_suite(c, CHILD(n, 3));
if (!seq1)
return NULL;
seq2 = ast_for_suite(c, CHILD(n, 6));
if (!seq2)
return NULL;
return While(expression, seq1, seq2, LINENO(n), n->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of tokens for 'while' statement: %d",
NCH(n));
return NULL;
}
static stmt_ty
ast_for_for_stmt(struct compiling *c, const node *n0, bool is_async)
{
const node * const n = is_async ? CHILD(n0, 1) : n0;
asdl_seq *_target, *seq = NULL, *suite_seq;
expr_ty expression;
expr_ty target, first;
const node *node_target;
int has_type_comment;
string type_comment;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async for loops are only supported in Python 3.5 and greater");
return NULL;
}
/* for_stmt: 'for' exprlist 'in' testlist ':' [TYPE_COMMENT] suite ['else' ':' suite] */
REQ(n, for_stmt);
has_type_comment = TYPE(CHILD(n, 5)) == TYPE_COMMENT;
if (NCH(n) == 9 + has_type_comment) {
seq = ast_for_suite(c, CHILD(n, 8 + has_type_comment));
if (!seq)
return NULL;
}
node_target = CHILD(n, 1);
_target = ast_for_exprlist(c, node_target, Store);
if (!_target)
return NULL;
/* Check the # of children rather than the length of _target, since
for x, in ... has 1 element in _target, but still requires a Tuple. */
first = (expr_ty)asdl_seq_GET(_target, 0);
if (NCH(node_target) == 1)
target = first;
else
target = Tuple(_target, Store, first->lineno, first->col_offset, c->c_arena);
expression = ast_for_testlist(c, CHILD(n, 3));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, CHILD(n, 5 + has_type_comment));
if (!suite_seq)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, 5));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
if (is_async)
return AsyncFor(target, expression, suite_seq, seq, type_comment,
LINENO(n0), n0->n_col_offset,
c->c_arena);
else
return For(target, expression, suite_seq, seq, type_comment,
LINENO(n), n->n_col_offset,
c->c_arena);
}
static excepthandler_ty
ast_for_except_clause(struct compiling *c, const node *exc, node *body)
{
/* except_clause: 'except' [test ['as' test]] */
REQ(exc, except_clause);
REQ(body, suite);
if (NCH(exc) == 1) {
asdl_seq *suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(NULL, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 2) {
expr_ty expression;
asdl_seq *suite_seq;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, NULL, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
else if (NCH(exc) == 4) {
asdl_seq *suite_seq;
expr_ty expression;
identifier e = NEW_IDENTIFIER(CHILD(exc, 3));
if (!e)
return NULL;
if (forbidden_name(c, e, CHILD(exc, 3), 0))
return NULL;
expression = ast_for_expr(c, CHILD(exc, 1));
if (!expression)
return NULL;
suite_seq = ast_for_suite(c, body);
if (!suite_seq)
return NULL;
return ExceptHandler(expression, e, suite_seq, LINENO(exc),
exc->n_col_offset, c->c_arena);
}
PyErr_Format(PyExc_SystemError,
"wrong number of children for 'except' clause: %d",
NCH(exc));
return NULL;
}
static stmt_ty
ast_for_try_stmt(struct compiling *c, const node *n)
{
const int nch = NCH(n);
int n_except = (nch - 3)/3;
asdl_seq *body, *handlers = NULL, *orelse = NULL, *finally = NULL;
REQ(n, try_stmt);
body = ast_for_suite(c, CHILD(n, 2));
if (body == NULL)
return NULL;
if (TYPE(CHILD(n, nch - 3)) == NAME) {
if (strcmp(STR(CHILD(n, nch - 3)), "finally") == 0) {
if (nch >= 9 && TYPE(CHILD(n, nch - 6)) == NAME) {
/* we can assume it's an "else",
because nch >= 9 for try-else-finally and
it would otherwise have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 4));
if (orelse == NULL)
return NULL;
n_except--;
}
finally = ast_for_suite(c, CHILD(n, nch - 1));
if (finally == NULL)
return NULL;
n_except--;
}
else {
/* we can assume it's an "else",
otherwise it would have a type of except_clause */
orelse = ast_for_suite(c, CHILD(n, nch - 1));
if (orelse == NULL)
return NULL;
n_except--;
}
}
else if (TYPE(CHILD(n, nch - 3)) != except_clause) {
ast_error(c, n, "malformed 'try' statement");
return NULL;
}
if (n_except > 0) {
int i;
/* process except statements to create a try ... except */
handlers = _Ta3_asdl_seq_new(n_except, c->c_arena);
if (handlers == NULL)
return NULL;
for (i = 0; i < n_except; i++) {
excepthandler_ty e = ast_for_except_clause(c, CHILD(n, 3 + i * 3),
CHILD(n, 5 + i * 3));
if (!e)
return NULL;
asdl_seq_SET(handlers, i, e);
}
}
assert(finally != NULL || asdl_seq_LEN(handlers));
return Try(body, handlers, orelse, finally, LINENO(n), n->n_col_offset, c->c_arena);
}
/* with_item: test ['as' expr] */
static withitem_ty
ast_for_with_item(struct compiling *c, const node *n)
{
expr_ty context_expr, optional_vars = NULL;
REQ(n, with_item);
context_expr = ast_for_expr(c, CHILD(n, 0));
if (!context_expr)
return NULL;
if (NCH(n) == 3) {
optional_vars = ast_for_expr(c, CHILD(n, 2));
if (!optional_vars) {
return NULL;
}
if (!set_context(c, optional_vars, Store, n)) {
return NULL;
}
}
return withitem(context_expr, optional_vars, c->c_arena);
}
/* with_stmt: 'with' with_item (',' with_item)* ':' [TYPE_COMMENT] suite */
static stmt_ty
ast_for_with_stmt(struct compiling *c, const node *n0, bool is_async)
{
const node * const n = is_async ? CHILD(n0, 1) : n0;
int i, n_items, nch_minus_type, has_type_comment;
asdl_seq *items, *body;
string type_comment;
if (is_async && c->c_feature_version < 5) {
ast_error(c, n,
"Async with statements are only supported in Python 3.5 and greater");
return NULL;
}
REQ(n, with_stmt);
has_type_comment = TYPE(CHILD(n, NCH(n) - 2)) == TYPE_COMMENT;
nch_minus_type = NCH(n) - has_type_comment;
n_items = (nch_minus_type - 2) / 2;
items = _Ta3_asdl_seq_new(n_items, c->c_arena);
if (!items)
return NULL;
for (i = 1; i < nch_minus_type - 2; i += 2) {
withitem_ty item = ast_for_with_item(c, CHILD(n, i));
if (!item)
return NULL;
asdl_seq_SET(items, (i - 1) / 2, item);
}
body = ast_for_suite(c, CHILD(n, NCH(n) - 1));
if (!body)
return NULL;
if (has_type_comment) {
type_comment = NEW_TYPE_COMMENT(CHILD(n, NCH(n) - 2));
if (!type_comment)
return NULL;
}
else
type_comment = NULL;
if (is_async)
return AsyncWith(items, body, type_comment, LINENO(n0), n0->n_col_offset, c->c_arena);
else
return With(items, body, type_comment, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* classdef: 'class' NAME ['(' arglist ')'] ':' suite */
PyObject *classname;
asdl_seq *s;
expr_ty call;
REQ(n, classdef);
if (NCH(n) == 4) { /* class NAME ':' suite */
s = ast_for_suite(c, CHILD(n, 3));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 3), 0))
return NULL;
return ClassDef(classname, NULL, NULL, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */
s = ast_for_suite(c, CHILD(n, 5));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 3), 0))
return NULL;
return ClassDef(classname, NULL, NULL, s, decorator_seq,
LINENO(n), n->n_col_offset, c->c_arena);
}
/* class NAME '(' arglist ')' ':' suite */
/* build up a fake Call node so we can extract its pieces */
{
PyObject *dummy_name;
expr_ty dummy;
dummy_name = NEW_IDENTIFIER(CHILD(n, 1));
if (!dummy_name)
return NULL;
dummy = Name(dummy_name, Load, LINENO(n), n->n_col_offset, c->c_arena);
call = ast_for_call(c, CHILD(n, 3), dummy, false);
if (!call)
return NULL;
}
s = ast_for_suite(c, CHILD(n, 6));
if (!s)
return NULL;
classname = NEW_IDENTIFIER(CHILD(n, 1));
if (!classname)
return NULL;
if (forbidden_name(c, classname, CHILD(n, 1), 0))
return NULL;
return ClassDef(classname, call->v.Call.args, call->v.Call.keywords, s,
decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_stmt(struct compiling *c, const node *n)
{
if (TYPE(n) == stmt) {
assert(NCH(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == simple_stmt) {
assert(num_stmts(n) == 1);
n = CHILD(n, 0);
}
if (TYPE(n) == small_stmt) {
n = CHILD(n, 0);
/* small_stmt: expr_stmt | del_stmt | pass_stmt | flow_stmt
| import_stmt | global_stmt | nonlocal_stmt | assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
return ast_for_expr_stmt(c, n);
case del_stmt:
return ast_for_del_stmt(c, n);
case pass_stmt:
return Pass(LINENO(n), n->n_col_offset, c->c_arena);
case flow_stmt:
return ast_for_flow_stmt(c, n);
case import_stmt:
return ast_for_import_stmt(c, n);
case global_stmt:
return ast_for_global_stmt(c, n);
case nonlocal_stmt:
return ast_for_nonlocal_stmt(c, n);
case assert_stmt:
return ast_for_assert_stmt(c, n);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
else {
/* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
| funcdef | classdef | decorated | async_stmt
*/
node *ch = CHILD(n, 0);
REQ(n, compound_stmt);
switch (TYPE(ch)) {
case if_stmt:
return ast_for_if_stmt(c, ch);
case while_stmt:
return ast_for_while_stmt(c, ch);
case for_stmt:
return ast_for_for_stmt(c, ch, 0);
case try_stmt:
return ast_for_try_stmt(c, ch);
case with_stmt:
return ast_for_with_stmt(c, ch, 0);
case funcdef:
return ast_for_funcdef(c, ch, NULL);
case classdef:
return ast_for_classdef(c, ch, NULL);
case decorated:
return ast_for_decorated(c, ch);
case async_stmt:
return ast_for_async_stmt(c, ch);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",
TYPE(n), NCH(n));
return NULL;
}
}
}
static PyObject *
parsenumber_raw(struct compiling *c, const char *s)
{
const char *end;
long x;
double dx;
Py_complex compl;
int imflag;
assert(s != NULL);
errno = 0;
end = s + strlen(s) - 1;
imflag = *end == 'j' || *end == 'J';
if (s[0] == '0') {
x = (long) PyOS_strtoul(s, (char **)&end, 0);
if (x < 0 && errno == 0) {
return PyLong_FromString(s, (char **)0, 0);
}
}
else
x = PyOS_strtol(s, (char **)&end, 0);
if (*end == '\0') {
if (errno != 0)
return PyLong_FromString(s, (char **)0, 0);
return PyLong_FromLong(x);
}
/* XXX Huge floats may silently fail */
if (imflag) {
compl.real = 0.;
compl.imag = PyOS_string_to_double(s, (char **)&end, NULL);
if (compl.imag == -1.0 && PyErr_Occurred())
return NULL;
return PyComplex_FromCComplex(compl);
}
else
{
dx = PyOS_string_to_double(s, NULL, NULL);
if (dx == -1.0 && PyErr_Occurred())
return NULL;
return PyFloat_FromDouble(dx);
}
}
static PyObject *
parsenumber(struct compiling *c, const char *s)
{
char *dup, *end;
PyObject *res = NULL;
assert(s != NULL);
if (strchr(s, '_') == NULL) {
return parsenumber_raw(c, s);
}
/* Create a duplicate without underscores. */
dup = PyMem_Malloc(strlen(s) + 1);
if (dup == NULL) {
return PyErr_NoMemory();
}
end = dup;
for (; *s; s++) {
if (*s != '_') {
*end++ = *s;
}
}
*end = '\0';
res = parsenumber_raw(c, dup);
PyMem_Free(dup);
return res;
}
static PyObject *
decode_utf8(struct compiling *c, const char **sPtr, const char *end)
{
const char *s, *t;
t = s = *sPtr;
/* while (s < end && *s != '\\') s++; */ /* inefficient for u".." */
while (s < end && (*s & 0x80)) s++;
*sPtr = s;
return PyUnicode_DecodeUTF8(t, s - t, NULL);
}
static int
warn_invalid_escape_sequence(struct compiling *c, const node *n,
unsigned char first_invalid_escape_char)
{
PyObject *msg = PyUnicode_FromFormat("invalid escape sequence \\%c",
first_invalid_escape_char);
if (msg == NULL) {
return -1;
}
if (PyErr_WarnExplicitObject(PyExc_DeprecationWarning, msg,
c->c_filename, LINENO(n),
NULL, NULL) < 0)
{
if (PyErr_ExceptionMatches(PyExc_DeprecationWarning)) {
const char *s;
/* Replace the DeprecationWarning exception with a SyntaxError
to get a more accurate error report */
PyErr_Clear();
s = PyUnicode_AsUTF8(msg);
if (s != NULL) {
ast_error(c, n, s);
}
}
Py_DECREF(msg);
return -1;
}
Py_DECREF(msg);
return 0;
}
static PyObject *
decode_unicode_with_escapes(struct compiling *c, const node *n, const char *s,
size_t len)
{
PyObject *v, *u;
char *buf;
char *p;
const char *end;
const char *first_invalid_escape;
/* check for integer overflow */
if (len > SIZE_MAX / 6)
return NULL;
/* "ä" (2 bytes) may become "\U000000E4" (10 bytes), or 1:5
"\ä" (3 bytes) may become "\u005c\U000000E4" (16 bytes), or ~1:6 */
u = PyBytes_FromStringAndSize((char *)NULL, len * 6);
if (u == NULL)
return NULL;
p = buf = PyBytes_AsString(u);
end = s + len;
while (s < end) {
if (*s == '\\') {
*p++ = *s++;
if (s >= end || *s & 0x80) {
strcpy(p, "u005c");
p += 5;
if (s >= end)
break;
}
}
if (*s & 0x80) { /* XXX inefficient */
PyObject *w;
int kind;
void *data;
Py_ssize_t len, i;
w = decode_utf8(c, &s, end);
if (w == NULL) {
Py_DECREF(u);
return NULL;
}
kind = PyUnicode_KIND(w);
data = PyUnicode_DATA(w);
len = PyUnicode_GET_LENGTH(w);
for (i = 0; i < len; i++) {
Py_UCS4 chr = PyUnicode_READ(kind, data, i);
sprintf(p, "\\U%08x", chr);
p += 10;
}
/* Should be impossible to overflow */
assert(p - buf <= PyBytes_GET_SIZE(u));
Py_DECREF(w);
} else {
*p++ = *s++;
}
}
len = p - buf;
s = buf;
v = _PyUnicode_DecodeUnicodeEscape(s, len, NULL, &first_invalid_escape);
if (v != NULL && first_invalid_escape != NULL) {
if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
/* We have not decref u before because first_invalid_escape points
inside u. */
Py_XDECREF(u);
Py_DECREF(v);
return NULL;
}
}
Py_XDECREF(u);
return v;
}
static PyObject *
decode_bytes_with_escapes(struct compiling *c, const node *n, const char *s,
size_t len)
{
const char *first_invalid_escape;
PyObject *result = _PyBytes_DecodeEscape(s, len, NULL, 0, NULL,
&first_invalid_escape);
if (result == NULL)
return NULL;
if (first_invalid_escape != NULL) {
if (warn_invalid_escape_sequence(c, n, *first_invalid_escape) < 0) {
Py_DECREF(result);
return NULL;
}
}
return result;
}
/* Shift locations for the given node and all its children by adding `lineno`
and `col_offset` to existing locations. */
static void fstring_shift_node_locations(node *n, int lineno, int col_offset)
{
int i;
n->n_col_offset = n->n_col_offset + col_offset;
for (i = 0; i < NCH(n); ++i) {
if (n->n_lineno && n->n_lineno < CHILD(n, i)->n_lineno) {
/* Shifting column offsets unnecessary if there's been newlines. */
col_offset = 0;
}
fstring_shift_node_locations(CHILD(n, i), lineno, col_offset);
}
n->n_lineno = n->n_lineno + lineno;
}
/* Fix locations for the given node and its children.
`parent` is the enclosing node.
`n` is the node which locations are going to be fixed relative to parent.
`expr_str` is the child node's string representation, including braces.
*/
static void
fstring_fix_node_location(const node *parent, node *n, char *expr_str)
{
char *substr = NULL;
char *start;
int lines = LINENO(parent) - 1;
int cols = parent->n_col_offset;
/* Find the full fstring to fix location information in `n`. */
while (parent && parent->n_type != STRING)
parent = parent->n_child;
if (parent && parent->n_str) {
substr = strstr(parent->n_str, expr_str);
if (substr) {
start = substr;
while (start > parent->n_str) {
if (start[0] == '\n')
break;
start--;
}
cols += substr - start;
/* Fix lineno in mulitline strings. */
while ((substr = strchr(substr + 1, '\n')))
lines--;
}
}
fstring_shift_node_locations(n, lines, cols);
}
/* Compile this expression in to an expr_ty. Add parens around the
expression, in order to allow leading spaces in the expression. */
static expr_ty
fstring_compile_expr(const char *expr_start, const char *expr_end,
struct compiling *c, const node *n)
{
PyCompilerFlags cf;
node *mod_n;
mod_ty mod;
char *str;
Py_ssize_t len;
const char *s;
int iflags = 0;
assert(expr_end >= expr_start);
assert(*(expr_start-1) == '{');
assert(*expr_end == '}' || *expr_end == '!' || *expr_end == ':');
/* If the substring is all whitespace, it's an error. We need to catch this
here, and not when we call PyParser_SimpleParseStringFlagsFilename,
because turning the expression '' in to '()' would go from being invalid
to valid. */
for (s = expr_start; s != expr_end; s++) {
char c = *s;
/* The Python parser ignores only the following whitespace
characters (\r already is converted to \n). */
if (!(c == ' ' || c == '\t' || c == '\n' || c == '\f')) {
break;
}
}
if (s == expr_end) {
ast_error(c, n, "f-string: empty expression not allowed");
return NULL;
}
len = expr_end - expr_start;
/* Allocate 3 extra bytes: open paren, close paren, null byte. */
str = PyMem_RawMalloc(len + 3);
if (str == NULL) {
PyErr_NoMemory();
return NULL;
}
str[0] = '(';
memcpy(str+1, expr_start, len);
str[len+1] = ')';
str[len+2] = 0;
cf.cf_flags = PyCF_ONLY_AST;
_Ta3Parser_UpdateFlags(&cf, &iflags, c->c_feature_version);
mod_n = Ta3Parser_SimpleParseStringFlagsFilename(str, "<fstring>",
Py_eval_input, iflags);
if (!mod_n) {
PyMem_RawFree(str);
return NULL;
}
/* Reuse str to find the correct column offset. */
str[0] = '{';
str[len+1] = '}';
fstring_fix_node_location(n, mod_n, str);
mod = Ta3AST_FromNode(mod_n, &cf, "<fstring>", c->c_feature_version, c->c_arena);
PyMem_RawFree(str);
Ta3Node_Free(mod_n);
if (!mod)
return NULL;
return mod->v.Expression.body;
}
/* Return -1 on error.
Return 0 if we reached the end of the literal.
Return 1 if we haven't reached the end of the literal, but we want
the caller to process the literal up to this point. Used for
doubled braces.
*/
static int
fstring_find_literal(const char **str, const char *end, int raw,
PyObject **literal, int recurse_lvl,
struct compiling *c, const node *n)
{
/* Get any literal string. It ends when we hit an un-doubled left
brace (which isn't part of a unicode name escape such as
"\N{EULER CONSTANT}"), or the end of the string. */
const char *s = *str;
const char *literal_start = s;
int result = 0;
assert(*literal == NULL);
while (s < end) {
char ch = *s++;
if (!raw && ch == '\\' && s < end) {
ch = *s++;
if (ch == 'N') {
if (s < end && *s++ == '{') {
while (s < end && *s++ != '}') {
}
continue;
}
break;
}
if (ch == '{' && warn_invalid_escape_sequence(c, n, ch) < 0) {
return -1;
}
}
if (ch == '{' || ch == '}') {
/* Check for doubled braces, but only at the top level. If
we checked at every level, then f'{0:{3}}' would fail
with the two closing braces. */
if (recurse_lvl == 0) {
if (s < end && *s == ch) {
/* We're going to tell the caller that the literal ends
here, but that they should continue scanning. But also
skip over the second brace when we resume scanning. */
*str = s + 1;
result = 1;
goto done;
}
/* Where a single '{' is the start of a new expression, a
single '}' is not allowed. */
if (ch == '}') {
*str = s - 1;
ast_error(c, n, "f-string: single '}' is not allowed");
return -1;
}
}
/* We're either at a '{', which means we're starting another
expression; or a '}', which means we're at the end of this
f-string (for a nested format_spec). */
s--;
break;
}
}
*str = s;
assert(s <= end);
assert(s == end || *s == '{' || *s == '}');
done:
if (literal_start != s) {
if (raw)
*literal = PyUnicode_DecodeUTF8Stateful(literal_start,
s - literal_start,
NULL, NULL);
else
*literal = decode_unicode_with_escapes(c, n, literal_start,
s - literal_start);
if (!*literal)
return -1;
}
return result;
}
/* Forward declaration because parsing is recursive. */
static expr_ty
fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n);
/* Parse the f-string at *str, ending at end. We know *str starts an
expression (so it must be a '{'). Returns the FormattedValue node,
which includes the expression, conversion character, and
format_spec expression.
Note that I don't do a perfect job here: I don't make sure that a
closing brace doesn't match an opening paren, for example. It
doesn't need to error on all invalid expressions, just correctly
find the end of all valid ones. Any errors inside the expression
will be caught when we parse it later. */
static int
fstring_find_expr(const char **str, const char *end, int raw, int recurse_lvl,
expr_ty *expression, struct compiling *c, const node *n)
{
/* Return -1 on error, else 0. */
const char *expr_start;
const char *expr_end;
expr_ty simple_expression;
expr_ty format_spec = NULL; /* Optional format specifier. */
int conversion = -1; /* The conversion char. -1 if not specified. */
/* 0 if we're not in a string, else the quote char we're trying to
match (single or double quote). */
char quote_char = 0;
/* If we're inside a string, 1=normal, 3=triple-quoted. */
int string_type = 0;
/* Keep track of nesting level for braces/parens/brackets in
expressions. */
Py_ssize_t nested_depth = 0;
/* Can only nest one level deep. */
if (recurse_lvl >= 2) {
ast_error(c, n, "f-string: expressions nested too deeply");
return -1;
}
/* The first char must be a left brace, or we wouldn't have gotten
here. Skip over it. */
assert(**str == '{');
*str += 1;
expr_start = *str;
for (; *str < end; (*str)++) {
char ch;
/* Loop invariants. */
assert(nested_depth >= 0);
assert(*str >= expr_start && *str < end);
if (quote_char)
assert(string_type == 1 || string_type == 3);
else
assert(string_type == 0);
ch = **str;
/* Nowhere inside an expression is a backslash allowed. */
if (ch == '\\') {
/* Error: can't include a backslash character, inside
parens or strings or not. */
ast_error(c, n, "f-string expression part "
"cannot include a backslash");
return -1;
}
if (quote_char) {
/* We're inside a string. See if we're at the end. */
/* This code needs to implement the same non-error logic
as tok_get from tokenizer.c, at the letter_quote
label. To actually share that code would be a
nightmare. But, it's unlikely to change and is small,
so duplicate it here. Note we don't need to catch all
of the errors, since they'll be caught when parsing the
expression. We just need to match the non-error
cases. Thus we can ignore \n in single-quoted strings,
for example. Or non-terminated strings. */
if (ch == quote_char) {
/* Does this match the string_type (single or triple
quoted)? */
if (string_type == 3) {
if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
/* We're at the end of a triple quoted string. */
*str += 2;
string_type = 0;
quote_char = 0;
continue;
}
} else {
/* We're at the end of a normal string. */
quote_char = 0;
string_type = 0;
continue;
}
}
} else if (ch == '\'' || ch == '"') {
/* Is this a triple quoted string? */
if (*str+2 < end && *(*str+1) == ch && *(*str+2) == ch) {
string_type = 3;
*str += 2;
} else {
/* Start of a normal string. */
string_type = 1;
}
/* Start looking for the end of the string. */
quote_char = ch;
} else if (ch == '[' || ch == '{' || ch == '(') {
nested_depth++;
} else if (nested_depth != 0 &&
(ch == ']' || ch == '}' || ch == ')')) {
nested_depth--;
} else if (ch == '#') {
/* Error: can't include a comment character, inside parens
or not. */
ast_error(c, n, "f-string expression part cannot include '#'");
return -1;
} else if (nested_depth == 0 &&
(ch == '!' || ch == ':' || ch == '}')) {
/* First, test for the special case of "!=". Since '=' is
not an allowed conversion character, nothing is lost in
this test. */
if (ch == '!' && *str+1 < end && *(*str+1) == '=') {
/* This isn't a conversion character, just continue. */
continue;
}
/* Normal way out of this loop. */
break;
} else {
/* Just consume this char and loop around. */
}
}
expr_end = *str;
/* If we leave this loop in a string or with mismatched parens, we
don't care. We'll get a syntax error when compiling the
expression. But, we can produce a better error message, so
let's just do that.*/
if (quote_char) {
ast_error(c, n, "f-string: unterminated string");
return -1;
}
if (nested_depth) {
ast_error(c, n, "f-string: mismatched '(', '{', or '['");
return -1;
}
if (*str >= end)
goto unexpected_end_of_string;
/* Compile the expression as soon as possible, so we show errors
related to the expression before errors related to the
conversion or format_spec. */
simple_expression = fstring_compile_expr(expr_start, expr_end, c, n);
if (!simple_expression)
return -1;
/* Check for a conversion char, if present. */
if (**str == '!') {
*str += 1;
if (*str >= end)
goto unexpected_end_of_string;
conversion = **str;
*str += 1;
/* Validate the conversion. */
if (!(conversion == 's' || conversion == 'r'
|| conversion == 'a')) {
ast_error(c, n, "f-string: invalid conversion character: "
"expected 's', 'r', or 'a'");
return -1;
}
}
/* Check for the format spec, if present. */
if (*str >= end)
goto unexpected_end_of_string;
if (**str == ':') {
*str += 1;
if (*str >= end)
goto unexpected_end_of_string;
/* Parse the format spec. */
format_spec = fstring_parse(str, end, raw, recurse_lvl+1, c, n);
if (!format_spec)
return -1;
}
if (*str >= end || **str != '}')
goto unexpected_end_of_string;
/* We're at a right brace. Consume it. */
assert(*str < end);
assert(**str == '}');
*str += 1;
/* And now create the FormattedValue node that represents this
entire expression with the conversion and format spec. */
*expression = FormattedValue(simple_expression, conversion,
format_spec, LINENO(n), n->n_col_offset,
c->c_arena);
if (!*expression)
return -1;
return 0;
unexpected_end_of_string:
ast_error(c, n, "f-string: expecting '}'");
return -1;
}
/* Return -1 on error.
Return 0 if we have a literal (possible zero length) and an
expression (zero length if at the end of the string.
Return 1 if we have a literal, but no expression, and we want the
caller to call us again. This is used to deal with doubled
braces.
When called multiple times on the string 'a{{b{0}c', this function
will return:
1. the literal 'a{' with no expression, and a return value
of 1. Despite the fact that there's no expression, the return
value of 1 means we're not finished yet.
2. the literal 'b' and the expression '0', with a return value of
0. The fact that there's an expression means we're not finished.
3. literal 'c' with no expression and a return value of 0. The
combination of the return value of 0 with no expression means
we're finished.
*/
static int
fstring_find_literal_and_expr(const char **str, const char *end, int raw,
int recurse_lvl, PyObject **literal,
expr_ty *expression,
struct compiling *c, const node *n)
{
int result;
assert(*literal == NULL && *expression == NULL);
/* Get any literal string. */
result = fstring_find_literal(str, end, raw, literal, recurse_lvl, c, n);
if (result < 0)
goto error;
assert(result == 0 || result == 1);
if (result == 1)
/* We have a literal, but don't look at the expression. */
return 1;
if (*str >= end || **str == '}')
/* We're at the end of the string or the end of a nested
f-string: no expression. The top-level error case where we
expect to be at the end of the string but we're at a '}' is
handled later. */
return 0;
/* We must now be the start of an expression, on a '{'. */
assert(**str == '{');
if (fstring_find_expr(str, end, raw, recurse_lvl, expression, c, n) < 0)
goto error;
return 0;
error:
Py_CLEAR(*literal);
return -1;
}
#define EXPRLIST_N_CACHED 64
typedef struct {
/* Incrementally build an array of expr_ty, so be used in an
asdl_seq. Cache some small but reasonably sized number of
expr_ty's, and then after that start dynamically allocating,
doubling the number allocated each time. Note that the f-string
f'{0}a{1}' contains 3 expr_ty's: 2 FormattedValue's, and one
Str for the literal 'a'. So you add expr_ty's about twice as
fast as you add exressions in an f-string. */
Py_ssize_t allocated; /* Number we've allocated. */
Py_ssize_t size; /* Number we've used. */
expr_ty *p; /* Pointer to the memory we're actually
using. Will point to 'data' until we
start dynamically allocating. */
expr_ty data[EXPRLIST_N_CACHED];
} ExprList;
#ifdef NDEBUG
#define ExprList_check_invariants(l)
#else
static void
ExprList_check_invariants(ExprList *l)
{
/* Check our invariants. Make sure this object is "live", and
hasn't been deallocated. */
assert(l->size >= 0);
assert(l->p != NULL);
if (l->size <= EXPRLIST_N_CACHED)
assert(l->data == l->p);
}
#endif
static void
ExprList_Init(ExprList *l)
{
l->allocated = EXPRLIST_N_CACHED;
l->size = 0;
/* Until we start allocating dynamically, p points to data. */
l->p = l->data;
ExprList_check_invariants(l);
}
static int
ExprList_Append(ExprList *l, expr_ty exp)
{
ExprList_check_invariants(l);
if (l->size >= l->allocated) {
/* We need to alloc (or realloc) the memory. */
Py_ssize_t new_size = l->allocated * 2;
/* See if we've ever allocated anything dynamically. */
if (l->p == l->data) {
Py_ssize_t i;
/* We're still using the cached data. Switch to
alloc-ing. */
l->p = PyMem_RawMalloc(sizeof(expr_ty) * new_size);
if (!l->p)
return -1;
/* Copy the cached data into the new buffer. */
for (i = 0; i < l->size; i++)
l->p[i] = l->data[i];
} else {
/* Just realloc. */
expr_ty *tmp = PyMem_RawRealloc(l->p, sizeof(expr_ty) * new_size);
if (!tmp) {
PyMem_RawFree(l->p);
l->p = NULL;
return -1;
}
l->p = tmp;
}
l->allocated = new_size;
assert(l->allocated == 2 * l->size);
}
l->p[l->size++] = exp;
ExprList_check_invariants(l);
return 0;
}
static void
ExprList_Dealloc(ExprList *l)
{
ExprList_check_invariants(l);
/* If there's been an error, or we've never dynamically allocated,
do nothing. */
if (!l->p || l->p == l->data) {
/* Do nothing. */
} else {
/* We have dynamically allocated. Free the memory. */
PyMem_RawFree(l->p);
}
l->p = NULL;
l->size = -1;
}
static asdl_seq *
ExprList_Finish(ExprList *l, PyArena *arena)
{
asdl_seq *seq;
ExprList_check_invariants(l);
/* Allocate the asdl_seq and copy the expressions in to it. */
seq = _Ta3_asdl_seq_new(l->size, arena);
if (seq) {
Py_ssize_t i;
for (i = 0; i < l->size; i++)
asdl_seq_SET(seq, i, l->p[i]);
}
ExprList_Dealloc(l);
return seq;
}
/* The FstringParser is designed to add a mix of strings and
f-strings, and concat them together as needed. Ultimately, it
generates an expr_ty. */
typedef struct {
PyObject *last_str;
ExprList expr_list;
int fmode;
} FstringParser;
#ifdef NDEBUG
#define FstringParser_check_invariants(state)
#else
static void
FstringParser_check_invariants(FstringParser *state)
{
if (state->last_str)
assert(PyUnicode_CheckExact(state->last_str));
ExprList_check_invariants(&state->expr_list);
}
#endif
static void
FstringParser_Init(FstringParser *state)
{
state->last_str = NULL;
state->fmode = 0;
ExprList_Init(&state->expr_list);
FstringParser_check_invariants(state);
}
static void
FstringParser_Dealloc(FstringParser *state)
{
FstringParser_check_invariants(state);
Py_XDECREF(state->last_str);
ExprList_Dealloc(&state->expr_list);
}
static PyObject *
make_str_kind(const char *raw) {
/* currently Python allows up to 2 string modifiers */
char *ch, s_kind[3] = {0, 0, 0};
ch = s_kind;
while (*raw && *raw != '\'' && *raw != '"') {
*ch++ = *raw++;
}
return PyUnicode_FromString(s_kind);
}
/* Make a Str node, but decref the PyUnicode object being added. */
static expr_ty
make_str_node_and_del(PyObject **str, struct compiling *c, const node* n)
{
PyObject *s = *str;
PyObject *kind = make_str_kind(STR(CHILD(n, 0)));
if (!kind) {
return NULL;
}
*str = NULL;
assert(PyUnicode_CheckExact(s));
if (PyArena_AddPyObject(c->c_arena, s) < 0) {
Py_DECREF(s);
return NULL;
}
return Str(s, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
/* Add a non-f-string (that is, a regular literal string). str is
decref'd. */
static int
FstringParser_ConcatAndDel(FstringParser *state, PyObject *str)
{
FstringParser_check_invariants(state);
assert(PyUnicode_CheckExact(str));
if (PyUnicode_GET_LENGTH(str) == 0) {
Py_DECREF(str);
return 0;
}
if (!state->last_str) {
/* We didn't have a string before, so just remember this one. */
state->last_str = str;
} else {
/* Concatenate this with the previous string. */
PyUnicode_AppendAndDel(&state->last_str, str);
if (!state->last_str)
return -1;
}
FstringParser_check_invariants(state);
return 0;
}
/* Parse an f-string. The f-string is in *str to end, with no
'f' or quotes. */
static int
FstringParser_ConcatFstring(FstringParser *state, const char **str,
const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n)
{
FstringParser_check_invariants(state);
state->fmode = 1;
/* Parse the f-string. */
while (1) {
PyObject *literal = NULL;
expr_ty expression = NULL;
/* If there's a zero length literal in front of the
expression, literal will be NULL. If we're at the end of
the f-string, expression will be NULL (unless result == 1,
see below). */
int result = fstring_find_literal_and_expr(str, end, raw, recurse_lvl,
&literal, &expression,
c, n);
if (result < 0)
return -1;
/* Add the literal, if any. */
if (!literal) {
/* Do nothing. Just leave last_str alone (and possibly
NULL). */
} else if (!state->last_str) {
/* Note that the literal can be zero length, if the
input string is "\\\n" or "\\\r", among others. */
state->last_str = literal;
literal = NULL;
} else {
/* We have a literal, concatenate it. */
assert(PyUnicode_GET_LENGTH(literal) != 0);
if (FstringParser_ConcatAndDel(state, literal) < 0)
return -1;
literal = NULL;
}
/* We've dealt with the literal now. It can't be leaked on further
errors. */
assert(literal == NULL);
/* See if we should just loop around to get the next literal
and expression, while ignoring the expression this
time. This is used for un-doubling braces, as an
optimization. */
if (result == 1)
continue;
if (!expression)
/* We're done with this f-string. */
break;
/* We know we have an expression. Convert any existing string
to a Str node. */
if (!state->last_str) {
/* Do nothing. No previous literal. */
} else {
/* Convert the existing last_str literal to a Str node. */
expr_ty str = make_str_node_and_del(&state->last_str, c, n);
if (!str || ExprList_Append(&state->expr_list, str) < 0)
return -1;
}
if (ExprList_Append(&state->expr_list, expression) < 0)
return -1;
}
/* If recurse_lvl is zero, then we must be at the end of the
string. Otherwise, we must be at a right brace. */
if (recurse_lvl == 0 && *str < end-1) {
ast_error(c, n, "f-string: unexpected end of string");
return -1;
}
if (recurse_lvl != 0 && **str != '}') {
ast_error(c, n, "f-string: expecting '}'");
return -1;
}
FstringParser_check_invariants(state);
return 0;
}
/* Convert the partial state reflected in last_str and expr_list to an
expr_ty. The expr_ty can be a Str, or a JoinedStr. */
static expr_ty
FstringParser_Finish(FstringParser *state, struct compiling *c,
const node *n)
{
asdl_seq *seq;
FstringParser_check_invariants(state);
/* If we're just a constant string with no expressions, return
that. */
if (!state->fmode) {
assert(!state->expr_list.size);
if (!state->last_str) {
/* Create a zero length string. */
state->last_str = PyUnicode_FromStringAndSize(NULL, 0);
if (!state->last_str)
goto error;
}
return make_str_node_and_del(&state->last_str, c, n);
}
/* Create a Str node out of last_str, if needed. It will be the
last node in our expression list. */
if (state->last_str) {
expr_ty str = make_str_node_and_del(&state->last_str, c, n);
if (!str || ExprList_Append(&state->expr_list, str) < 0)
goto error;
}
/* This has already been freed. */
assert(state->last_str == NULL);
seq = ExprList_Finish(&state->expr_list, c->c_arena);
if (!seq)
goto error;
return JoinedStr(seq, LINENO(n), n->n_col_offset, c->c_arena);
error:
FstringParser_Dealloc(state);
return NULL;
}
/* Given an f-string (with no 'f' or quotes) that's in *str and ends
at end, parse it into an expr_ty. Return NULL on error. Adjust
str to point past the parsed portion. */
static expr_ty
fstring_parse(const char **str, const char *end, int raw, int recurse_lvl,
struct compiling *c, const node *n)
{
FstringParser state;
FstringParser_Init(&state);
if (FstringParser_ConcatFstring(&state, str, end, raw, recurse_lvl,
c, n) < 0) {
FstringParser_Dealloc(&state);
return NULL;
}
return FstringParser_Finish(&state, c, n);
}
/* n is a Python string literal, including the bracketing quote
characters, and r, b, u, &/or f prefixes (if any), and embedded
escape sequences (if any). parsestr parses it, and sets *result to
decoded Python string object. If the string is an f-string, set
*fstr and *fstrlen to the unparsed string object. Return 0 if no
errors occurred.
*/
static int
parsestr(struct compiling *c, const node *n, int *bytesmode, int *rawmode,
PyObject **result, const char **fstr, Py_ssize_t *fstrlen)
{
size_t len;
const char *s = STR(n);
int quote = Py_CHARMASK(*s);
int fmode = 0;
*bytesmode = 0;
*rawmode = 0;
*result = NULL;
*fstr = NULL;
if (Py_ISALPHA(quote)) {
while (!*bytesmode || !*rawmode) {
if (quote == 'b' || quote == 'B') {
quote = *++s;
*bytesmode = 1;
}
else if (quote == 'u' || quote == 'U') {
quote = *++s;
}
else if (quote == 'r' || quote == 'R') {
quote = *++s;
*rawmode = 1;
}
else if (quote == 'f' || quote == 'F') {
quote = *++s;
fmode = 1;
}
else {
break;
}
}
}
/* fstrings are only allowed in Python 3.6 and greater */
if (fmode && c->c_feature_version < 6) {
ast_error(c, n, "Format strings are only supported in Python 3.6 and greater");
return -1;
}
if (fmode && *bytesmode) {
PyErr_BadInternalCall();
return -1;
}
if (quote != '\'' && quote != '\"') {
PyErr_BadInternalCall();
return -1;
}
/* Skip the leading quote char. */
s++;
len = strlen(s);
if (len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string to parse is too long");
return -1;
}
if (s[--len] != quote) {
/* Last quote char must match the first. */
PyErr_BadInternalCall();
return -1;
}
if (len >= 4 && s[0] == quote && s[1] == quote) {
/* A triple quoted string. We've already skipped one quote at
the start and one at the end of the string. Now skip the
two at the start. */
s += 2;
len -= 2;
/* And check that the last two match. */
if (s[--len] != quote || s[--len] != quote) {
PyErr_BadInternalCall();
return -1;
}
}
if (fmode) {
/* Just return the bytes. The caller will parse the resulting
string. */
*fstr = s;
*fstrlen = len;
return 0;
}
/* Not an f-string. */
/* Avoid invoking escape decoding routines if possible. */
*rawmode = *rawmode || strchr(s, '\\') == NULL;
if (*bytesmode) {
/* Disallow non-ASCII characters. */
const char *ch;
for (ch = s; *ch; ch++) {
if (Py_CHARMASK(*ch) >= 0x80) {
ast_error(c, n, "bytes can only contain ASCII "
"literal characters.");
return -1;
}
}
if (*rawmode)
*result = PyBytes_FromStringAndSize(s, len);
else
*result = decode_bytes_with_escapes(c, n, s, len);
} else {
if (*rawmode)
*result = PyUnicode_DecodeUTF8Stateful(s, len, NULL, NULL);
else
*result = decode_unicode_with_escapes(c, n, s, len);
}
return *result == NULL ? -1 : 0;
}
/* Accepts a STRING+ atom, and produces an expr_ty node. Run through
each STRING atom, and process it as needed. For bytes, just
concatenate them together, and the result will be a Bytes node. For
normal strings and f-strings, concatenate them together. The result
will be a Str node if there were no f-strings; a FormattedValue
node if there's just an f-string (with no leading or trailing
literals), or a JoinedStr node if there are multiple f-strings or
any literals involved. */
static expr_ty
parsestrplus(struct compiling *c, const node *n)
{
int bytesmode = 0;
PyObject *bytes_str = NULL;
int i;
FstringParser state;
FstringParser_Init(&state);
for (i = 0; i < NCH(n); i++) {
int this_bytesmode;
int this_rawmode;
PyObject *s;
const char *fstr;
Py_ssize_t fstrlen = -1; /* Silence a compiler warning. */
REQ(CHILD(n, i), STRING);
if (parsestr(c, CHILD(n, i), &this_bytesmode, &this_rawmode, &s,
&fstr, &fstrlen) != 0)
goto error;
/* Check that we're not mixing bytes with unicode. */
if (i != 0 && bytesmode != this_bytesmode) {
ast_error(c, n, "cannot mix bytes and nonbytes literals");
/* s is NULL if the current string part is an f-string. */
Py_XDECREF(s);
goto error;
}
bytesmode = this_bytesmode;
if (fstr != NULL) {
int result;
assert(s == NULL && !bytesmode);
/* This is an f-string. Parse and concatenate it. */
result = FstringParser_ConcatFstring(&state, &fstr, fstr+fstrlen,
this_rawmode, 0, c, n);
if (result < 0)
goto error;
} else {
/* A string or byte string. */
assert(s != NULL && fstr == NULL);
assert(bytesmode ? PyBytes_CheckExact(s) :
PyUnicode_CheckExact(s));
if (bytesmode) {
/* For bytes, concat as we go. */
if (i == 0) {
/* First time, just remember this value. */
bytes_str = s;
} else {
PyBytes_ConcatAndDel(&bytes_str, s);
if (!bytes_str)
goto error;
}
} else {
/* This is a regular string. Concatenate it. */
if (FstringParser_ConcatAndDel(&state, s) < 0)
goto error;
}
}
}
if (bytesmode) {
PyObject *kind = make_str_kind(STR(CHILD(n, 0)));
/* Just return the bytes object and we're done. */
if (PyArena_AddPyObject(c->c_arena, bytes_str) < 0) {
Py_DECREF(kind);
goto error;
}
return Bytes(bytes_str, kind, LINENO(n), n->n_col_offset, c->c_arena);
}
/* We're not a bytes string, bytes_str should never have been set. */
assert(bytes_str == NULL);
return FstringParser_Finish(&state, c, n);
error:
Py_XDECREF(bytes_str);
FstringParser_Dealloc(&state);
return NULL;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_1283_0 |
crossvul-cpp_data_bad_182_0 | /* radare - LGPL - Copyright 2015 - condret, riq */
/* 6502 info taken from http://unusedino.de/ec64/technical/aay/c64/bchrt651.htm
*
* Mnemonics logic based on:
* http://homepage.ntlworld.com/cyborgsystems/CS_Main/6502/6502.htm
* and:
* http://vice-emu.sourceforge.net/
*/
#include <string.h>
#include <r_types.h>
#include <r_lib.h>
#include <r_asm.h>
#include <r_anal.h>
#include "../../asm/arch/snes/snes_op_table.h"
enum {
_6502_FLAGS_C = (1 << 0),
_6502_FLAGS_B = (1 << 1),
_6502_FLAGS_Z = (1 << 2),
_6502_FLAGS_N = (1 << 3),
_6502_FLAGS_NZ = (_6502_FLAGS_Z | _6502_FLAGS_N),
_6502_FLAGS_CNZ = (_6502_FLAGS_C | _6502_FLAGS_Z | _6502_FLAGS_N),
_6502_FLAGS_BNZ = (_6502_FLAGS_B | _6502_FLAGS_Z | _6502_FLAGS_N),
};
static void _6502_anal_update_flags(RAnalOp *op, int flags) {
/* FIXME: $b9 instead of $b8 to prevent the bug triggered by: A = 0 - 0xff - 1 */
if (flags & _6502_FLAGS_B) r_strbuf_append (&op->esil, ",$b9,C,=");
if (flags & _6502_FLAGS_C) r_strbuf_append (&op->esil, ",$c7,C,=");
if (flags & _6502_FLAGS_Z) r_strbuf_append (&op->esil, ",$z,Z,=");
if (flags & _6502_FLAGS_N) r_strbuf_append (&op->esil, ",$s,N,=");
}
/* ORA, AND, EOR, ADC, STA, LDA, CMP and SBC share this pattern */
static void _6502_anal_esil_get_addr_pattern1(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize) {
// turn off bits 5, 6 and 7
switch(data[0] & 0x1f) { // 0x1f = b00111111
case 0x09: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize,"0x%02x", data[1]);
break;
case 0x05: // op $ff
op->cycles = 3;
snprintf (addrbuf, addrsize,"0x%02x", data[1]);
break;
case 0x15: // op $ff,x
op->cycles = 4;
snprintf (addrbuf, addrsize,"x,0x%02x,+", data[1]);
break;
case 0x0d: // op $ffff
op->cycles = 4;
snprintf (addrbuf, addrsize,"0x%04x", data[1] | data[2] << 8);
break;
case 0x1d: // op $ffff,x
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 4;
snprintf (addrbuf, addrsize,"x,0x%04x,+", data[1] | data[2] << 8);
break;
case 0x19: // op $ffff,y
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 4;
snprintf (addrbuf, addrsize,"y,0x%04x,+", data[1] | data[2] << 8);
break;
case 0x01: // op ($ff,x)
op->cycles = 6;
snprintf (addrbuf, addrsize,"x,0x%02x,+,[2]", data[1]);
break;
case 0x11: // op ($ff),y
// FIXME: Add 1 if page boundary is crossed.
op->cycles = 5;
snprintf (addrbuf, addrsize,"y,0x%02x,[2],+", data[1]);
break;
}
}
/* ASL, ROL, LSR, ROR, STX, LDX, DEC and INC share this pattern */
static void _6502_anal_esil_get_addr_pattern2(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize, char reg) {
// turn off bits 5, 6 and 7
switch(data[0] & 0x1f) { // 0x1f = b00111111
case 0x02: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x0a: //op a
op->cycles = 2;
snprintf (addrbuf, addrsize, "a");
break;
case 0x06: // op $ff
op->cycles = 5;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x16: // op $ff,x
op->cycles = 6;
snprintf (addrbuf, addrsize, "%c,0x%02x,+", reg, data[1]);
break;
case 0x0e: // op $ffff
op->cycles = 6;
snprintf (addrbuf, addrsize, "0x%04x", data[1] | data[2] << 8);
break;
case 0x1e: // op $ffff,x
op->cycles = 7;
snprintf (addrbuf, addrsize, "%c,0x%04x,+", reg, data[1] | data[2] << 8);
break;
}
}
/* BIT, JMP, JMP(), STY, LDY, CPY, and CPX share this pattern */
static void _6502_anal_esil_get_addr_pattern3(RAnalOp *op, const ut8* data, char* addrbuf, int addrsize, char reg) {
// turn off bits 5, 6 and 7
switch (data[0] & 0x1f) { // 0x1f = b00111111
case 0x00: // op #$ff
op->cycles = 2;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x08: //op a
op->cycles = 2;
snprintf (addrbuf, addrsize, "a");
break;
case 0x04: // op $ff
op->cycles = 5;
snprintf (addrbuf, addrsize, "0x%02x", data[1]);
break;
case 0x14: // op $ff,x
op->cycles = 6;
snprintf (addrbuf, addrsize, "%c,0x%02x,+", reg, data[1]);
break;
case 0x0c: // op $ffff
op->cycles = 6;
snprintf (addrbuf, addrsize, "0x%04x", data[1] | data[2] << 8);
break;
case 0x1c: // op $ffff,x
op->cycles = 7;
snprintf (addrbuf, addrsize, "%c,0x%04x,+", reg, data[1] | data[2] << 8);
break;
}
}
static void _6502_anal_esil_ccall(RAnalOp *op, ut8 data0)
{
char *flag;
switch(data0) {
case 0x10: // bpl $ffff
flag = "N,!";
break;
case 0x30: // bmi $ffff
flag = "N";
break;
case 0x50: // bvc $ffff
flag = "V,!";
break;
case 0x70: // bvs $ffff
flag = "V";
break;
case 0x90: // bcc $ffff
flag = "C,!";
break;
case 0xb0: // bcs $ffff
flag = "C";
break;
case 0xd0: // bne $ffff
flag = "Z,!";
break;
case 0xf0: // beq $ffff
flag = "Z";
break;
default:
// FIXME: should not happen
flag = "unk";
break;
}
r_strbuf_setf (&op->esil, "%s,?{,0x%04x,pc,=,}", flag, (op->jump & 0xffff));
}
// inc register
static void _6502_anal_esil_inc_reg(RAnalOp *op, ut8 data0, char* sign)
{
char* reg = NULL;
switch(data0) {
case 0xe8: // inx
case 0xca: // dex
reg = "x";
break;
case 0xc8: // iny
case 0x88: // dey
reg = "y";
break;
}
r_strbuf_setf (&op->esil, "%s,%s%s=", reg, sign, sign);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_mov(RAnalOp *op, ut8 data0) {
const char* src="unk";
const char* dst="unk";
switch(data0) {
case 0xaa: // tax
src="a";
dst="x";
break;
case 0x8a: // txa
src="x";
dst="a";
break;
case 0xa8: // tay
src="a";
dst="y";
break;
case 0x98: // tya
src="y";
dst="a";
break;
case 0x9a: // txs
src="x";
dst="sp";
break;
case 0xba: // tsx
src="sp";
dst="x";
break;
default:
// FIXME: should not happen
break;
}
r_strbuf_setf (&op->esil, "%s,%s,=",src,dst);
// don't update NZ on txs
if (data0 != 0x9a) _6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_push(RAnalOp *op, ut8 data0) {
// case 0x08: // php
// case 0x48: // pha
char *reg = (data0==0x08) ? "flags" : "a";
// stack is on page one: sp + 0x100
r_strbuf_setf (&op->esil, "%s,sp,0x100,+,=[1],sp,--=", reg);
}
static void _6502_anal_esil_pop(RAnalOp *op, ut8 data0) {
// case 0x28: // plp
// case 0x68: // pla
char *reg = (data0==0x28) ? "flags" : "a";
// stack is on page one: sp + 0x100
r_strbuf_setf (&op->esil, "sp,++=,sp,0x100,+,[1],%s,=", reg);
if (data0==0x68) _6502_anal_update_flags (op, _6502_FLAGS_NZ);
}
static void _6502_anal_esil_flags(RAnalOp *op, ut8 data0) {
int enabled=0;
char flag ='u';
switch(data0) {
case 0x78: // sei
enabled = 1;
flag = 'I';
break;
case 0x58: // cli
enabled = 0;
flag = 'I';
break;
case 0x38: // sec
enabled = 1;
flag = 'C';
break;
case 0x18: // clc
enabled = 0;
flag = 'C';
break;
case 0xf8: // sed
enabled = 1;
flag = 'D';
break;
case 0xd8: // cld
enabled = 0;
flag = 'D';
break;
case 0xb8: // clv
enabled = 0;
flag = 'V';
break;
break;
}
r_strbuf_setf (&op->esil, "%d,%c,=", enabled, flag);
}
static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) {
char addrbuf[64];
const int buffsize = sizeof (addrbuf) - 1;
memset (op, '\0', sizeof (RAnalOp));
op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502
op->addr = addr;
op->type = R_ANAL_OP_TYPE_UNK;
op->id = data[0];
r_strbuf_init (&op->esil);
switch (data[0]) {
case 0x02:
case 0x03:
case 0x04:
case 0x07:
case 0x0b:
case 0x0c:
case 0x0f:
case 0x12:
case 0x13:
case 0x14:
case 0x17:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1f:
case 0x22:
case 0x23:
case 0x27:
case 0x2b:
case 0x2f:
case 0x32:
case 0x33:
case 0x34:
case 0x37:
case 0x3a:
case 0x3b:
case 0x3c:
case 0x3f:
case 0x42:
case 0x43:
case 0x44:
case 0x47:
case 0x4b:
case 0x4f:
case 0x52:
case 0x53:
case 0x54:
case 0x57:
case 0x5a:
case 0x5b:
case 0x5c:
case 0x5f:
case 0x62:
case 0x63:
case 0x64:
case 0x67:
case 0x6b:
case 0x6f:
case 0x72:
case 0x73:
case 0x74:
case 0x77:
case 0x7a:
case 0x7b:
case 0x7c:
case 0x7f:
case 0x80:
case 0x82:
case 0x83:
case 0x87:
case 0x89:
case 0x8b:
case 0x8f:
case 0x92:
case 0x93:
case 0x97:
case 0x9b:
case 0x9c:
case 0x9e:
case 0x9f:
case 0xa3:
case 0xa7:
case 0xab:
case 0xaf:
case 0xb2:
case 0xb3:
case 0xb7:
case 0xbb:
case 0xbf:
case 0xc2:
case 0xc3:
case 0xc7:
case 0xcb:
case 0xcf:
case 0xd2:
case 0xd3:
case 0xd4:
case 0xd7:
case 0xda:
case 0xdb:
case 0xdc:
case 0xdf:
case 0xe2:
case 0xe3:
case 0xe7:
case 0xeb:
case 0xef:
case 0xf2:
case 0xf3:
case 0xf4:
case 0xf7:
case 0xfa:
case 0xfb:
case 0xfc:
case 0xff:
// undocumented or not-implemented opcodes for 6502.
// some of them might be implemented in 65816
op->size = 1;
op->type = R_ANAL_OP_TYPE_ILL;
break;
// BRK
case 0x00: // brk
op->cycles = 7;
op->type = R_ANAL_OP_TYPE_SWI;
// override 65816 code which seems to be wrong: size is 1, but pc = pc + 2
op->size = 1;
// PC + 2 to Stack, P to Stack B=1 D=0 I=1. "B" is not a flag. Only its bit is pushed on the stack
// PC was already incremented by one at this point. Needs to incremented once more
// New PC is Interrupt Vector: $fffe. (FIXME: Confirm this is valid for all 6502)
r_strbuf_set (&op->esil, ",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=");
break;
// FLAGS
case 0x78: // sei
case 0x58: // cli
case 0x38: // sec
case 0x18: // clc
case 0xf8: // sed
case 0xd8: // cld
case 0xb8: // clv
op->cycles = 2;
// FIXME: what opcode for this?
op->type = R_ANAL_OP_TYPE_NOP;
_6502_anal_esil_flags (op, data[0]);
break;
// BIT
case 0x24: // bit $ff
case 0x2c: // bit $ffff
op->type = R_ANAL_OP_TYPE_MOV;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
r_strbuf_setf (&op->esil, "a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,=",addrbuf, addrbuf, addrbuf);
break;
// ADC
case 0x69: // adc #$ff
case 0x65: // adc $ff
case 0x75: // adc $ff,x
case 0x6d: // adc $ffff
case 0x7d: // adc $ffff,x
case 0x79: // adc $ffff,y
case 0x61: // adc ($ff,x)
case 0x71: // adc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_ADD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x69) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
// fix Z
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=");
break;
// SBC
case 0xe9: // sbc #$ff
case 0xe5: // sbc $ff
case 0xf5: // sbc $ff,x
case 0xed: // sbc $ffff
case 0xfd: // sbc $ffff,x
case 0xf9: // sbc $ffff,y
case 0xe1: // sbc ($ff,x)
case 0xf1: // sbc ($ff,y)
// FIXME: update V
// FIXME: support BCD mode
op->type = R_ANAL_OP_TYPE_SUB;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xe9) // immediate mode
r_strbuf_setf (&op->esil, "C,!,%s,+,a,-=", addrbuf);
else r_strbuf_setf (&op->esil, "C,!,%s,[1],+,a,-=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// fix Z and revert C
r_strbuf_append (&op->esil, ",a,a,=,$z,Z,=,C,!=");
break;
// ORA
case 0x09: // ora #$ff
case 0x05: // ora $ff
case 0x15: // ora $ff,x
case 0x0d: // ora $ffff
case 0x1d: // ora $ffff,x
case 0x19: // ora $ffff,y
case 0x01: // ora ($ff,x)
case 0x11: // ora ($ff),y
op->type = R_ANAL_OP_TYPE_OR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x09) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,|=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,|=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// AND
case 0x29: // and #$ff
case 0x25: // and $ff
case 0x35: // and $ff,x
case 0x2d: // and $ffff
case 0x3d: // and $ffff,x
case 0x39: // and $ffff,y
case 0x21: // and ($ff,x)
case 0x31: // and ($ff),y
op->type = R_ANAL_OP_TYPE_AND;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x29) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,&=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,&=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// EOR
case 0x49: // eor #$ff
case 0x45: // eor $ff
case 0x55: // eor $ff,x
case 0x4d: // eor $ffff
case 0x5d: // eor $ffff,x
case 0x59: // eor $ffff,y
case 0x41: // eor ($ff,x)
case 0x51: // eor ($ff),y
op->type = R_ANAL_OP_TYPE_XOR;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0x49) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,^=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,^=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ASL
case 0x0a: // asl a
case 0x06: // asl $ff
case 0x16: // asl $ff,x
case 0x0e: // asl $ffff
case 0x1e: // asl $ffff,x
op->type = R_ANAL_OP_TYPE_SHL;
if (data[0] == 0x0a) {
r_strbuf_set (&op->esil, "1,a,<<=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LSR
case 0x4a: // lsr a
case 0x46: // lsr $ff
case 0x56: // lsr $ff,x
case 0x4e: // lsr $ffff
case 0x5e: // lsr $ffff,x
op->type = R_ANAL_OP_TYPE_SHR;
if (data[0] == 0x4a) {
r_strbuf_set (&op->esil, "1,a,&,C,=,1,a,>>=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROL
case 0x2a: // rol a
case 0x26: // rol $ff
case 0x36: // rol $ff,x
case 0x2e: // rol $ffff
case 0x3e: // rol $ffff,x
op->type = R_ANAL_OP_TYPE_ROL;
if (data[0] == 0x2a) {
r_strbuf_set (&op->esil, "1,a,<<,C,|,a,=,$c7,C,=,a,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "1,%s,[1],<<,C,|,%s,=[1],$c7,C,=", addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// ROR
case 0x6a: // ror a
case 0x66: // ror $ff
case 0x76: // ror $ff,x
case 0x6e: // ror $ffff
case 0x7e: // ror $ffff,x
// uses N as temporary to hold C value. but in fact,
// it is not temporary since in all ROR ops, N will have the value of C
op->type = R_ANAL_OP_TYPE_ROR;
if (data[0] == 0x6a) {
r_strbuf_set (&op->esil, "C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=");
} else {
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]", addrbuf, addrbuf, addrbuf);
}
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INC
case 0xe6: // inc $ff
case 0xf6: // inc $ff,x
case 0xee: // inc $ffff
case 0xfe: // inc $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,++=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// DEC
case 0xc6: // dec $ff
case 0xd6: // dec $ff,x
case 0xce: // dec $ffff
case 0xde: // dec $ffff,x
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "%s,--=[1]", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// INX, INY
case 0xe8: // inx
case 0xc8: // iny
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "+");
break;
// DEX, DEY
case 0xca: // dex
case 0x88: // dey
op->cycles = 2;
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_inc_reg (op, data[0], "-");
break;
// CMP
case 0xc9: // cmp #$ff
case 0xc5: // cmp $ff
case 0xd5: // cmp $ff,x
case 0xcd: // cmp $ffff
case 0xdd: // cmp $ffff,x
case 0xd9: // cmp $ffff,y
case 0xc1: // cmp ($ff,x)
case 0xd1: // cmp ($ff),y
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xc9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPX
case 0xe0: // cpx #$ff
case 0xe4: // cpx $ff
case 0xec: // cpx $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xe0) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// CPY
case 0xc0: // cpy #$ff
case 0xc4: // cpy $ff
case 0xcc: // cpy $ffff
op->type = R_ANAL_OP_TYPE_CMP;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0);
if (data[0] == 0xc0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,==", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,==", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_BNZ);
// invert C, since C=1 when A-M >= 0
r_strbuf_append (&op->esil, ",C,!,C,=");
break;
// BRANCHES
case 0x10: // bpl $ffff
case 0x30: // bmi $ffff
case 0x50: // bvc $ffff
case 0x70: // bvs $ffff
case 0x90: // bcc $ffff
case 0xb0: // bcs $ffff
case 0xd0: // bne $ffff
case 0xf0: // beq $ffff
// FIXME: Add 1 if branch occurs to same page.
// FIXME: Add 2 if branch occurs to different page
op->cycles = 2;
op->failcycles = 3;
op->type = R_ANAL_OP_TYPE_CJMP;
if (data[1] <= 127)
op->jump = addr + data[1] + op->size;
else op->jump = addr - (256 - data[1]) + op->size;
op->fail = addr + op->size;
// FIXME: add a type of conditional
// op->cond = R_ANAL_COND_LE;
_6502_anal_esil_ccall (op, data[0]);
break;
// JSR
case 0x20: // jsr $ffff
op->cycles = 6;
op->type = R_ANAL_OP_TYPE_CALL;
op->jump = data[1] | data[2] << 8;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 2;
// JSR pushes the address-1 of the next operation on to the stack before transferring program
// control to the following address
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_setf (&op->esil, "1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-=", op->jump);
break;
// JMP
case 0x4c: // jmp $ffff
op->cycles = 3;
op->type = R_ANAL_OP_TYPE_JMP;
op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,pc,=", op->jump);
break;
case 0x6c: // jmp ($ffff)
op->cycles = 5;
op->type = R_ANAL_OP_TYPE_UJMP;
// FIXME: how to read memory?
// op->jump = data[1] | data[2] << 8;
r_strbuf_setf (&op->esil, "0x%04x,[2],pc,=", data[1] | data[2] << 8);
break;
// RTS
case 0x60: // rts
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -2;
// Operation: PC from Stack, PC + 1 -> PC
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=");
break;
// RTI
case 0x40: // rti
op->eob = true;
op->type = R_ANAL_OP_TYPE_RET;
op->cycles = 6;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -3;
// Operation: P from Stack, PC from Stack
// stack is on page one and sp is an 8-bit reg: operations must be done like: sp + 0x100
r_strbuf_set (&op->esil, "0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=");
break;
// NOP
case 0xea: // nop
op->type = R_ANAL_OP_TYPE_NOP;
op->cycles = 2;
break;
// LDA
case 0xa9: // lda #$ff
case 0xa5: // lda $ff
case 0xb5: // lda $ff,x
case 0xad: // lda $ffff
case 0xbd: // lda $ffff,x
case 0xb9: // lda $ffff,y
case 0xa1: // lda ($ff,x)
case 0xb1: // lda ($ff),y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
if (data[0] == 0xa9) // immediate mode
r_strbuf_setf (&op->esil, "%s,a,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],a,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDX
case 0xa2: // ldx #$ff
case 0xa6: // ldx $ff
case 0xb6: // ldx $ff,y
case 0xae: // ldx $ffff
case 0xbe: // ldx $ffff,y
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
if (data[0] == 0xa2) // immediate mode
r_strbuf_setf (&op->esil, "%s,x,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],x,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// LDY
case 0xa0: // ldy #$ff
case 0xa4: // ldy $ff
case 0xb4: // ldy $ff,x
case 0xac: // ldy $ffff
case 0xbc: // ldy $ffff,x
op->type = R_ANAL_OP_TYPE_LOAD;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
if (data[0] == 0xa0) // immediate mode
r_strbuf_setf (&op->esil, "%s,y,=", addrbuf);
else r_strbuf_setf (&op->esil, "%s,[1],y,=", addrbuf);
_6502_anal_update_flags (op, _6502_FLAGS_NZ);
break;
// STA
case 0x85: // sta $ff
case 0x95: // sta $ff,x
case 0x8d: // sta $ffff
case 0x9d: // sta $ffff,x
case 0x99: // sta $ffff,y
case 0x81: // sta ($ff,x)
case 0x91: // sta ($ff),y
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize);
r_strbuf_setf (&op->esil, "a,%s,=[1]", addrbuf);
break;
// STX
case 0x86: // stx $ff
case 0x96: // stx $ff,y
case 0x8e: // stx $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y');
r_strbuf_setf (&op->esil, "x,%s,=[1]", addrbuf);
break;
// STY
case 0x84: // sty $ff
case 0x94: // sty $ff,x
case 0x8c: // sty $ffff
op->type = R_ANAL_OP_TYPE_STORE;
_6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x');
r_strbuf_setf (&op->esil, "y,%s,=[1]", addrbuf);
break;
// PHP/PHA
case 0x08: // php
case 0x48: // pha
op->type = R_ANAL_OP_TYPE_PUSH;
op->cycles = 3;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = 1;
_6502_anal_esil_push (op, data[0]);
break;
// PLP,PLA
case 0x28: // plp
case 0x68: // plp
op->type = R_ANAL_OP_TYPE_POP;
op->cycles = 4;
op->stackop = R_ANAL_STACK_INC;
op->stackptr = -1;
_6502_anal_esil_pop (op, data[0]);
break;
// TAX,TYA,...
case 0xaa: // tax
case 0x8a: // txa
case 0xa8: // tay
case 0x98: // tya
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
_6502_anal_esil_mov (op, data[0]);
break;
case 0x9a: // txs
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_SET;
// FIXME: should I get register X a place it here?
// op->stackptr = get_register_x();
_6502_anal_esil_mov (op, data[0]);
break;
case 0xba: // tsx
op->type = R_ANAL_OP_TYPE_MOV;
op->cycles = 2;
op->stackop = R_ANAL_STACK_GET;
_6502_anal_esil_mov (op, data[0]);
break;
}
return op->size;
}
static int set_reg_profile(RAnal *anal) {
char *p =
"=PC pc\n"
"=SP sp\n"
"gpr a .8 0 0\n"
"gpr x .8 1 0\n"
"gpr y .8 2 0\n"
"gpr flags .8 3 0\n"
"gpr C .1 .24 0\n"
"gpr Z .1 .25 0\n"
"gpr I .1 .26 0\n"
"gpr D .1 .27 0\n"
// bit 4 (.28) is NOT a real flag.
// "gpr B .1 .28 0\n"
// bit 5 (.29) is not used
"gpr V .1 .30 0\n"
"gpr N .1 .31 0\n"
"gpr sp .8 4 0\n"
"gpr pc .16 5 0\n";
return r_reg_set_profile_string (anal->reg, p);
}
static int esil_6502_init (RAnalEsil *esil) {
if (esil->anal && esil->anal->reg) { //initial values
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "pc", -1), 0x0000);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "sp", -1), 0xff);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "a", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "x", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "y", -1), 0x00);
r_reg_set_value (esil->anal->reg, r_reg_get (esil->anal->reg, "flags", -1), 0x00);
}
return true;
}
static int esil_6502_fini (RAnalEsil *esil) {
return true;
}
RAnalPlugin r_anal_plugin_6502 = {
.name = "6502",
.desc = "6502/NES analysis plugin",
.license = "LGPL3",
.arch = "6502",
.bits = 8,
.op = &_6502_op,
.set_reg_profile = &set_reg_profile,
.esil = true,
.esil_init = esil_6502_init,
.esil_fini = esil_6502_fini,
};
#ifndef CORELIB
RLibStruct radare_plugin = {
.type = R_LIB_TYPE_ANAL,
.data = &r_anal_plugin_6502,
.version = R2_VERSION
};
#endif
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_182_0 |
crossvul-cpp_data_bad_504_0 | /* radare - LGPL - Copyright 2009-2018 - pancake, maijin */
#include "r_util.h"
#include "r_core.h"
#include "r_anal.h"
static const char *help_msg_a[] = {
"Usage:", "a", "[abdefFghoprxstc] [...]",
"aa", "[?]", "analyze all (fcns + bbs) (aa0 to avoid sub renaming)",
"a8", " [hexpairs]", "analyze bytes",
"ab", "[b] [addr]", "analyze block at given address",
"abb", " [len]", "analyze N basic blocks in [len] (section.size by default)",
"ac", " [cycles]", "analyze which op could be executed in [cycles]",
"ad", "[?]", "analyze data trampoline (wip)",
"ad", " [from] [to]", "analyze data pointers to (from-to)",
"ae", "[?] [expr]", "analyze opcode eval expression (see ao)",
"af", "[?]", "analyze Functions",
"aF", "", "same as above, but using anal.depth=1",
"ag", "[?] [options]", "draw graphs in various formats",
"ah", "[?]", "analysis hints (force opcode size, ...)",
"ai", " [addr]", "address information (show perms, stack, heap, ...)",
"aL", "", "list all asm/anal plugins (e asm.arch=?)",
"an"," [name] [@addr]","show/rename/create whatever flag/function is used at addr",
"ao", "[?] [len]", "analyze Opcodes (or emulate it)",
"aO", "[?] [len]", "Analyze N instructions in M bytes",
"ap", "", "find prelude for current offset",
"ar", "[?]", "like 'dr' but for the esil vm. (registers)",
"as", "[?] [num]", "analyze syscall using dbg.reg",
"av", "[?] [.]", "show vtables",
"ax", "[?]", "manage refs/xrefs (see also afx?)",
NULL
};
static const char *help_msg_aa[] = {
"Usage:", "aa[0*?]", " # see also 'af' and 'afna'",
"aa", " ", "alias for 'af@@ sym.*;af@entry0;afva'", //;.afna @@ fcn.*'",
"aa*", "", "analyze all flags starting with sym. (af @@ sym.*)",
"aaa", "[?]", "autoname functions after aa (see afna)",
"aab", "", "aab across bin.sections.rx",
"aac", " [len]", "analyze function calls (af @@ `pi len~call[1]`)",
"aac*", " [len]", "flag function calls without performing a complete analysis",
"aad", " [len]", "analyze data references to code",
"aae", " [len] ([addr])", "analyze references with ESIL (optionally to address)",
"aaE", "", "run aef on all functions (same as aef @@f)",
"aaf", " ", "analyze all functions (e anal.hasnext=1;afr @@c:isq)",
"aai", "[j]", "show info of all analysis parameters",
"aan", "", "autoname functions that either start with fcn.* or sym.func.*",
"aang", "", "find function and symbol names from golang binaries",
"aap", "", "find and analyze function preludes",
"aar", "[?] [len]", "analyze len bytes of instructions for references",
"aas", " [len]", "analyze symbols (af @@= `isq~[0]`)",
"aat", " [len]", "analyze all consecutive functions in section",
"aaT", " [len]", "analyze code after trap-sleds",
"aau", " [len]", "list mem areas (larger than len bytes) not covered by functions",
"aav", " [sat]", "find values referencing a specific section or map",
NULL
};
static const char *help_msg_aar[] = {
"Usage:", "aar", "[j*] [sz] # search and analyze xrefs",
"aar", " [sz]", "analyze xrefs in current section or sz bytes of code",
"aar*", " [sz]", "list found xrefs in radare commands format",
"aarj", " [sz]", "list found xrefs in JSON format",
NULL
};
static const char *help_msg_ab[] = {
"Usage:", "ab", "",
"ab", " [addr]", "show basic block information at given address",
"abb", " [length]", "analyze N bytes and extract basic blocks",
"abj", " [addr]", "display basic block information in JSON (alias to afbj)",
"abx", " [hexpair-bytes]", "analyze N bytes",
"abt[?]", " [addr] [num]", "find num paths from current offset to addr",
NULL
};
static const char *help_msg_abt[] = {
"Usage:", "abt", "[addr] [num] # find num paths from current offset to addr",
"abt", " [addr] [num]", "find num paths from current offset to addr",
"abtj", " [addr] [num]", "display paths in JSON",
NULL
};
static const char *help_msg_ad[] = {
"Usage:", "ad", "[kt] [...]",
"ad", " [N] [D]", "analyze N data words at D depth",
"ad4", " [N] [D]", "analyze N data words at D depth (asm.bits=32)",
"ad8", " [N] [D]", "analyze N data words at D depth (asm.bits=64)",
"adf", "", "analyze data in function (use like .adf @@=`afl~[0]`",
"adfg", "", "analyze data in function gaps",
"adt", "", "analyze data trampolines (wip)",
"adk", "", "analyze data kind (code, text, data, invalid, ...)",
NULL
};
static const char *help_msg_ae[] = {
"Usage:", "ae[idesr?] [arg]", "ESIL code emulation",
"ae", " [expr]", "evaluate ESIL expression",
"ae?", "", "show this help",
"ae??", "", "show ESIL help",
"ae[aA]", "[f] [count]", "analyse esil accesses (regs, mem..)",
"aec", "[?]", "continue until ^C",
"aecs", "", "continue until syscall",
"aecc", "", "continue until call",
"aecu", " [addr]", "continue until address",
"aecue", " [esil]", "continue until esil expression match",
"aef", " [addr]", "emulate function",
"aefa", " [addr]", "emulate function to find out args in given or current offset",
"aei", "", "initialize ESIL VM state (aei- to deinitialize)",
"aeim", " [addr] [size] [name]", "initialize ESIL VM stack (aeim- remove)",
"aeip", "", "initialize ESIL program counter to curseek",
"aek", " [query]", "perform sdb query on ESIL.info",
"aek-", "", "resets the ESIL.info sdb instance",
"aeli", "", "list loaded ESIL interrupts",
"aeli", " [file]", "load ESIL interrupts from shared object",
"aelir", " [interrupt number]", "remove ESIL interrupt and free it if needed",
"aep", "[?] [addr]", "manage esil pin hooks",
"aepc", " [addr]", "change esil PC to this address",
"aer", " [..]", "handle ESIL registers like 'ar' or 'dr' does",
"aets", "[?]", "ESIL Trace session",
"aes", "", "perform emulated debugger step",
"aesp", " [X] [N]", "evaluate N instr from offset X",
"aesb", "", "step back",
"aeso", " ", "step over",
"aesu", " [addr]", "step until given address",
"aesue", " [esil]", "step until esil expression match",
"aetr", "[esil]", "Convert an ESIL Expression to REIL",
"aex", " [hex]", "evaluate opcode expression",
NULL
};
static const char *help_detail_ae[] = {
"Examples:", "ESIL", " examples and documentation",
"+=", "", "A+=B => B,A,+=",
"+", "", "A=A+B => B,A,+,A,=",
"++", "", "increment, 2,A,++ == 3 (see rsi,--=[1], ... )",
"--", "", "decrement, 2,A,-- == 1",
"*=", "", "A*=B => B,A,*=",
"/=", "", "A/=B => B,A,/=",
"%=", "", "A%=B => B,A,%=",
"&=", "", "and ax, bx => bx,ax,&=",
"|", "", "or r0, r1, r2 => r2,r1,|,r0,=",
"!=", "", "negate all bits",
"^=", "", "xor ax, bx => bx,ax,^=",
"", "[]", "mov eax,[eax] => eax,[],eax,=",
"=", "[]", "mov [eax+3], 1 => 1,3,eax,+,=[]",
"=", "[1]", "mov byte[eax],1 => 1,eax,=[1]",
"=", "[8]", "mov [rax],1 => 1,rax,=[8]",
"[]", "", "peek from random position",
"[*]", "", "peek some from random position",
"=", "[*]", "poke some at random position",
"$", "", "int 0x80 => 0x80,$",
"$$", "", "simulate a hardware trap",
"==", "", "pops twice, compare and update esil flags",
"<", "", "compare for smaller",
"<=", "", "compare for smaller or equal",
">", "", "compare for bigger",
">=", "", "compare bigger for or equal",
">>=", "", "shr ax, bx => bx,ax,>>= # shift right",
"<<=", "", "shl ax, bx => bx,ax,<<= # shift left",
">>>=", "", "ror ax, bx => bx,ax,>>>= # rotate right",
"<<<=", "", "rol ax, bx => bx,ax,<<<= # rotate left",
"?{", "", "if popped value != 0 run the block until }",
"POP", "", "drops last element in the esil stack",
"DUP", "", "duplicate last value in stack",
"NUM", "", "evaluate last item in stack to number",
"PICK", "", "pick Nth element in stack",
"RPICK", "", "pick Nth element in reversed stack",
"SWAP", "", "swap last two values in stack",
"TRAP", "", "stop execution",
"BITS", "", "16,BITS # change bits, useful for arm/thumb",
"TODO", "", "the instruction is not yet esilized",
"STACK", "", "show contents of stack",
"CLEAR", "", "clears the esil stack",
"REPEAT", "", "repeat n times",
"BREAK", "", "terminates the string parsing",
"GOTO", "", "jump to the Nth word popped from the stack",
NULL
};
static const char *help_msg_aea[] = {
"Examples:", "aea", " show regs used in a range",
"aea", " [ops]", "Show regs used in N instructions (all,read,{no,}written,memreads,memwrites)",
"aea*", " [ops]", "Create mem.* flags for memory accesses",
"aeaf", "", "Show regs used in current function",
"aear", " [ops]", "Show regs read in N instructions",
"aeaw", " [ops]", "Show regs written in N instructions",
"aean", " [ops]", "Show regs not written in N instructions",
"aeaj", " [ops]", "Show aea output in JSON format",
"aeA", " [len]", "Show regs used in N bytes (subcommands are the same)",
NULL
};
static const char *help_msg_aec[] = {
"Examples:", "aec", " continue until ^c",
"aec", "", "Continue until exception",
"aecs", "", "Continue until syscall",
"aecc", "", "Continue until call",
"aecu", "[addr]", "Continue until address",
"aecue", "[addr]", "Continue until esil expression",
NULL
};
static const char *help_msg_aep[] = {
"Usage:", "aep[-c] ", " [...]",
"aepc", " [addr]", "change program counter for esil",
"aep", "-[addr]", "remove pin",
"aep", " [name] @ [addr]", "set pin",
"aep", "", "list pins",
NULL
};
static const char *help_msg_aets[] = {
"Usage:", "aets ", " [...]",
"aets", "", "List all ESIL trace sessions",
"aets+", "", "Add ESIL trace session",
NULL
};
static const char *help_msg_af[] = {
"Usage:", "af", "",
"af", " ([name]) ([addr])", "analyze functions (start at addr or $$)",
"afr", " ([name]) ([addr])", "analyze functions recursively",
"af+", " addr name [type] [diff]", "hand craft a function (requires afb+)",
"af-", " [addr]", "clean all function analysis data (or function at addr)",
"afb+", " fcnA bbA sz [j] [f] ([t]( [d]))", "add bb to function @ fcnaddr",
"afb", "[?] [addr]", "List basic blocks of given function",
"afB", " 16", "set current function as thumb (change asm.bits)",
"afC[lc]", " ([addr])@[addr]", "calculate the Cycles (afC) or Cyclomatic Complexity (afCc)",
"afc", "[?] type @[addr]", "set calling convention for function",
"afd", "[addr]","show function + delta for given offset",
"aff", "", "re-adjust function boundaries to fit",
"afF", "[1|0|]", "fold/unfold/toggle",
"afi", " [addr|fcn.name]", "show function(s) information (verbose afl)",
"afl", "[?] [ls*] [fcn name]", "list functions (addr, size, bbs, name) (see afll)",
"afm", " name", "merge two functions",
"afM", " name", "print functions map",
"afn", "[?] name [addr]", "rename name for function at address (change flag too)",
"afna", "", "suggest automatic name for current offset",
"afo", " [fcn.name]", "show address for the function named like this",
"afs", " [addr] [fcnsign]", "get/set function signature at current address",
"afS", "[stack_size]", "set stack frame size for function at current address",
"aft", "[?]", "type matching, type propagation",
"afu", " [addr]", "resize and analyze function from current address until addr",
"afv[bsra]", "?", "manipulate args, registers and variables in function",
"afx", "", "list function references",
NULL
};
static const char *help_msg_afb[] = {
"Usage:", "afb", " List basic blocks of given function",
".afbr-", "", "Set breakpoint on every return address of the function",
".afbr-*", "", "Remove breakpoint on every return address of the function",
"afb", " [addr]", "list basic blocks of function",
"afb.", " [addr]", "show info of current basic block",
"afb+", " fcn_at bbat bbsz [jump] [fail] ([type] ([diff]))", "add basic block by hand",
"afbr", "", "Show addresses of instructions which leave the function",
"afbi", "", "print current basic block information",
"afbj", " [addr]", "show basic blocks information in json",
"afbe", " bbfrom bbto", "add basic-block edge for switch-cases",
"afB", " [bits]", "define asm.bits for the given function",
"afbc", " [addr] [color(ut32)]", "set a color for the bb at a given address",
NULL
};
static const char *help_msg_afc[] = {
"Usage:", "afc[agl?]", "",
"afc", " convention", "Manually set calling convention for current function",
"afc", "", "Show Calling convention for the Current function",
"afcr", "[j]", "Show register usage for the current function",
"afca", "", "Analyse function for finding the current calling convention",
"afcf", " [name]", "Prints return type function(arg1, arg2...)",
"afcl", "", "List all available calling conventions",
"afco", " path", "Open Calling Convention sdb profile from given path",
NULL
};
static const char *help_msg_afC[] = {
"Usage:", "afC", " [addr]",
"afC", "", "function cycles cost",
"afCc", "", "cyclomatic complexity",
"afCl", "", "loop count (backward jumps)",
NULL
};
static const char *help_msg_afi[] = {
"Usage:", "afi[jlp*]", " <addr>",
"afi", "", "show information of the function",
"afi.", "", "show function name in current offset",
"afi*", "", "function, variables and arguments",
"afij", "", "function info in json format",
"afil", "", "verbose function info",
"afip", "", "show whether the function is pure or not",
NULL
};
static const char *help_msg_afl[] = {
"Usage:", "afl", " List all functions",
"afl", "", "list functions",
"afl+", "", "display sum all function sizes",
"aflc", "", "count of functions",
"aflj", "", "list functions in json",
"afll", "", "list functions in verbose mode",
"afllj", "", "list functions in verbose mode (alias to aflj)",
"aflq", "", "list functions in quiet mode",
"aflqj", "", "list functions in json quiet mode",
"afls", "", "sort function list by address",
NULL
};
static const char *help_msg_afll[] = {
"Usage:", "", " List functions in verbose mode",
"", "", "",
"Table fields:", "", "",
"", "", "",
"address", "", "start address",
"size", "", "function size (realsize)",
"nbbs", "", "number of basic blocks",
"edges", "", "number of edges between basic blocks",
"cc", "", "cyclomatic complexity ( cc = edges - blocks + 2 * exit_blocks)",
"cost", "", "cyclomatic cost",
"min bound", "", "minimal address",
"range", "", "function size",
"max bound", "", "maximal address",
"calls", "", "number of caller functions",
"locals", "", "number of local variables",
"args", "", "number of function arguments",
"xref", "", "number of cross references",
"frame", "", "function stack size",
"name", "", "function name",
NULL
};
static const char *help_msg_afn[] = {
"Usage:", "afn[sa]", " Analyze function names",
"afn", " [name]", "rename the function",
"afna", "", "construct a function name for the current offset",
"afns", "", "list all strings associated with the current function",
NULL
};
static const char *help_msg_aft[] = {
"Usage:", "aft[a|m]", "",
"afta", "", "setup memory and analyse do type matching analysis for all functions",
"aftm", "", "type matching analysis for current function",
NULL
};
static const char *help_msg_afv[] = {
"Usage:", "afv","[rbs]",
"afvr", "[?]", "manipulate register based arguments",
"afvb", "[?]", "manipulate bp based arguments/locals",
"afvs", "[?]", "manipulate sp based arguments/locals",
"afv*", "", "output r2 command to add args/locals to flagspace",
"afvR", " [varname]", "list addresses where vars are accessed (READ)",
"afvW", " [varname]", "list addresses where vars are accessed (WRITE)",
"afva", "", "analyze function arguments/locals",
"afvd", " name", "output r2 command for displaying the value of args/locals in the debugger",
"afvn", " [new_name] ([old_name])", "rename argument/local",
"afvt", " [name] [new_type]", "change type for given argument/local",
"afv-", "([name])", "remove all or given var",
NULL
};
static const char *help_msg_afvb[] = {
"Usage:", "afvb", " [idx] [name] ([type])",
"afvb", "", "list base pointer based arguments, locals",
"afvb*", "", "same as afvb but in r2 commands",
"afvb", " [idx] [name] ([type])", "define base pointer based arguments, locals",
"afvbj", "", "return list of base pointer based arguments, locals in JSON format",
"afvb-", " [name]", "delete argument/locals at the given name",
"afvbg", " [idx] [addr]", "define var get reference",
"afvbs", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_afvr[] = {
"Usage:", "afvr", " [reg] [type] [name]",
"afvr", "", "list register based arguments",
"afvr*", "", "same as afvr but in r2 commands",
"afvr", " [reg] [name] ([type])", "define register arguments",
"afvrj", "", "return list of register arguments in JSON format",
"afvr-", " [name]", "delete register arguments at the given index",
"afvrg", " [reg] [addr]", "define argument get reference",
"afvrs", " [reg] [addr]", "define argument set reference",
NULL
};
static const char *help_msg_afvs[] = {
"Usage:", "afvs", " [idx] [type] [name]",
"afvs", "", "list stack based arguments and locals",
"afvs*", "", "same as afvs but in r2 commands",
"afvs", " [idx] [name] [type]", "define stack based arguments,locals",
"afvsj", "", "return list of stack based arguments and locals in JSON format",
"afvs-", " [name]", "delete stack based argument or locals with the given name",
"afvsg", " [idx] [addr]", "define var get reference",
"afvss", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_ag[] = {
"Usage:", "ag<graphtype><format> [addr]", "",
"Graph commands:", "", "",
"aga", "[format]", "Data references graph",
"agA", "[format]", "Global data references graph",
"agc", "[format]", "Function callgraph",
"agC", "[format]", "Global callgraph",
"agd", "[format] [fcn addr]", "Diff graph",
"agf", "[format]", "Basic blocks function graph",
"agi", "[format]", "Imports graph",
"agr", "[format]", "References graph",
"agR", "[format]", "Global references graph",
"agx", "[format]", "Cross references graph",
"agg", "[format]", "Custom graph",
"ag-", "", "Clear the custom graph",
"agn", "[?] title body", "Add a node to the custom graph",
"age", "[?] title1 title2", "Add an edge to the custom graph",
"","","",
"Output formats:", "", "",
"<blank>", "", "Ascii art",
"*", "", "r2 commands",
"d", "", "Graphviz dot",
"g", "", "Graph Modelling Language (gml)",
"j", "", "json ('J' for formatted disassembly)",
"k", "", "SDB key-value",
"t", "", "Tiny ascii art",
"v", "", "Interactive ascii art",
"w", " [path]", "Write to path or display graph image (see graph.gv.format and graph.web)",
NULL
};
static const char *help_msg_age[] = {
"Usage:", "age [title1] [title2]", "",
"Examples:", "", "",
"age", " title1 title2", "Add an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age", " \"title1 with spaces\" title2", "Add an edge from node \"title1 with spaces\" to node \"title2\"",
"age-", " title1 title2", "Remove an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age?", "", "Show this help",
NULL
};
static const char *help_msg_agn[] = {
"Usage:", "agn [title] [body]", "",
"Examples:", "", "",
"agn", " title1 body1", "Add a node with title \"title1\" and body \"body1\"",
"agn", " \"title with space\" \"body with space\"", "Add a node with spaces in the title and in the body",
"agn", " title1 base64:Ym9keTE=", "Add a node with the body specified as base64",
"agn-", " title1", "Remove a node with title \"title1\"",
"agn?", "", "Show this help",
NULL
};
static const char *help_msg_ah[] = {
"Usage:", "ah[lba-]", "Analysis Hints",
"ah?", "", "show this help",
"ah?", " offset", "show hint of given offset",
"ah", "", "list hints in human-readable format",
"ah.", "", "list hints in human-readable format from current offset",
"ah-", "", "remove all hints",
"ah-", " offset [size]", "remove hints at given offset",
"ah*", " offset", "list hints in radare commands format",
"aha", " ppc 51", "set arch for a range of N bytes",
"ahb", " 16 @ $$", "force 16bit for current instruction",
"ahc", " 0x804804", "override call/jump address",
"ahe", " 3,eax,+=", "set vm analysis string",
"ahf", " 0x804840", "override fallback address for call",
"ahh", " 0x804840", "highlight this adrress offset in disasm",
"ahi", "[?] 10", "define numeric base for immediates (1, 8, 10, 16, s)",
"ahj", "", "list hints in JSON",
"aho", " foo a0,33", "replace opcode string",
"ahp", " addr", "set pointer hint",
"ahr", " val", "set hint for return value of a function",
"ahs", " 4", "set opcode size=4",
"ahS", " jz", "set asm.syntax=jz for this opcode",
NULL
};
static const char *help_msg_ahi[] = {
"Usage:", "ahi [sbodh] [@ offset]", " Define numeric base",
"ahi", " [base]", "set numeric base (1, 2, 8, 10, 16)",
"ahi", " b", "set base to binary (2)",
"ahi", " d", "set base to decimal (10)",
"ahi", " h", "set base to hexadecimal (16)",
"ahi", " o", "set base to octal (8)",
"ahi", " p", "set base to htons(port) (3)",
"ahi", " i", "set base to IP address (32)",
"ahi", " S", "set base to syscall (80)",
"ahi", " s", "set base to string (1)",
NULL
};
static const char *help_msg_ao[] = {
"Usage:", "ao[e?] [len]", "Analyze Opcodes",
"aoj", " N", "display opcode analysis information in JSON for N opcodes",
"aoe", " N", "display esil form for N opcodes",
"aor", " N", "display reil form for N opcodes",
"aos", " N", "display size of N opcodes",
"aom", " [id]", "list current or all mnemonics for current arch",
"aod", " [mnemonic]", "describe opcode for asm.arch",
"aoda", "", "show all mnemonic descriptions",
"ao", " 5", "display opcode analysis of 5 opcodes",
"ao*", "", "display opcode in r commands",
NULL
};
static const char *help_msg_ar[] = {
"Usage: ar", "", "# Analysis Registers",
"ar", "", "Show 'gpr' registers",
"ar0", "", "Reset register arenas to 0",
"ara", "[?]", "Manage register arenas",
"arA", "", "Show values of function argument calls (A0, A1, A2, ..)",
"ar", " 16", "Show 16 bit registers",
"ar", " 32", "Show 32 bit registers",
"ar", " all", "Show all bit registers",
"ar", " <type>", "Show all registers of given type",
"arC", "", "Display register profile comments",
"arr", "", "Show register references (telescoping)",
"arrj", "", "Show register references (telescoping) in JSON format",
"ar=", "([size])(:[regs])", "Show register values in columns",
"ar?", " <reg>", "Show register value",
"arb", " <type>", "Display hexdump of the given arena",
"arc", " <name>", "Conditional flag registers",
"ard", " <name>", "Show only different registers",
"arn", " <regalias>", "Get regname for pc,sp,bp,a0-3,zf,cf,of,sg",
"aro", "", "Show old (previous) register values",
"arp", "[?] <file>", "Load register profile from file",
"ars", "", "Stack register state",
"art", "", "List all register types",
"arw", " <hexnum>", "Set contents of the register arena",
".ar*", "", "Import register values as flags",
".ar-", "", "Unflag all registers",
NULL
};
static const char *help_msg_ara[] = {
"Usage:", "ara[+-s]", "Register Arena Push/Pop/Swap",
"ara", "", "show all register arenas allocated",
"ara", "+", "push a new register arena for each type",
"ara", "-", "pop last register arena",
"aras", "", "swap last two register arenas",
NULL
};
static const char *help_msg_arw[] = {
"Usage:", "arw ", "# Set contents of the register arena",
"arw", " <hexnum>", "Set contents of the register arena",
NULL
};
static const char *help_msg_as[] = {
"Usage: as[ljk?]", "", "syscall name <-> number utility",
"as", "", "show current syscall and arguments",
"as", " 4", "show syscall 4 based on asm.os and current regs/mem",
"asc[a]", " 4", "dump syscall info in .asm or .h",
"asf", " [k[=[v]]]", "list/set/unset pf function signatures (see fcnsign)",
"asj", "", "list of syscalls in JSON",
"asl", "", "list of syscalls by asm.os and asm.arch",
"asl", " close", "returns the syscall number for close",
"asl", " 4", "returns the name of the syscall number 4",
"ask", " [query]", "perform syscall/ queries",
NULL
};
static const char *help_msg_av[] = {
"Usage:", "av[?jr*]", " C++ vtables and RTTI",
"av", "", "search for vtables in data sections and show results",
"avj", "", "like av, but as json",
"av*", "", "like av, but as r2 commands",
"avr", "[j@addr]", "try to parse RTTI at vtable addr (see anal.cpp.abi)",
"avra", "[j]", "search for vtables and try to parse RTTI at each of them",
"avrD", " [classname]", "demangle a class name from RTTI",
NULL
};
static const char *help_msg_ax[] = {
"Usage:", "ax[?d-l*]", " # see also 'afx?'",
"ax", "", "list refs",
"ax*", "", "output radare commands",
"ax", " addr [at]", "add code ref pointing to addr (from curseek)",
"ax-", " [at]", "clean all refs/refs from addr",
"ax-*", "", "clean all refs/refs",
"axc", " addr [at]", "add generic code ref",
"axC", " addr [at]", "add code call ref",
"axg", " [addr]", "show xrefs graph to reach current function",
"axg*", " [addr]", "show xrefs graph to given address, use .axg*;aggv",
"axgj", " [addr]", "show xrefs graph to reach current function in json format",
"axd", " addr [at]", "add data ref",
"axq", "", "list refs in quiet/human-readable format",
"axj", "", "list refs in json format",
"axF", " [flg-glob]", "find data/code references of flags",
"axt", " [addr]", "find data/code references to this address",
"axf", " [addr]", "find data/code references from this address",
"axff", " [addr]", "find data/code references from this function",
"axs", " addr [at]", "add string ref",
NULL
};
static void cmd_anal_init(RCore *core) {
DEFINE_CMD_DESCRIPTOR (core, a);
DEFINE_CMD_DESCRIPTOR (core, aa);
DEFINE_CMD_DESCRIPTOR (core, aar);
DEFINE_CMD_DESCRIPTOR (core, ab);
DEFINE_CMD_DESCRIPTOR (core, ad);
DEFINE_CMD_DESCRIPTOR (core, ae);
DEFINE_CMD_DESCRIPTOR (core, aea);
DEFINE_CMD_DESCRIPTOR (core, aec);
DEFINE_CMD_DESCRIPTOR (core, aep);
DEFINE_CMD_DESCRIPTOR (core, af);
DEFINE_CMD_DESCRIPTOR (core, afb);
DEFINE_CMD_DESCRIPTOR (core, afc);
DEFINE_CMD_DESCRIPTOR (core, afC);
DEFINE_CMD_DESCRIPTOR (core, afi);
DEFINE_CMD_DESCRIPTOR (core, afl);
DEFINE_CMD_DESCRIPTOR (core, afll);
DEFINE_CMD_DESCRIPTOR (core, afn);
DEFINE_CMD_DESCRIPTOR (core, aft);
DEFINE_CMD_DESCRIPTOR (core, afv);
DEFINE_CMD_DESCRIPTOR (core, afvb);
DEFINE_CMD_DESCRIPTOR (core, afvr);
DEFINE_CMD_DESCRIPTOR (core, afvs);
DEFINE_CMD_DESCRIPTOR (core, ag);
DEFINE_CMD_DESCRIPTOR (core, age);
DEFINE_CMD_DESCRIPTOR (core, agn);
DEFINE_CMD_DESCRIPTOR (core, ah);
DEFINE_CMD_DESCRIPTOR (core, ahi);
DEFINE_CMD_DESCRIPTOR (core, ao);
DEFINE_CMD_DESCRIPTOR (core, ar);
DEFINE_CMD_DESCRIPTOR (core, ara);
DEFINE_CMD_DESCRIPTOR (core, arw);
DEFINE_CMD_DESCRIPTOR (core, as);
DEFINE_CMD_DESCRIPTOR (core, ax);
}
static int cmpaddr (const void *_a, const void *_b) {
const RAnalFunction *a = _a, *b = _b;
return a->addr - b->addr;
}
static int listOpDescriptions(void *_core, const char *k, const char *v) {
r_cons_printf ("%s=%s\n", k, v);
return 1;
}
/* better aac for windows-x86-32 */
#define JAYRO_03 0
#if JAYRO_03
static bool anal_is_bad_call(RCore *core, ut64 from, ut64 to, ut64 addr, ut8 *buf, int bufi) {
ut64 align = R_ABS (addr % PE_ALIGN);
ut32 call_bytes;
// XXX this is x86 specific
if (align == 0) {
call_bytes = (ut32)((ut8*)buf)[bufi + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi];
} else {
call_bytes = (ut32)((ut8*)buf)[bufi - align + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi - align];
}
if (call_bytes >= from && call_bytes <= to) {
return true;
}
call_bytes = (ut32)((ut8*)buf)[bufi + 4] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 3] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1];
call_bytes += addr + 5;
if (call_bytes >= from && call_bytes <= to) {
return false;
}
return false;
}
#endif
static bool type_cmd_afta (RCore *core, RAnalFunction *fcn) {
RListIter *it;
ut64 seek;
const char *io_cache_key = "io.pcache.write";
bool io_cache = r_config_get_i (core->config, io_cache_key);
if (r_config_get_i (core->config, "cfg.debug")) {
eprintf ("TOFIX: afta can't run in debugger mode.\n");
return false;
}
if (!io_cache) {
// XXX. we shouldnt need this, but it breaks 'r2 -c aaa -w ls'
r_config_set_i (core->config, io_cache_key, true);
}
seek = core->offset;
r_core_cmd0 (core, "aei");
r_core_cmd0 (core, "aeim");
r_reg_arena_push (core->anal->reg);
// Iterating Reverse so that we get function in top-bottom call order
r_list_foreach_prev (core->anal->fcns, it, fcn) {
int ret = r_core_seek (core, fcn->addr, true);
if (!ret) {
continue;
}
r_anal_esil_set_pc (core->anal->esil, fcn->addr);
r_core_anal_type_match (core, fcn);
if (r_cons_is_breaked ()) {
break;
}
}
r_core_cmd0 (core, "aeim-");
r_core_cmd0 (core, "aei-");
r_core_seek (core, seek, true);
r_reg_arena_pop (core->anal->reg);
r_config_set_i (core->config, io_cache_key, io_cache);
return true;
}
static void type_cmd(RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (!fcn && *input != '?' && *input != 'a') {
eprintf ("cant find function here\n");
return;
}
ut64 seek;
r_cons_break_push (NULL, NULL);
switch (*input) {
case 'a': // "afta"
type_cmd_afta (core, fcn);
break;
case 'm': // "aftm"
seek = core->offset;
r_anal_esil_set_pc (core->anal->esil, fcn? fcn->addr: core->offset);
r_core_anal_type_match (core, fcn);
r_core_seek (core, seek, true);
break;
case '?':
r_core_cmd_help (core, help_msg_aft);
break;
}
r_cons_break_pop ();
}
static int cc_print(void *p, const char *k, const char *v) {
if (!strcmp (v, "cc")) {
r_cons_println (k);
}
return 1;
}
static void find_refs(RCore *core, const char *glob) {
char cmd[128];
ut64 curseek = core->offset;
while (*glob == ' ') glob++;
if (!*glob) {
glob = "str.";
}
if (*glob == '?') {
eprintf ("Usage: axF [flag-str-filter]\n");
return;
}
eprintf ("Finding references of flags matching '%s'...\n", glob);
snprintf (cmd, sizeof (cmd) - 1, ".(findstref) @@= `f~%s[0]`", glob);
r_core_cmd0 (core, "(findstref,f here=$$,s entry0,/r here,f-here)");
r_core_cmd0 (core, cmd);
r_core_cmd0 (core, "(-findstref)");
r_core_seek (core, curseek, 1);
}
/* set flags for every function */
static void flag_every_function(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
r_flag_space_push (core->flags, "functions");
r_list_foreach (core->anal->fcns, iter, fcn) {
r_flag_set (core->flags, fcn->name,
fcn->addr, r_anal_fcn_size (fcn));
}
r_flag_space_pop (core->flags);
}
static void var_help(RCore *core, char ch) {
switch (ch) {
case 'b':
r_core_cmd_help (core, help_msg_afvb);
break;
case 's':
r_core_cmd_help (core, help_msg_afvs);
break;
case 'r':
r_core_cmd_help (core, help_msg_afvr);
break;
case '?':
r_core_cmd_help (core, help_msg_afv);
break;
default:
eprintf ("See afv?, afvb?, afvr? and afvs?\n");
}
}
static void var_accesses_list(RAnal *a, RAnalFunction *fcn, int delta, const char *typestr) {
const char *var_local = sdb_fmt ("var.0x%"PFMT64x".%d.%d.%s",
fcn->addr, 1, delta, typestr);
const char *xss = sdb_const_get (a->sdb_fcns, var_local, 0);
if (xss && *xss) {
r_cons_printf ("%s\n", xss);
} else {
r_cons_newline ();
}
}
static void list_vars(RCore *core, RAnalFunction *fcn, int type, const char *name) {
RAnalVar *var;
RListIter *iter;
RList *list = r_anal_var_all_list (core->anal, fcn);
if (type == '*') {
const char *bp = r_reg_get_name (core->anal->reg, R_REG_NAME_BP);
r_cons_printf ("f-fcnvar*\n");
r_list_foreach (list, iter, var) {
r_cons_printf ("f fcnvar.%s @ %s%s%d\n", var->name, bp,
var->delta>=0? "+":"", var->delta);
}
return;
}
if (type != 'W' && type != 'R') {
return;
}
const char *typestr = type == 'R'?"reads":"writes";
if (name && *name) {
var = r_anal_var_get_byname (core->anal, fcn->addr, name);
if (var) {
r_cons_printf ("%10s ", var->name);
var_accesses_list (core->anal, fcn, var->delta, typestr);
}
} else {
r_list_foreach (list, iter, var) {
r_cons_printf ("%10s ", var->name);
var_accesses_list (core->anal, fcn, var->delta, typestr);
}
}
}
static int cmd_an(RCore *core, bool use_json, const char *name)
{
ut64 off = core->offset;
RAnalOp op;
char *q = NULL;
ut64 tgt_addr = UT64_MAX;
if (use_json) {
r_cons_print ("[");
}
r_anal_op (core->anal, &op, off,
core->block + off - core->offset, 32, R_ANAL_OP_MASK_BASIC);
tgt_addr = op.jump != UT64_MAX ? op.jump : op.ptr;
if (op.var) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, off, 0);
if (fcn) {
RAnalVar *bar = r_anal_var_get_byname (core->anal, fcn->addr, op.var->name);
if (bar) {
if (name) {
r_anal_var_rename (core->anal, fcn->addr, bar->scope,
bar->kind, bar->name, name, true);
} else if (!use_json) {
r_cons_println (bar->name);
} else {
r_cons_printf ("{\"type\":\"var\",\"name\":\"%s\"}",
bar->name);
}
} else {
eprintf ("Cannot find variable\n");
}
} else {
eprintf ("Cannot find function\n");
}
} else if (tgt_addr != UT64_MAX) {
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, tgt_addr, R_ANAL_FCN_TYPE_NULL);
RFlagItem *f = r_flag_get_i (core->flags, tgt_addr);
if (fcn) {
if (name) {
q = r_str_newf ("afn %s 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_println (fcn->name);
} else {
r_cons_printf ("{\"type\":\"function\",\"name\":\"%s\"}",
fcn->name);
}
} else if (f) {
if (name) {
q = r_str_newf ("fr %s %s", f->name, name);
} else if (!use_json) {
r_cons_println (f->name);
} else {
r_cons_printf ("{\"type\":\"flag\",\"name\":\"%s\"}",
f->name);
}
} else {
if (name) {
q = r_str_newf ("f %s @ 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_printf ("0x%" PFMT64x "\n", tgt_addr);
} else {
r_cons_printf ("{\"type\":\"address\",\"offset\":"
"%" PFMT64u "}", tgt_addr);
}
}
}
if (use_json) {
r_cons_print ("]\n");
}
if (q) {
r_core_cmd0 (core, q);
free (q);
}
r_anal_op_fini (&op);
return 0;
}
static int var_cmd(RCore *core, const char *str) {
char *p, *ostr;
int delta, type = *str, res = true;
RAnalVar *v1;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ostr = p = NULL;
if (!str[0]) {
// "afv"
if (fcn) {
r_core_cmd0 (core, "afvs");
r_core_cmd0 (core, "afvb");
r_core_cmd0 (core, "afvr");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (str[0] == 'j') {
// "afvj"
if (fcn) {
r_cons_printf ("{\"sp\":");
r_core_cmd0 (core, "afvsj");
r_cons_printf (",\"bp\":");
r_core_cmd0 (core, "afvbj");
r_cons_printf (",\"reg\":");
r_core_cmd0 (core, "afvrj");
r_cons_printf ("}\n");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (!str[0] || str[1] == '?'|| str[0] == '?') {
var_help (core, *str);
return res;
}
if (!fcn) {
eprintf ("Cannot find function in 0x%08"PFMT64x"\n", core->offset);
return false;
}
ostr = p = strdup (str);
/* Variable access CFvs = set fun var */
switch (str[0]) {
case '-':
// "afv"
if (fcn) {
r_core_cmdf (core, "afvs-%s", str + 1);
r_core_cmdf (core, "afvb-%s", str + 1);
r_core_cmdf (core, "afvr-%s", str + 1);
return true;
}
eprintf ("Cannot find function\n");
return false;
case 'R': // "afvR"
case 'W': // "afvW"
case '*': // "afv*"
{
char *name = r_str_trim_head (strchr (ostr, ' '));
list_vars (core, fcn, str[0], name);
return true;
}
case 'a': // "afva"
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_REG);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_BPV);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_SPV);
r_core_recover_vars (core, fcn, false);
free (p);
return true;
case 'n':
if (str[1]) { // "afvn"
RAnalOp *op = r_core_anal_op (core, core->offset, R_ANAL_OP_MASK_BASIC);
char *new_name = r_str_trim_head (strchr (ostr, ' '));
if (!new_name) {
r_anal_op_free (op);
free (ostr);
return false;
}
char *old_name = strchr (new_name, ' ');
if (!old_name) {
if (op && op->var) {
old_name = op->var->name;
} else {
eprintf ("Cannot find var @ 0x%08"PFMT64x"\n", core->offset);
r_anal_op_free (op);
free (ostr);
return false;
}
} else {
*old_name++ = 0;
r_str_trim (old_name);
}
v1 = r_anal_var_get_byname (core->anal, fcn->addr, old_name);
if (v1) {
r_anal_var_rename (core->anal, fcn->addr, R_ANAL_VAR_SCOPE_LOCAL,
v1->kind, old_name, new_name, true);
r_anal_var_free (v1);
} else {
eprintf ("Cant find var by name\n");
}
r_anal_op_free (op);
free (ostr);
} else {
RListIter *iter;
RAnalVar *v;
RList *list = r_anal_var_all_list (core->anal, fcn);
r_list_foreach (list, iter, v) {
r_cons_printf ("%s\n", v->name);
}
}
return true;
case 'd': // "afvd"
if (str[1]) {
p = r_str_trim (strchr (ostr, ' '));
if (!p) {
free (ostr);
return false;
}
v1 = r_anal_var_get_byname (core->anal, fcn->addr, p);
if (!v1) {
free (ostr);
return false;
}
r_anal_var_display (core->anal, v1->delta, v1->kind, v1->type);
r_anal_var_free (v1);
free (ostr);
} else {
RListIter *iter;
RAnalVar *p;
RList *list = r_anal_var_all_list (core->anal, fcn);
r_list_foreach (list, iter, p) {
char *a = r_core_cmd_strf (core, ".afvd %s", p->name);
if ((a && !*a) || !a) {
free (a);
a = strdup ("\n");
}
r_cons_printf ("%s %s = %s", p->isarg ? "arg": "var", p->name, a);
free (a);
}
r_list_free (list);
}
return true;
case 't':{ // "afvt"
p = strchr (ostr, ' ');
if (!p++) {
free (ostr);
return false;
}
char *type = strchr (p, ' ');
if (!type) {
free (ostr);
return false;
}
*type++ = 0;
v1 = r_anal_var_get_byname (core->anal, fcn->addr, p);
if (!v1) {
eprintf ("Cant find get by name %s\n", p);
free (ostr);
return false;
}
r_anal_var_retype (core->anal, fcn->addr,
R_ANAL_VAR_SCOPE_LOCAL, -1, v1->kind, type, -1, v1->isarg, p);
r_anal_var_free (v1);
free (ostr);
return true;
}
}
switch (str[1]) { // afv[bsr]
case '\0':
case '*':
case 'j':
r_anal_var_list_show (core->anal, fcn, type, str[1]);
if (str[1] == 'j') {
r_cons_print ("\n");
}
break;
case '.':
r_anal_var_list_show (core->anal, fcn, core->offset, 0);
break;
case '-': // "afv[bsr]-"
if (str[2] == '*') {
r_anal_var_delete_all (core->anal, fcn->addr, type);
} else {
if (IS_DIGIT (str[2])) {
r_anal_var_delete (core->anal, fcn->addr,
type, 1, (int)r_num_math (core->num, str + 1));
} else {
char *name = r_str_trim ( strdup (str + 2));
r_anal_var_delete_byname (core->anal, fcn, type, name);
free (name);
}
}
break;
case 'd':
eprintf ("This command is deprecated, use afvd instead\n");
break;
case 't':
eprintf ("This command is deprecated use afvt instead\n");
break;
case 's':
case 'g':
if (str[2] != '\0') {
int rw = 0; // 0 = read, 1 = write
int idx = r_num_math (core->num, str + 2);
char *vaddr;
char *p = r_str_trim (strchr (ostr, ' '));
if (!p) {
var_help (core, type);
break;
}
ut64 addr = core->offset;
if ((vaddr = strchr (p , ' '))) {
addr = r_num_math (core->num, vaddr);
}
RAnalVar *var = r_anal_var_get (core->anal, fcn->addr,
str[0], R_ANAL_VAR_SCOPE_LOCAL, idx);
if (!var) {
eprintf ("Cannot find variable with delta %d\n", idx);
res = false;
break;
}
rw = (str[1] == 'g')? 0: 1;
r_anal_var_access (core->anal, fcn->addr, str[0],
R_ANAL_VAR_SCOPE_LOCAL, idx, rw, addr);
r_anal_var_free (var);
} else {
eprintf ("Missing argument\n");
}
break;
case ' ': {
const char *name;
char *vartype;
bool isarg = false;
int size = 4;
int scope = 1;
for (str++; *str == ' ';) str++;
p = strchr (str, ' ');
if (!p) {
var_help (core, type);
break;
}
*p++ = 0;
if (type == 'r') { //registers
RRegItem *i = r_reg_get (core->anal->reg, str, -1);
if (!i) {
eprintf ("Register not found");
break;
}
delta = i->index;
isarg = true;
} else {
delta = r_num_math (core->num, str);
}
name = p;
if (!name) {
eprintf ("Missing name\n");
break;
}
vartype = strchr (name, ' ');
if (!vartype) {
vartype = "int";
} else {
*vartype++ = 0;
}
if ((type == 'b') && delta > 0) {
isarg = true;
} else if ((type == 's') && delta > fcn->maxstack) {
isarg = true;
}
r_anal_var_add (core->anal, fcn->addr,scope,
delta, type, vartype,
size, isarg, name);
}
break;
};
free (ostr);
return res;
}
static void print_trampolines(RCore *core, ut64 a, ut64 b, size_t element_size) {
int i;
for (i = 0; i < core->blocksize; i += element_size) {
ut32 n;
memcpy (&n, core->block + i, sizeof (ut32));
if (n >= a && n <= b) {
if (element_size == 4) {
r_cons_printf ("f trampoline.%x @ 0x%" PFMT64x "\n", n, core->offset + i);
} else {
r_cons_printf ("f trampoline.%" PFMT64x " @ 0x%" PFMT64x "\n", n, core->offset + i);
}
r_cons_printf ("Cd %u @ 0x%" PFMT64x ":%u\n", element_size, core->offset + i, element_size);
// TODO: add data xrefs
}
}
}
static void cmd_anal_trampoline(RCore *core, const char *input) {
int bits = r_config_get_i (core->config, "asm.bits");
char *p, *inp = strdup (input);
p = strchr (inp, ' ');
if (p) {
*p = 0;
}
ut64 a = r_num_math (core->num, inp);
ut64 b = p? r_num_math (core->num, p + 1): 0;
free (inp);
switch (bits) {
case 32:
print_trampolines (core, a, b, 4);
break;
case 64:
print_trampolines (core, a, b, 8);
break;
}
}
static const char *syscallNumber(int n) {
return sdb_fmt (n > 1000 ? "0x%x" : "%d", n);
}
R_API char *cmd_syscall_dostr(RCore *core, int n, ut64 addr) {
char *res = NULL;
int i;
char str[64];
int defVector = r_syscall_get_swi (core->anal->syscall);
if (defVector > 0) {
n = -1;
}
if (n == -1) {
n = (int)r_debug_reg_get (core->dbg, "oeax");
if (!n || n == -1) {
const char *a0 = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
n = (a0 == NULL)? -1: (int)r_debug_reg_get (core->dbg, a0);
}
}
RSyscallItem *item = (defVector > 0)
? r_syscall_get (core->anal->syscall, n, -1)
: r_syscall_get (core->anal->syscall, 0, n);
if (!item) {
res = r_str_appendf (res, "%s = unknown ()", syscallNumber (n));
return res;
}
res = r_str_appendf (res, "%s = %s (", syscallNumber (item->num), item->name);
// TODO: move this to r_syscall
//TODO replace the hardcoded CC with the sdb ones
for (i = 0; i < item->args; i++) {
// XXX this is a hack to make syscall args work on x86-32 and x86-64
// we need to shift sn first.. which is bad, but needs to be redesigned
int regidx = i;
if (core->assembler->bits == 32) {
regidx++;
}
ut64 arg = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, regidx);
//r_cons_printf ("(%d:0x%"PFMT64x")\n", i, arg);
if (item->sargs) {
switch (item->sargs[i]) {
case 'p': // pointer
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
case 'i':
res = r_str_appendf (res, "%" PFMT64u "", arg);
break;
case 'z':
memset (str, 0, sizeof (str));
r_io_read_at (core->io, arg, (ut8 *)str, sizeof (str) - 1);
r_str_filter (str, strlen (str));
res = r_str_appendf (res, "\"%s\"", str);
break;
case 'Z': {
//TODO replace the hardcoded CC with the sdb ones
ut64 len = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, i + 2);
len = R_MIN (len + 1, sizeof (str) - 1);
if (len == 0) {
len = 16; // override default
}
(void)r_io_read_at (core->io, arg, (ut8 *)str, len);
str[len] = 0;
r_str_filter (str, -1);
res = r_str_appendf (res, "\"%s\"", str);
} break;
default:
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
}
} else {
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
}
if (i + 1 < item->args) {
res = r_str_appendf (res, ", ");
}
}
r_syscall_item_free (item);
res = r_str_appendf (res, ")");
return res;
}
static void cmd_syscall_do(RCore *core, int n, ut64 addr) {
char *msg = cmd_syscall_dostr (core, n, addr);
if (msg) {
r_cons_println (msg);
free (msg);
}
}
static void core_anal_bytes(RCore *core, const ut8 *buf, int len, int nops, int fmt) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
bool romem = r_config_get_i (core->config, "esil.romem");
bool stats = r_config_get_i (core->config, "esil.stats");
bool be = core->print->big_endian;
bool use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
int ret, i, j, idx, size;
const char *color = "";
const char *esilstr;
const char *opexstr;
RAnalHint *hint;
RAnalEsil *esil = NULL;
RAsmOp asmop;
RAnalOp op = {0};
ut64 addr;
bool isFirst = true;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
int totalsize = 0;
// Variables required for setting up ESIL to REIL conversion
if (use_color) {
color = core->cons->pal.label;
}
switch (fmt) {
case 'j':
r_cons_printf ("[");
break;
case 'r':
// Setup for ESIL to REIL conversion
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
break;
}
for (i = idx = ret = 0; idx < len && (!nops || (nops && i < nops)); i++, idx += ret) {
addr = core->offset + idx;
// TODO: use more anal hints
hint = r_anal_hint_get (core->anal, addr);
r_asm_set_pc (core->assembler, addr);
(void)r_asm_disassemble (core->assembler, &asmop, buf + idx, len - idx);
ret = r_anal_op (core->anal, &op, core->offset + idx, buf + idx, len - idx, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&op.esil);
opexstr = R_STRBUF_SAFEGET (&op.opex);
char *mnem = strdup (r_asm_op_get_asm (&asmop));
char *sp = strchr (mnem, ' ');
if (sp) {
*sp = 0;
if (op.prefix) {
char *arg = strdup (sp + 1);
char *sp = strchr (arg, ' ');
if (sp) {
*sp = 0;
}
free (mnem);
mnem = arg;
}
}
if (ret < 1 && fmt != 'd') {
eprintf ("Oops at 0x%08" PFMT64x " (", core->offset + idx);
for (i = idx, j = 0; i < core->blocksize && j < 3; ++i, ++j) {
eprintf ("%02x ", buf[i]);
}
eprintf ("...)\n");
free (mnem);
break;
}
size = (hint && hint->size)? hint->size: op.size;
if (fmt == 'd') {
char *opname = strdup (r_asm_op_get_asm (&asmop));
if (opname) {
r_str_split (opname, ' ');
char *d = r_asm_describe (core->assembler, opname);
if (d && *d) {
r_cons_printf ("%s: %s\n", opname, d);
free (d);
} else {
eprintf ("Unknown opcode\n");
}
free (opname);
}
} else if (fmt == 'e') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET " %s\n", color, core->offset + idx, esilstr);
} else {
r_cons_printf ("0x%" PFMT64x " %s\n", core->offset + idx, esilstr);
}
}
} else if (fmt == 's') {
totalsize += op.size;
} else if (fmt == 'r') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET "\n", color, core->offset + idx);
} else {
r_cons_printf ("0x%" PFMT64x "\n", core->offset + idx);
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
}
} else if (fmt == 'j') {
if (isFirst) {
isFirst = false;
} else {
r_cons_print (",");
}
r_cons_printf ("{\"opcode\":\"%s\",", r_asm_op_get_asm (&asmop));
{
char strsub[128] = { 0 };
// pc+33
r_parse_varsub (core->parser, NULL,
core->offset + idx,
asmop.size, r_asm_op_get_asm (&asmop),
strsub, sizeof (strsub));
{
ut64 killme = UT64_MAX;
if (r_io_read_i (core->io, op.ptr, &killme, op.refptr, be)) {
core->parser->relsub_addr = killme;
}
}
// 0x33->sym.xx
char *p = strdup (strsub);
if (p) {
r_parse_filter (core->parser, addr, core->flags, p,
strsub, sizeof (strsub), be);
free (p);
}
r_cons_printf ("\"disasm\":\"%s\",", strsub);
}
r_cons_printf ("\"mnemonic\":\"%s\",", mnem);
if (hint && hint->opcode) {
r_cons_printf ("\"ophint\":\"%s\",", hint->opcode);
}
r_cons_printf ("\"sign\":%s,", r_str_bool (op.sign));
r_cons_printf ("\"prefix\":%" PFMT64u ",", op.prefix);
r_cons_printf ("\"id\":%d,", op.id);
if (opexstr && *opexstr) {
r_cons_printf ("\"opex\":%s,", opexstr);
}
r_cons_printf ("\"addr\":%" PFMT64u ",", core->offset + idx);
r_cons_printf ("\"bytes\":\"");
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_printf ("\",");
if (op.val != UT64_MAX) {
r_cons_printf ("\"val\": %" PFMT64u ",", op.val);
}
if (op.ptr != UT64_MAX) {
r_cons_printf ("\"ptr\": %" PFMT64u ",", op.ptr);
}
r_cons_printf ("\"size\": %d,", size);
r_cons_printf ("\"type\": \"%s\",",
r_anal_optype_to_string (op.type));
if (op.reg) {
r_cons_printf ("\"reg\": \"%s\",", op.reg);
}
if (op.ireg) {
r_cons_printf ("\"ireg\": \"%s\",", op.ireg);
}
if (op.scale) {
r_cons_printf ("\"scale\":%d,", op.scale);
}
if (hint && hint->esil) {
r_cons_printf ("\"esil\": \"%s\",", hint->esil);
} else if (*esilstr) {
r_cons_printf ("\"esil\": \"%s\",", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
r_cons_printf ("\"jump\":%" PFMT64u ",", op.jump);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.refptr != -1) {
r_cons_printf ("\"refptr\":%d,", op.refptr);
}
if (op.fail != UT64_MAX) {
r_cons_printf ("\"fail\":%" PFMT64u ",", op.fail);
}
r_cons_printf ("\"cycles\":%d,", op.cycles);
if (op.failcycles) {
r_cons_printf ("\"failcycles\":%d,", op.failcycles);
}
r_cons_printf ("\"delay\":%d,", op.delay);
{
const char *p = r_anal_stackop_tostring (op.stackop);
if (p && *p && strcmp (p, "null"))
r_cons_printf ("\"stack\":\"%s\",", p);
}
if (op.stackptr) {
r_cons_printf ("\"stackptr\":%d,", op.stackptr);
}
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)
? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
r_cons_printf ("\"cond\":\"%s\",", arg);
}
}
r_cons_printf ("\"family\":\"%s\"}", r_anal_op_family_to_string (op.family));
} else {
#define printline(k, fmt, arg)\
{ \
if (use_color)\
r_cons_printf ("%s%s: " Color_RESET, color, k);\
else\
r_cons_printf ("%s: ", k);\
if (fmt) r_cons_printf (fmt, arg);\
}
printline ("address", "0x%" PFMT64x "\n", core->offset + idx);
printline ("opcode", "%s\n", r_asm_op_get_asm (&asmop));
printline ("mnemonic", "%s\n", mnem);
if (hint) {
if (hint->opcode) {
printline ("ophint", "%s\n", hint->opcode);
}
#if 0
// addr should not override core->offset + idx.. its silly
if (hint->addr != UT64_MAX) {
printline ("addr", "0x%08" PFMT64x "\n", (hint->addr + idx));
}
#endif
}
printline ("prefix", "%" PFMT64u "\n", op.prefix);
printline ("id", "%d\n", op.id);
#if 0
// no opex here to avoid lot of tests broken..and having json in here is not much useful imho
if (opexstr && *opexstr) {
printline ("opex", "%s\n", opexstr);
}
#endif
printline ("bytes", NULL, 0);
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_newline ();
if (op.val != UT64_MAX)
printline ("val", "0x%08" PFMT64x "\n", op.val);
if (op.ptr != UT64_MAX)
printline ("ptr", "0x%08" PFMT64x "\n", op.ptr);
if (op.refptr != -1)
printline ("refptr", "%d\n", op.refptr);
printline ("size", "%d\n", size);
printline ("sign", "%s\n", r_str_bool (op.sign));
printline ("type", "%s\n", r_anal_optype_to_string (op.type));
printline ("cycles", "%d\n", op.cycles);
if (op.failcycles) {
printline ("failcycles", "%d\n", op.failcycles);
}
{
const char *t2 = r_anal_optype_to_string (op.type2);
if (t2 && strcmp (t2, "null")) {
printline ("type2", "%s\n", t2);
}
}
if (op.reg) {
printline ("reg", "%s\n", op.reg);
}
if (op.ireg) {
printline ("ireg", "%s\n", op.ireg);
}
if (op.scale) {
printline ("scale", "%d\n", op.scale);
}
if (hint && hint->esil) {
printline ("esil", "%s\n", hint->esil);
} else if (*esilstr) {
printline ("esil", "%s\n", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
printline ("jump", "0x%08" PFMT64x "\n", op.jump);
}
if (op.direction != 0) {
const char * dir = op.direction == 1 ? "read"
: op.direction == 2 ? "write"
: op.direction == 4 ? "exec"
: op.direction == 8 ? "ref": "none";
printline ("direction", "%s\n", dir);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.fail != UT64_MAX) {
printline ("fail", "0x%08" PFMT64x "\n", op.fail);
}
if (op.delay) {
printline ("delay", "%d\n", op.delay);
}
printline ("stack", "%s\n", r_anal_stackop_tostring (op.stackop));
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
printline ("cond", "%s\n", arg);
}
}
printline ("family", "%s\n", r_anal_op_family_to_string (op.family));
printline ("stackop", "%s\n", r_anal_stackop_tostring (op.stackop));
if (op.stackptr) {
printline ("stackptr", "%"PFMT64u"\n", op.stackptr);
}
}
//r_cons_printf ("false: 0x%08"PFMT64x"\n", core->offset+idx);
//free (hint);
free (mnem);
r_anal_hint_free (hint);
r_anal_op_fini (&op);
}
r_anal_op_fini (&op);
if (fmt == 'j') {
r_cons_printf ("]");
r_cons_newline ();
} else if (fmt == 's') {
r_cons_printf ("%d\n", totalsize);
}
r_anal_esil_free (esil);
}
static int bb_cmp(const void *a, const void *b) {
const RAnalBlock *ba = a;
const RAnalBlock *bb = b;
return ba->addr - bb->addr;
}
static int anal_fcn_list_bb(RCore *core, const char *input, bool one) {
RDebugTracepoint *tp = NULL;
RListIter *iter;
RAnalBlock *b;
int mode = 0;
ut64 addr, bbaddr = UT64_MAX;
bool firstItem = true;
if (*input == '.') {
one = true;
input++;
}
if (*input) {
mode = *input;
input++;
}
if (*input == '.') {
one = true;
input++;
}
if (input && *input) {
addr = bbaddr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (one) {
bbaddr = addr;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (!fcn) {
return false;
}
switch (mode) {
case 'j':
r_cons_printf ("[");
break;
case '*':
r_cons_printf ("fs blocks\n");
break;
}
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, b) {
if (one) {
if (bbaddr != UT64_MAX && (bbaddr < b->addr || bbaddr >= (b->addr + b->size))) {
continue;
}
}
switch (mode) {
case 'r':
if (b->jump == UT64_MAX) {
ut64 retaddr = b->addr;
if (b->op_pos) {
retaddr += b->op_pos[b->ninstr - 2];
}
if (!strcmp (input, "*")) {
r_cons_printf ("db 0x%08"PFMT64x"\n", retaddr);
} else if (!strcmp (input, "-*")) {
r_cons_printf ("db-0x%08"PFMT64x"\n", retaddr);
} else {
r_cons_printf ("0x%08"PFMT64x"\n", retaddr);
}
}
break;
case '*':
r_cons_printf ("f bb.%05" PFMT64x " = 0x%08" PFMT64x "\n",
b->addr & 0xFFFFF, b->addr);
break;
case 'q':
r_cons_printf ("0x%08" PFMT64x "\n", b->addr);
break;
case 'j':
//r_cons_printf ("%" PFMT64u "%s", b->addr, iter->n? ",": "");
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
r_cons_printf ("%s{", firstItem? "": ",");
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("\"jump\":%"PFMT64u",", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("\"fail\":%"PFMT64u",", b->fail);
}
if (b->switch_op) {
r_cons_print ("\"switch_op\":{");
r_cons_printf ("\"addr\":%"PFMT64u",", b->switch_op->addr);
r_cons_printf ("\"min_val\":%"PFMT64u",", b->switch_op->min_val);
r_cons_printf ("\"def_val\":%"PFMT64u",", b->switch_op->def_val);
r_cons_printf ("\"max_val\":%"PFMT64u",", b->switch_op->max_val);
r_cons_print ("\"cases\":[");
{
RListIter *case_op_iter;
RAnalCaseOp *case_op;
r_list_foreach (b->switch_op->cases, case_op_iter, case_op) {
r_cons_printf ("%s{", case_op_iter->p ? "," : "");
r_cons_printf ("\"addr\":%"PFMT64u",", case_op->addr);
r_cons_printf ("\"jump\":%"PFMT64u",", case_op->jump);
r_cons_printf ("\"value\":%"PFMT64u",", case_op->value);
r_cons_printf ("\"cond\":%"PFMT32u",", case_op->cond);
r_cons_printf ("\"bb_ref_to\":%"PFMT64u",", case_op->bb_ref_to);
r_cons_printf ("\"bb_ref_from\":%"PFMT64u"", case_op->bb_ref_from);
r_cons_print ("}");
}
}
r_cons_print ("]},");
}
r_cons_printf ("\"addr\":%" PFMT64u ",\"size\":%d,\"inputs\":%d,\"outputs\":%d,\"ninstr\":%d,\"traced\":%s}",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
case 'i':
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("jump: 0x%08"PFMT64x"\n", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("fail: 0x%08"PFMT64x"\n", b->fail);
}
r_cons_printf ("addr: 0x%08"PFMT64x"\nsize: %d\ninputs: %d\noutputs: %d\nninstr: %d\ntraced: %s\n",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
default:
tp = r_debug_trace_get (core->dbg, b->addr);
r_cons_printf ("0x%08" PFMT64x " 0x%08" PFMT64x " %02X:%04X %d",
b->addr, b->addr + b->size,
tp? tp->times: 0, tp? tp->count: 0,
b->size);
if (b->jump != UT64_MAX) {
r_cons_printf (" j 0x%08" PFMT64x, b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf (" f 0x%08" PFMT64x, b->fail);
}
r_cons_newline ();
break;
}
}
if (mode == 'j') {
r_cons_printf ("]\n");
}
return true;
}
static bool anal_bb_edge (RCore *core, const char *input) {
// "afbe" switch-bb-addr case-bb-addr
char *arg = strdup (r_str_trim_ro(input));
char *sp = strchr (arg, ' ');
if (sp) {
*sp++ = 0;
ut64 sw_at = r_num_math (core->num, arg);
ut64 cs_at = r_num_math (core->num, sp);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, sw_at, 0);
if (fcn) {
RAnalBlock *bb;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, bb) {
if (sw_at >= bb->addr && sw_at < (bb->addr + bb->size)) {
if (!bb->switch_op) {
bb->switch_op = r_anal_switch_op_new (
sw_at, 0, 0);
}
r_anal_switch_op_add_case (bb->switch_op, cs_at, 0, cs_at);
}
}
free (arg);
return true;
}
}
free (arg);
return false;
}
static bool anal_fcn_del_bb(RCore *core, const char *input) {
ut64 addr = r_num_math (core->num, input);
if (!addr) {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (!strcmp (input, "*")) {
r_list_free (fcn->bbs);
fcn->bbs = NULL;
} else {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
if (b->addr == addr) {
r_list_delete (fcn->bbs, iter);
return true;
}
}
eprintf ("Cannot find basic block\n");
}
} else {
eprintf ("Cannot find function\n");
}
return false;
}
static int anal_fcn_add_bb(RCore *core, const char *input) {
// fcn_addr bb_addr bb_size [jump] [fail]
char *ptr;
const char *ptr2 = NULL;
ut64 fcnaddr = -1LL, addr = -1LL;
ut64 size = 0LL;
ut64 jump = UT64_MAX;
ut64 fail = UT64_MAX;
int type = R_ANAL_BB_TYPE_NULL;
RAnalFunction *fcn = NULL;
RAnalDiff *diff = NULL;
while (*input == ' ') input++;
ptr = strdup (input);
switch (r_str_word_set0 (ptr)) {
case 7:
ptr2 = r_str_word_get0 (ptr, 6);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 6:
ptr2 = r_str_word_get0 (ptr, 5);
if (strchr (ptr2, 'h')) {
type |= R_ANAL_BB_TYPE_HEAD;
}
if (strchr (ptr2, 'b')) {
type |= R_ANAL_BB_TYPE_BODY;
}
if (strchr (ptr2, 'l')) {
type |= R_ANAL_BB_TYPE_LAST;
}
if (strchr (ptr2, 'f')) {
type |= R_ANAL_BB_TYPE_FOOT;
}
case 5: // get fail
fail = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4: // get jump
jump = r_num_math (core->num, r_str_word_get0 (ptr, 3));
case 3: // get size
size = r_num_math (core->num, r_str_word_get0 (ptr, 2));
case 2: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 1));
case 1: // get fcnaddr
fcnaddr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
fcn = r_anal_get_fcn_in (core->anal, fcnaddr, 0);
if (fcn) {
int ret = r_anal_fcn_add_bb (core->anal, fcn, addr, size, jump, fail, type, diff);
if (!ret) {
eprintf ("Cannot add basic block\n");
}
} else {
eprintf ("Cannot find function at 0x%" PFMT64x "\n", fcnaddr);
}
r_anal_diff_free (diff);
free (ptr);
return true;
}
static void r_core_anal_nofunclist (RCore *core, const char *input) {
int minlen = (int)(input[0]==' ') ? r_num_math (core->num, input + 1): 16;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
ut64 chunk_size, chunk_offset, i;
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int counter;
if (minlen < 1) {
minlen = 1;
}
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not withing range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
// finally, add a special marker to show the beginning of a
// function
bitmap[fcn->addr-base_addr] = 'F';
}
}
// Now we print the list of memory regions that are not assigned to a function
chunk_size = 0;
chunk_offset = 0;
for (i = 0; i < code_size; i++) {
if (bitmap[i]){
// We only print a region is its size is bigger than 15 bytes
if (chunk_size >= minlen){
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
chunk_size = 0;
chunk_offset = i+1;
continue;
}
chunk_size+=1;
}
if (chunk_size >= 16) {
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
free(bitmap);
}
static void r_core_anal_fmap (RCore *core, const char *input) {
int show_color = r_config_get_i (core->config, "scr.color");
int cols = r_config_get_i (core->config, "hex.cols") * 4;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int assigned;
ut64 i;
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not within range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
int counter = 1;
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
bitmap[fcn->addr-base_addr] = 'F';
}
}
// print the bitmap
assigned = 0;
if (cols < 1) {
cols = 1;
}
for (i = 0; i < code_size; i += 1) {
if (!(i % cols)) {
r_cons_printf ("\n0x%08"PFMT64x" ", base_addr+i);
}
if (bitmap[i]) {
assigned++;
}
if (show_color) {
if (bitmap[i]) {
r_cons_printf ("%s%c\x1b[0m", Color_GREEN, bitmap[i]);
} else {
r_cons_printf (".");
}
} else {
r_cons_printf ("%c", bitmap[i] ? bitmap[i] : '.' );
}
}
r_cons_printf ("\n%d / %d (%.2lf%%) bytes assigned to a function\n", assigned, code_size, 100.0*( (float) assigned) / code_size);
free(bitmap);
}
static bool fcnNeedsPrefix(const char *name) {
if (!strncmp (name, "entry", 5)) {
return false;
}
if (!strncmp (name, "main", 4)) {
return false;
}
return (!strchr (name, '.'));
}
/* TODO: move into r_anal_fcn_rename(); */
static bool setFunctionName(RCore *core, ut64 off, const char *_name, bool prefix) {
char *name, *nname = NULL;
RAnalFunction *fcn;
if (!core || !_name) {
return false;
}
const char *fcnpfx = r_config_get (core->config, "anal.fcnprefix");
if (!fcnpfx) {
fcnpfx = "fcn";
}
if (r_reg_get (core->anal->reg, _name, -1)) {
name = r_str_newf ("%s.%s", fcnpfx, _name);
} else {
name = strdup (_name);
}
fcn = r_anal_get_fcn_in (core->anal, off,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM | R_ANAL_FCN_TYPE_LOC);
if (!fcn) {
free (name);
return false;
}
if (prefix && fcnNeedsPrefix (name)) {
nname = r_str_newf ("%s.%s", fcnpfx, name);
} else {
nname = strdup (name);
}
char *oname = fcn->name;
r_flag_rename (core->flags, r_flag_get (core->flags, fcn->name), nname);
fcn->name = strdup (nname);
if (core->anal->cb.on_fcn_rename) {
core->anal->cb.on_fcn_rename (core->anal,
core->anal->user, fcn, nname);
}
free (oname);
free (nname);
free (name);
return true;
}
static void afCc(RCore *core, const char *input) {
ut64 addr;
RAnalFunction *fcn;
if (*input == ' ') {
addr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
ut32 totalCycles = r_anal_fcn_cost (core->anal, fcn);
// FIXME: This defeats the purpose of the function, but afC is used in project files.
// cf. canal.c
r_cons_printf ("%d\n", totalCycles);
} else {
eprintf ("Cannot find function\n");
}
}
static int cmd_anal_fcn(RCore *core, const char *input) {
char i;
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
switch (input[1]) {
case 'f': // "aff"
r_anal_fcn_fit_overlaps (core->anal, NULL);
break;
case 'a':
if (input[2] == 'l') { // afal : list function call arguments
int show_args = r_config_get_i (core->config, "dbg.funcarg");
if (show_args) {
r_core_print_func_args (core);
}
break;
}
case 'd': // "afd"
{
ut64 addr = 0;
if (input[2] == '?') {
eprintf ("afd [offset]\n");
} else if (input[2] == ' ') {
addr = r_num_math (core->num, input + 2);
} else {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
if (fcn->addr != addr) {
r_cons_printf ("%s + %d\n", fcn->name,
(int)(addr - fcn->addr));
} else {
r_cons_println (fcn->name);
}
} else {
eprintf ("Cannot find function\n");
}
}
break;
case '-': // "af-"
if (!input[2] || !strcmp (input + 2, "*")) {
RAnalFunction *f;
RListIter *iter;
r_list_foreach (core->anal->fcns, iter, f) {
r_anal_del_jmprefs (core->anal, f);
}
r_list_purge (core->anal->fcns);
core->anal->fcn_tree = NULL;
} else {
ut64 addr = input[2]
? r_num_math (core->num, input + 2)
: core->offset;
r_anal_fcn_del_locs (core->anal, addr);
r_anal_fcn_del (core->anal, addr);
}
break;
case 'u': // "afu"
{
ut64 addr = core->offset;
ut64 addr_end = r_num_math (core->num, input + 2);
if (addr_end < addr) {
eprintf ("Invalid address ranges\n");
} else {
int depth = 1;
ut64 a, b;
const char *c;
a = r_config_get_i (core->config, "anal.from");
b = r_config_get_i (core->config, "anal.to");
c = r_config_get (core->config, "anal.limits");
r_config_set_i (core->config, "anal.from", addr);
r_config_set_i (core->config, "anal.to", addr_end);
r_config_set (core->config, "anal.limits", "true");
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_core_anal_fcn (core, addr, UT64_MAX,
R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_config_set_i (core->config, "anal.from", a);
r_config_set_i (core->config, "anal.to", b);
r_config_set (core->config, "anal.limits", c? c: "");
}
}
break;
case '+': { // "af+"
if (input[2] != ' ') {
eprintf ("Missing arguments\n");
return false;
}
char *ptr = strdup (input + 3);
const char *ptr2;
int n = r_str_word_set0 (ptr);
const char *name = NULL;
ut64 addr = UT64_MAX;
ut64 size = 0LL;
RAnalDiff *diff = NULL;
int type = R_ANAL_FCN_TYPE_FCN;
if (n > 1) {
switch (n) {
case 5:
size = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4:
ptr2 = r_str_word_get0 (ptr, 3);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 3:
ptr2 = r_str_word_get0 (ptr, 2);
if (strchr (ptr2, 'l')) {
type = R_ANAL_FCN_TYPE_LOC;
} else if (strchr (ptr2, 'i')) {
type = R_ANAL_FCN_TYPE_IMP;
} else if (strchr (ptr2, 's')) {
type = R_ANAL_FCN_TYPE_SYM;
} else {
type = R_ANAL_FCN_TYPE_FCN;
}
case 2:
name = r_str_word_get0 (ptr, 1);
case 1:
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
if (!r_anal_fcn_add (core->anal, addr, size, name, type, diff)) {
eprintf ("Cannot add function (duplicated)\n");
}
}
r_anal_diff_free (diff);
free (ptr);
}
break;
case 'o': // "afo"
{
RAnalFunction *fcn;
ut64 addr = core->offset;
if (input[2] == ' ')
addr = r_num_math (core->num, input + 3);
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
r_cons_printf ("0x%08" PFMT64x "\n", fcn->addr);
}
}
break;
case 'i': // "afi"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afi);
break;
case '.': // "afi."
{
ut64 addr = core->offset;
if (input[3] == ' ') {
addr = r_num_math (core->num, input + 3);
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case 'l': // "afil"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afil";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "afij"
case '*': // "afi*"
r_core_anal_fcn_list (core, input + 3, input + 2);
break;
case 'p': // "afip"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf ("is-pure: %s\n", r_anal_fcn_get_purity (core->anal, fcn) ? "true" : "false");
}
}
break;
default:
i = 1;
r_core_anal_fcn_list (core, input + 2, &i);
break;
}
break;
case 'l': // "afl"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afl);
break;
case 's': // "afls"
r_list_sort (core->anal->fcns, cmpaddr);
break;
case 'l': // "afll"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afll";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "aflj"
case 'q': // "aflq"
case '+': // "afl+"
case '*': // "afl*"
r_core_anal_fcn_list (core, NULL, input + 2);
break;
case 'c': // "aflc"
r_cons_printf ("%d\n", r_list_length (core->anal->fcns));
break;
default: // "afl "
r_core_anal_fcn_list (core, NULL, "o");
break;
}
break;
case 's': // "afs"
{
ut64 addr;
RAnalFunction *f;
const char *arg = input + 2;
if (input[2] && (addr = r_num_math (core->num, arg))) {
arg = strchr (arg, ' ');
if (arg) {
arg++;
}
} else {
addr = core->offset;
}
if ((f = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL))) {
if (arg && *arg) {
r_anal_str_to_fcn (core->anal, f, arg);
} else {
char *str = r_anal_fcn_to_string (core->anal, f);
r_cons_println (str);
free (str);
}
} else {
eprintf ("No function defined at 0x%08" PFMT64x "\n", addr);
}
}
break;
case 'm': // "afm" - merge two functions
r_core_anal_fcn_merge (core, core->offset, r_num_math (core->num, input + 2));
break;
case 'M': // "afM" - print functions map
r_core_anal_fmap (core, input + 1);
break;
case 'v': // "afv"
var_cmd (core, input + 2);
break;
case 't': // "aft"
type_cmd (core, input + 2);
break;
case 'C': // "afC"
if (input[2] == 'c') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%i\n", r_anal_fcn_cc (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == 'l') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%d\n", r_anal_fcn_loops (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == '?') {
r_core_cmd_help (core, help_msg_afC);
} else {
afCc (core, input + 3);
}
break;
case 'c':{ // "afc"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (!fcn && !(input[2] == '?'|| input[2] == 'l' || input[2] == 'o' || input[2] == 'f')) {
eprintf ("Cannot find function here\n");
break;
}
switch (input[2]) {
case '\0': // "afc"
r_cons_println (fcn->cc);
break;
case ' ': { // "afc "
char *cc = r_str_trim (strdup (input + 3));
if (!r_anal_cc_exist (core->anal, cc)) {
eprintf ("Unknown calling convention '%s'\n"
"See afcl for available types\n", cc);
} else {
fcn->cc = r_str_const (r_anal_cc_to_constant (core->anal, cc));
}
break;
}
case 'a': // "afca"
eprintf ("Todo\n");
break;
case 'f': { // "afcf"
bool json = false;
if (input[3] == 'j') {
json = true;
r_cons_printf ("[");
}
char *p = strchr (input, ' ');
const char *fcn_name = p? r_str_trim (strdup (p)): NULL;
char *key = NULL;
RListIter *iter;
RAnalFuncArg *arg;
if (fcn && !fcn_name) {
fcn_name = fcn->name;
}
if (fcn_name) {
key = resolve_fcn_name (core->anal, fcn_name);
}
if (key) {
const char *fcn_type = r_type_func_ret (core->anal->sdb_types, key);
int nargs = r_type_func_args_count (core->anal->sdb_types, key);
if (fcn_type) {
char *sp = " ";
if (*fcn_type && (fcn_type[strlen (fcn_type) - 1] == '*')) {
sp = "";
}
if (json) {
r_cons_printf ("{\"name\": \"%s\"",r_str_get (key));
r_cons_printf (",\"return\": \"%s\"",r_str_get (fcn_type));
r_cons_printf (",\"count\": %d", nargs);
if (nargs) {
r_cons_printf (",\"args\":[", nargs);
}
} else {
r_cons_printf ("%s%s%s(", r_str_get (fcn_type), sp, r_str_get (key));
if (!nargs) {
r_cons_println ("void)");
break;
}
}
bool first = true;
RList *list = r_core_get_func_args (core, fcn_name);
r_list_foreach (list, iter, arg) {
RListIter *nextele = r_list_iter_get_next (iter);
char *type = arg->orig_c_type;
char *sp1 = " ";
if (*type && (type[strlen (type) - 1] == '*')) {
sp1 = "";
}
if (json) {
r_cons_printf ("%s{\"name\": \"%s\",\"type\":\"%s\"}",
first? "": ",", arg->name, type);
first = false;
} else {
r_cons_printf ("%s%s%s%s", type, sp1, arg->name, nextele?", ":")");
}
}
if (json) {
if (nargs) {
r_cons_printf ("]");
}
r_cons_printf ("}");
} else {
r_cons_println ("");
}
}
}
if (json) {
r_cons_printf ("]\n");
}
break;
}
case 'l': // "afcl" list all function Calling conventions.
sdb_foreach (core->anal->sdb_cc, cc_print, NULL);
break;
case 'o': { // "afco"
char *dbpath = r_str_trim (strdup (input + 3));
if (r_file_exists (dbpath)) {
Sdb *db = sdb_new (0, dbpath, 0);
sdb_merge (core->anal->sdb_cc, db);
sdb_close (db);
sdb_free (db);
}
free (dbpath);
break;
}
case 'r': { // "afcr"
int i;
char *out, *cmd, *regname, *tmp;
char *subvec_str = r_str_new ("");
char *json_str = r_str_new ("");
// if json_str initialize to NULL, it's possible for afcrj to output a (NULL)
// subvec_str and json_str should be valid until exiting this code block
bool json = input[3] == 'j'? true: false;
for (i = 0; i <= 11; i++) {
if (i == 0) {
cmd = r_str_newf ("cc.%s.ret", fcn->cc);
} else {
cmd = r_str_newf ("cc.%s.arg%d", fcn->cc, i);
}
if (i < 7) {
regname = r_str_new (cmd);
} else {
regname = r_str_newf ("cc.%s.float_arg%d", fcn->cc, i - 6);
}
out = sdb_querys (core->anal->sdb_cc, NULL, 0, cmd);
free (cmd);
if (out) {
out[strlen (out) - 1] = 0;
if (json) {
tmp = subvec_str;
subvec_str = r_str_newf ("%s,\"%s\"", subvec_str, out);
free (tmp);
} else {
r_cons_printf ("%s: %s\n", regname, out);
}
free (out);
}
free (regname);
if (!subvec_str[0]) {
continue;
}
switch (i) {
case 0: {
tmp = json_str;
json_str = r_str_newf ("%s,\"ret\":%s", json_str, subvec_str + 1);
free (tmp);
} break;
case 6: {
tmp = json_str;
json_str = r_str_newf ("%s,\"args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
case 11: {
tmp = json_str;
json_str = r_str_newf ("%s,\"float_args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
default:
continue;
}
free (subvec_str);
subvec_str = r_str_new ("");
}
if (json && json_str[0]) {
r_cons_printf ("{%s}\n", json_str + 1);
}
free (subvec_str);
free (json_str);
} break;
case '?': // "afc?"
default:
r_core_cmd_help (core, help_msg_afc);
}
}break;
case 'B': // "afB" // set function bits
if (input[2] == ' ') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
int bits = atoi (input + 3);
r_anal_hint_set_bits (core->anal, fcn->addr, bits);
r_anal_hint_set_bits (core->anal,
fcn->addr + r_anal_fcn_size (fcn),
core->anal->bits);
fcn->bits = bits;
} else {
eprintf ("Cannot find function to set bits\n");
}
} else {
eprintf ("Usage: afB [bits]\n");
}
break;
case 'b': // "afb"
switch (input[2]) {
case '-': // "afb-"
anal_fcn_del_bb (core, input + 3);
break;
case 'e': // "afbe"
anal_bb_edge (core, input + 3);
break;
case 0:
case ' ': // "afb "
case 'q': // "afbq"
case 'r': // "afbr"
case '*': // "afb*"
case 'j': // "afbj"
anal_fcn_list_bb (core, input + 2, false);
break;
case 'i': // "afbi"
anal_fcn_list_bb (core, input + 2, true);
break;
case '.': // "afb."
anal_fcn_list_bb (core, input[2]? " $$": input + 2, true);
break;
case '+': // "afb+"
anal_fcn_add_bb (core, input + 3);
break;
case 'c': // "afbc"
{
const char *ptr = input + 3;
ut64 addr = r_num_math (core->num, ptr);
ut32 color;
ptr = strchr (ptr, ' ');
if (ptr) {
ptr = strchr (ptr + 1, ' ');
if (ptr) {
color = r_num_math (core->num, ptr + 1);
RAnalOp *op = r_core_op_anal (core, addr);
if (op) {
r_anal_colorize_bb (core->anal, addr, color);
r_anal_op_free (op);
} else {
eprintf ("Cannot analyze opcode at 0x%08" PFMT64x "\n", addr);
}
}
}
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_afb);
break;
}
break;
case 'n': // "afn"
switch (input[2]) {
case 's': // "afns"
free (r_core_anal_fcn_autoname (core, core->offset, 1));
break;
case 'a': // "afna"
{
char *name = r_core_anal_fcn_autoname (core, core->offset, 0);
if (name) {
r_cons_printf ("afn %s 0x%08" PFMT64x "\n", name, core->offset);
free (name);
}
}
break;
case 0: // "afn"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case ' ': // "afn "
{
ut64 off = core->offset;
char *p, *name = strdup (input + 3);
if ((p = strchr (name, ' '))) {
*p++ = 0;
off = r_num_math (core->num, p);
}
if (*name == '?') {
eprintf ("Usage: afn newname [off] # set new name to given function\n");
} else {
if (!*name || !setFunctionName (core, off, name, false)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, off);
}
}
free (name);
}
break;
default:
r_core_cmd_help (core, help_msg_afn);
break;
}
break;
case 'S': // afS"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
fcn->maxstack = r_num_math (core->num, input + 3);
//fcn->stack = fcn->maxstack;
}
}
break;
#if 0
/* this is undocumented and probably have no uses. plz discuss */
case 'e': // "afe"
{
RAnalFunction *fcn;
ut64 off = core->offset;
char *p, *name = strdup ((input[2]&&input[3])? input + 3: "");
if ((p = strchr (name, ' '))) {
*p = 0;
off = r_num_math (core->num, p + 1);
}
fcn = r_anal_get_fcn_in (core->anal, off, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
RAnalBlock *b;
RListIter *iter;
RAnalRef *r;
r_list_foreach (fcn->refs, iter, r) {
r_cons_printf ("0x%08" PFMT64x " -%c 0x%08" PFMT64x "\n", r->at, r->type, r->addr);
}
r_list_foreach (fcn->bbs, iter, b) {
int ok = 0;
if (b->type == R_ANAL_BB_TYPE_LAST) ok = 1;
if (b->type == R_ANAL_BB_TYPE_FOOT) ok = 1;
if (b->jump == UT64_MAX && b->fail == UT64_MAX) ok = 1;
if (ok) {
r_cons_printf ("0x%08" PFMT64x " -r\n", b->addr);
// TODO: check if destination is outside the function boundaries
}
}
} else eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
free (name);
}
break;
#endif
case 'x': // "afx"
switch (input[2]) {
case '\0': // "afx"
case 'j': // "afxj"
case ' ': // "afx "
if (input[2] == 'j') {
r_cons_printf ("[");
}
// list xrefs from current address
{
ut64 addr = input[2]==' '? r_num_math (core->num, input + 2): core->offset;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (input[2] == 'j') {
r_cons_printf ("{\"type\":\"%c\",\"from\":%"PFMT64u",\"to\":%"PFMT64u"}%s",
ref->type, ref->at, ref->addr, iter->n? ",": "");
} else {
r_cons_printf ("%c 0x%08" PFMT64x " -> 0x%08" PFMT64x "\n",
ref->type, ref->at, ref->addr);
}
}
r_list_free (refs);
} else {
eprintf ("Cannot find function at 0x%08"PFMT64x"\n", addr);
}
}
if (input[2] == 'j') {
r_cons_printf ("]\n");
}
break;
default:
eprintf ("Wrong command. Look at af?\n");
break;
}
break;
case 'F': // "afF"
{
int val = input[2] && r_num_math (core->num, input + 2);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
fcn->folded = input[2]? val: !fcn->folded;
}
}
break;
case '?': // "af?"
r_core_cmd_help (core, help_msg_af);
break;
case 'r': // "afr" // analyze function recursively
case ' ': // "af "
case '\0': // "af"
{
char *uaddr = NULL, *name = NULL;
int depth = r_config_get_i (core->config, "anal.depth");
bool analyze_recursively = r_config_get_i (core->config, "anal.calls");
RAnalFunction *fcn;
RAnalFunction *fcni;
RListIter *iter;
ut64 addr = core->offset;
if (input[1] == 'r') {
input++;
analyze_recursively = true;
}
// first undefine
if (input[0] && input[1] == ' ') {
name = strdup (input + 2);
uaddr = strchr (name, ' ');
if (uaddr) {
*uaddr++ = 0;
addr = r_num_math (core->num, uaddr);
}
// depth = 1; // or 1?
// disable hasnext
}
//r_core_anal_undefine (core, core->offset);
r_core_anal_fcn (core, addr, UT64_MAX, R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
/* ensure we use a proper name */
setFunctionName (core, addr, fcn->name, false);
}
if (analyze_recursively) {
fcn = r_anal_get_fcn_in (core->anal, addr, 0); /// XXX wrong in case of nopskip
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (ref->addr == UT64_MAX) {
//eprintf ("Warning: ignore 0x%08"PFMT64x" call 0x%08"PFMT64x"\n", ref->at, ref->addr);
continue;
}
if (ref->type != R_ANAL_REF_TYPE_CODE && ref->type != R_ANAL_REF_TYPE_CALL) {
/* only follow code/call references */
continue;
}
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
r_core_anal_fcn (core, ref->addr, fcn->addr, R_ANAL_REF_TYPE_CALL, depth);
/* use recursivity here */
#if 1
RAnalFunction *f = r_anal_get_fcn_at (core->anal, ref->addr, 0);
if (f) {
RListIter *iter;
RAnalRef *ref;
RList *refs1 = r_anal_fcn_get_refs (core->anal, f);
r_list_foreach (refs1, iter, ref) {
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
if (ref->type != 'c' && ref->type != 'C') {
continue;
}
r_core_anal_fcn (core, ref->addr, f->addr, R_ANAL_REF_TYPE_CALL, depth);
// recursively follow fcn->refs again and again
}
r_list_free (refs1);
} else {
f = r_anal_get_fcn_in (core->anal, fcn->addr, 0);
if (f) {
/* cut function */
r_anal_fcn_resize (core->anal, f, addr - fcn->addr);
r_core_anal_fcn (core, ref->addr, fcn->addr,
R_ANAL_REF_TYPE_CALL, depth);
f = r_anal_get_fcn_at (core->anal, fcn->addr, 0);
}
if (!f) {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", fcn->addr);
}
}
#endif
}
r_list_free (refs);
}
}
if (name) {
if (*name && !setFunctionName (core, addr, name, true)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, (ut64)addr);
}
free (name);
}
if (core->anal->opt.vars) {
r_list_foreach (core->anal->fcns, iter, fcni) {
if (r_cons_is_breaked ()) {
break;
}
r_core_recover_vars (core, fcni, true);
}
}
flag_every_function (core);
}
default:
return false;
break;
}
return true;
}
// size: 0: bits; -1: any; >0: exact size
static void __anal_reg_list(RCore *core, int type, int bits, char mode) {
RReg *hack = core->dbg->reg;
const char *use_color;
int use_colors = r_config_get_i (core->config, "scr.color");
if (use_colors) {
#undef ConsP
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg) : Color_BWHITE;
} else {
use_color = NULL;
}
if (bits < 0) {
// TODO Change the `size` argument of r_debug_reg_list to use -1 for any and 0 for anal->bits
bits = 0;
} else if (!bits) {
bits = core->anal->bits;
}
int mode2 = mode;
if (core->anal) {
core->dbg->reg = core->anal->reg;
if (core->anal->cur && core->anal->cur->arch) {
/* workaround for thumb */
if (!strcmp (core->anal->cur->arch, "arm") && bits == 16) {
bits = 32;
}
/* workaround for 6502 */
if (!strcmp (core->anal->cur->arch, "6502") && bits == 8) {
mode2 = mode == 'j' ? 'J' : mode;
if (mode == 'j') {
r_cons_printf ("{");
}
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode2, use_color); // XXX detect which one is current usage
if (mode == 'j') {
r_cons_printf (",");
}
}
if (!strcmp (core->anal->cur->arch, "avr") && bits == 8) {
mode2 = mode == 'j' ? 'J' : mode;
if (mode == 'j') {
r_cons_printf ("{");
}
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode2, use_color); // XXX detect which one is current usage
if (mode == 'j') {
r_cons_printf (",");
}
}
}
}
if (mode == '=') {
int pcbits = 0;
const char *pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
RRegItem *reg = r_reg_get (core->anal->reg, pcname, 0);
if (bits != reg->size) {
pcbits = reg->size;
}
if (pcbits) {
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, pcbits, 2, use_color); // XXX detect which one is current usage
}
}
r_debug_reg_list (core->dbg, type, bits, mode2, use_color);
if (mode2 == 'J') {
r_cons_print ("}\n");
}
core->dbg->reg = hack;
}
// XXX dup from drp :OOO
void cmd_anal_reg(RCore *core, const char *str) {
int size = 0, i, type = R_REG_TYPE_GPR;
int bits = (core->anal->bits & R_SYS_BITS_64)? 64: 32;
int use_colors = r_config_get_i (core->config, "scr.color");
struct r_reg_item_t *r;
const char *use_color;
const char *name;
char *arg;
if (use_colors) {
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg)
: Color_BWHITE;
} else {
use_color = NULL;
}
switch (str[0]) {
case 'l': // "arl"
{
RRegSet *rs = r_reg_regset_get (core->anal->reg, R_REG_TYPE_GPR);
if (rs) {
RRegItem *r;
RListIter *iter;
r_list_foreach (rs->regs, iter, r) {
r_cons_println (r->name);
}
}
} break;
case '0': // "ar0"
r_reg_arena_zero (core->anal->reg);
break;
case 'A': // "arA"
{
int nargs = 4;
RReg *reg = core->anal->reg;
for (i = 0; i < nargs; i++) {
const char *name = r_reg_get_name (reg, r_reg_get_name_idx (sdb_fmt ("A%d", i)));
ut64 off = r_reg_getv (core->anal->reg, name);
r_cons_printf ("0x%08"PFMT64x" ", off);
// XXX very ugly hack
char *s = r_core_cmd_strf (core, "pxr 32 @ 0x%08"PFMT64x, off);
if (s) {
char *nl = strchr (s, '\n');
if (nl) {
*nl = 0;
r_cons_printf ("%s\n", s);
}
free (s);
}
// r_core_cmd0 (core, "ar A0,A1,A2,A3");
}
}
break;
case 'C': // "arC"
if (core->anal->reg->reg_profile_cmt) {
r_cons_println (core->anal->reg->reg_profile_cmt);
}
break;
case 'w': // "arw"
switch (str[1]) {
case '?': {
r_core_cmd_help (core, help_msg_arw);
break;
}
case ' ':
r_reg_arena_set_bytes (core->anal->reg, str + 1);
break;
default:
r_core_cmd_help (core, help_msg_arw);
break;
}
break;
case 'a': // "ara"
switch (str[1]) {
case '?': // "ara?"
r_core_cmd_help (core, help_msg_ara);
break;
case 's': // "aras"
r_reg_arena_swap (core->anal->reg, false);
break;
case '+': // "ara+"
r_reg_arena_push (core->anal->reg);
break;
case '-': // "ara-"
r_reg_arena_pop (core->anal->reg);
break;
default: {
int i, j;
RRegArena *a;
RListIter *iter;
for (i = 0; i < R_REG_TYPE_LAST; i++) {
RRegSet *rs = &core->anal->reg->regset[i];
j = 0;
r_list_foreach (rs->pool, iter, a) {
r_cons_printf ("%s %p %d %d %s %d\n",
(a == rs->arena)? "*": ".", a,
i, j, r_reg_get_type (i), a->size);
j++;
}
}
} break;
}
break;
case '?': // "ar?"
if (str[1]) {
ut64 off = r_reg_getv (core->anal->reg, str + 1);
r_cons_printf ("0x%08" PFMT64x "\n", off);
} else {
r_core_cmd_help (core, help_msg_ar);
}
break;
case 'r': // "arr"
switch (str[1]) {
case 'j': // "arrj"
r_core_debug_rr (core, core->dbg->reg, 'j');
break;
default:
r_core_debug_rr (core, core->dbg->reg, 0);
break;
}
break;
case 'S': { // "arS"
int sz;
ut8 *buf = r_reg_get_bytes (core->anal->reg, R_REG_TYPE_GPR, &sz);
r_cons_printf ("%d\n", sz);
free (buf);
} break;
case 'b': { // "arb" WORK IN PROGRESS // DEBUG COMMAND
int len, type = R_REG_TYPE_GPR;
arg = strchr (str, ' ');
if (arg) {
char *string = r_str_trim (strdup (arg + 1));
if (string) {
type = r_reg_type_by_name (string);
if (type == -1 && string[0] != 'a') {
type = R_REG_TYPE_GPR;
}
free (string);
}
}
ut8 *buf = r_reg_get_bytes (core->dbg->reg, type, &len);
if (buf) {
r_print_hexdump (core->print, 0LL, buf, len, 32, 4, 1);
free (buf);
}
} break;
case 'c': // "arc"
// TODO: set flag values with drc zf=1
{
RRegItem *r;
const char *name = r_str_trim_ro (str + 1);
if (*name && name[1]) {
r = r_reg_cond_get (core->dbg->reg, name);
if (r) {
r_cons_println (r->name);
} else {
int id = r_reg_cond_from_string (name);
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
int o = r_reg_cond_bits (core->dbg->reg, id, rf);
core->num->value = o;
// ORLY?
r_cons_printf ("%d\n", o);
free (rf);
} else {
eprintf ("unknown conditional or flag register\n");
}
}
} else {
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
r_cons_printf ("| s:%d z:%d c:%d o:%d p:%d\n",
rf->s, rf->z, rf->c, rf->o, rf->p);
if (*name == '=') {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%s:%d ",
r_reg_cond_to_string (i),
r_reg_cond_bits (core->dbg->reg, i, rf));
}
r_cons_newline ();
} else {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%d %s\n",
r_reg_cond_bits (core->dbg->reg, i, rf),
r_reg_cond_to_string (i));
}
}
free (rf);
}
}
}
break;
case 's': // "ars"
switch (str[1]) {
case '-': // "ars-"
r_reg_arena_pop (core->dbg->reg);
// restore debug registers if in debugger mode
r_debug_reg_sync (core->dbg, R_REG_TYPE_GPR, true);
break;
case '+': // "ars+"
r_reg_arena_push (core->dbg->reg);
break;
case '?': { // "ars?"
// TODO #7967 help refactor: dup from drp
const char *help_msg[] = {
"Usage:", "drs", " # Register states commands",
"drs", "", "List register stack",
"drs+", "", "Push register state",
"drs-", "", "Pop register state",
NULL };
r_core_cmd_help (core, help_msg);
} break;
default:
r_cons_printf ("%d\n", r_list_length (
core->dbg->reg->regset[0].pool));
break;
}
break;
case 'p': // "arp"
// XXX we have to break out .h for these cmd_xxx files.
cmd_reg_profile (core, 'a', str);
break;
case 't': // "art"
for (i = 0; (name = r_reg_get_type (i)); i++)
r_cons_println (name);
break;
case 'n': // "arn"
if (*(str + 1) == '\0') {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
break;
}
name = r_reg_get_name (core->dbg->reg, r_reg_get_name_idx (str + 2));
if (name && *name) {
r_cons_println (name);
} else {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
}
break;
case 'd': // "ard"
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 3, use_color); // XXX detect which one is current usage
break;
case 'o': // "aro"
r_reg_arena_swap (core->dbg->reg, false);
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 0, use_color); // XXX detect which one is current usage
r_reg_arena_swap (core->dbg->reg, false);
break;
case '=': // "ar="
{
char *p = NULL;
char *bits = NULL;
if (str[1]) {
p = strdup (str + 1);
if (str[1] != ':') {
// Bits were specified
bits = strtok (p, ":");
if (r_str_isnumber (bits)) {
st64 sz = r_num_math (core->num, bits);
if (sz > 0) {
size = sz;
}
} else {
r_core_cmd_help (core, help_msg_ar);
break;
}
}
int len = bits ? strlen (bits) : 0;
if (str[len + 1] == ':') {
// We have some regs
char *regs = bits ? strtok (NULL, ":") : strtok ((char *)str + 1, ":");
char *reg = strtok (regs, " ");
RList *q_regs = r_list_new ();
if (q_regs) {
while (reg) {
r_list_append (q_regs, reg);
reg = strtok (NULL, " ");
}
core->dbg->q_regs = q_regs;
}
}
}
__anal_reg_list (core, type, size, 2);
if (!r_list_empty (core->dbg->q_regs)) {
r_list_free (core->dbg->q_regs);
}
core->dbg->q_regs = NULL;
free (p);
}
break;
case '-': // "ar-"
case '*': // "ar*"
case 'R': // "arR"
case 'j': // "arj"
case '\0': // "ar"
__anal_reg_list (core, type, size, str[0]);
break;
case ' ': { // "ar "
arg = strchr (str + 1, '=');
if (arg) {
char *ostr, *regname;
*arg = 0;
ostr = r_str_trim (strdup (str + 1));
regname = r_str_trim_nc (ostr);
r = r_reg_get (core->dbg->reg, regname, -1);
if (!r) {
int role = r_reg_get_name_idx (regname);
if (role != -1) {
const char *alias = r_reg_get_name (core->dbg->reg, role);
r = r_reg_get (core->dbg->reg, alias, -1);
}
}
if (r) {
//eprintf ("%s 0x%08"PFMT64x" -> ", str,
// r_reg_get_value (core->dbg->reg, r));
r_reg_set_value (core->dbg->reg, r,
r_num_math (core->num, arg + 1));
r_debug_reg_sync (core->dbg, R_REG_TYPE_ALL, true);
//eprintf ("0x%08"PFMT64x"\n",
// r_reg_get_value (core->dbg->reg, r));
r_core_cmdf (core, ".dr*%d", bits);
} else {
eprintf ("ar: Unknown register '%s'\n", regname);
}
free (ostr);
return;
}
char name[32];
int i = 1, j;
while (str[i]) {
if (str[i] == ',') {
i++;
} else {
for (j = i; str[++j] && str[j] != ','; );
if (j - i + 1 <= sizeof name) {
r_str_ncpy (name, str + i, j - i + 1);
if (IS_DIGIT (name[0])) { // e.g. ar 32
__anal_reg_list (core, R_REG_TYPE_GPR, atoi (name), '\0');
} else if (showreg (core, name) > 0) { // e.g. ar rax
} else { // e.g. ar gpr ; ar all
type = r_reg_type_by_name (name);
// TODO differentiate ALL and illegal register types and print error message for the latter
__anal_reg_list (core, type, -1, '\0');
}
}
i = j;
}
}
}
}
}
static ut64 initializeEsil(RCore *core) {
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int exectrap = r_config_get_i (core->config, "esil.exectrap");
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return UT64_MAX;
}
ut64 addr;
RAnalEsil *esil = core->anal->esil;
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->exectrap = exectrap;
RList *entries = r_bin_get_entries (core->bin);
RBinAddr *entry = NULL;
RBinInfo *info = NULL;
if (entries && !r_list_empty (entries)) {
entry = (RBinAddr *)r_list_pop (entries);
info = r_bin_get_info (core->bin);
addr = info->has_va? entry->vaddr: entry->paddr;
r_list_push (entries, entry);
} else {
addr = core->offset;
}
r_reg_setv (core->anal->reg, name, addr);
// set memory read only
return addr;
}
R_API int r_core_esil_step(RCore *core, ut64 until_addr, const char *until_expr, ut64 *prev_addr) {
#define return_tail(x) { tail_return_value = x; goto tail_return; }
int tail_return_value = 0;
int ret;
ut8 code[32];
RAnalOp op = {0};
RAnalEsil *esil = core->anal->esil;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
bool breakoninvalid = r_config_get_i (core->config, "esil.breakoninvalid");
if (!esil) {
// TODO inititalizeEsil (core);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return 0;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
esil->cmd = r_core_esil_cmd;
ut64 addr = r_reg_getv (core->anal->reg, name);
r_cons_break_push (NULL, NULL);
repeat:
if (r_cons_is_breaked ()) {
eprintf ("[+] ESIL emulation interrupted at 0x%08" PFMT64x "\n", addr);
return_tail (0);
}
if (!esil) {
addr = initializeEsil (core);
esil = core->anal->esil;
if (!esil) {
return_tail (0);
}
} else {
esil->trap = 0;
addr = r_reg_getv (core->anal->reg, name);
//eprintf ("PC=0x%"PFMT64x"\n", (ut64)addr);
}
if (prev_addr) {
*prev_addr = addr;
}
if (esil->exectrap) {
if (!r_io_is_valid_offset (core->io, addr, R_PERM_X)) {
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute on non-executable memory\n");
return_tail (1);
}
}
r_asm_set_pc (core->assembler, addr);
// run esil pin command here
const char *pincmd = r_anal_pin_call (core->anal, addr);
if (pincmd) {
r_core_cmd0 (core, pincmd);
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if (addr != pc) {
return_tail (1);
}
}
int dataAlign = r_anal_archinfo (esil->anal, R_ANAL_ARCHINFO_DATA_ALIGN);
if (dataAlign > 1) {
if (addr % dataAlign) {
if (esil->cmd && esil->cmd_trap) {
esil->cmd (esil, esil->cmd_trap, addr, R_ANAL_TRAP_UNALIGNED);
}
if (breakoninvalid) {
r_cons_printf ("[ESIL] Stopped execution in an unaligned instruction (see e??esil.breakoninvalid)\n");
return_tail (0);
}
}
}
(void)r_io_read_at (core->io, addr, code, sizeof (code));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op, addr, code, sizeof (code), R_ANAL_OP_MASK_ESIL);
// if type is JMP then we execute the next N instructions
// update the esil pointer because RAnal.op() can change it
esil = core->anal->esil;
if (op.size < 1 || ret < 0) {
if (esil->cmd && esil->cmd_trap) {
esil->cmd (esil, esil->cmd_trap, addr, R_ANAL_TRAP_INVALID);
}
if (breakoninvalid) {
r_cons_printf ("[ESIL] Stopped execution in an invalid instruction (see e??esil.breakoninvalid)\n");
return_tail (0);
}
op.size = 1; // avoid inverted stepping
}
{
/* apply hint */
RAnalHint *hint = r_anal_hint_get (core->anal, addr);
r_anal_op_hint (&op, hint);
r_anal_hint_free (hint);
}
if (r_config_get_i (core->config, "cfg.r2wars")) {
// this is x86 and r2wars specific, shouldnt hurt outside x86
ut64 vECX = r_reg_getv (core->anal->reg, "ecx");
if (op.prefix & R_ANAL_OP_PREFIX_REP && vECX > 1) {
char *tmp = strstr (op.esil.ptr, ",ecx,?{,5,GOTO,}");
if (tmp) {
tmp[0] = 0;
}
op.esil.len -= 16;
} else {
r_reg_setv (core->anal->reg, name, addr + op.size);
}
} else {
r_reg_setv (core->anal->reg, name, addr + op.size);
}
if (ret) {
r_anal_esil_set_pc (esil, addr);
if (core->dbg->trace->enabled) {
RReg *reg = core->dbg->reg;
core->dbg->reg = core->anal->reg;
r_debug_trace_pc (core->dbg, addr);
core->dbg->reg = reg;
} else {
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
if (core->anal->cur && core->anal->cur->esil_post_loop) {
core->anal->cur->esil_post_loop (esil, &op);
}
r_anal_esil_stack_free (esil);
}
// only support 1 slot for now
if (op.delay) {
ut8 code2[32];
ut64 naddr = addr + op.size;
RAnalOp op2 = {0};
// emulate only 1 instruction
r_anal_esil_set_pc (esil, naddr);
(void)r_io_read_at (core->io, naddr, code2, sizeof (code2));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op2, naddr, code2, sizeof (code2), R_ANAL_OP_MASK_ESIL);
switch (op2.type) {
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CRET:
case R_ANAL_OP_TYPE_RET:
// branches are illegal in a delay slot
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute a branch in a delay slot\n");
return_tail (1);
break;
}
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op2.esil));
r_anal_op_fini (&op2);
}
tail_return_value = 1;
}
st64 follow = (st64)r_config_get_i (core->config, "dbg.follow");
if (follow > 0) {
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if ((pc < core->offset) || (pc > (core->offset + follow))) {
r_core_cmd0 (core, "sr PC");
}
}
// check breakpoints
ut64 pc = r_reg_getv (core->anal->reg, name);
if (r_bp_get_at (core->dbg->bp, pc)) {
r_cons_printf ("[ESIL] hit breakpoint at 0x%"PFMT64x "\n", pc);
return_tail (0);
}
// check addr
if (until_addr != UT64_MAX) {
if (pc == until_addr) {
return_tail (0);
}
goto repeat;
}
// check esil
if (esil && esil->trap) {
if (core->anal->esil->verbose) {
eprintf ("TRAP\n");
}
return_tail (0);
}
if (until_expr) {
if (r_anal_esil_condition (core->anal->esil, until_expr)) {
if (core->anal->esil->verbose) {
eprintf ("ESIL BREAK!\n");
}
return_tail (0);
}
goto repeat;
}
tail_return:
r_anal_op_fini (&op);
r_cons_break_pop ();
return tail_return_value;
}
R_API int r_core_esil_step_back(RCore *core) {
RAnalEsil *esil = core->anal->esil;
RListIter *tail;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
ut64 prev = 0;
ut64 end = r_reg_getv (core->anal->reg, name);
if (!esil || !(tail = r_list_tail (esil->sessions))) {
return 0;
}
RAnalEsilSession *before = (RAnalEsilSession *) tail->data;
if (!before) {
eprintf ("Cannot find any previous state here\n");
return 0;
}
eprintf ("NOTE: step back in esil is setting an initial state and stepping into pc is the same.\n");
eprintf ("NOTE: this is extremely wrong and poorly efficient. so don't use this feature unless\n");
eprintf ("NOTE: you are going to fix it by making it consistent with dts, which is also broken as hell\n");
eprintf ("Execute until 0x%08"PFMT64x"\n", end);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, end, NULL, &prev);
eprintf ("Before 0x%08"PFMT64x"\n", prev);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, prev, NULL, NULL);
return 1;
}
static void cmd_address_info(RCore *core, const char *addrstr, int fmt) {
ut64 addr, type;
if (!addrstr || !*addrstr) {
addr = core->offset;
} else {
addr = r_num_math (core->num, addrstr);
}
type = r_core_anal_address (core, addr);
int isp = 0;
switch (fmt) {
case 'j':
#define COMMA isp++? ",": ""
r_cons_printf ("{");
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("%s\"program\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("%s\"library\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("%s\"exec\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("%s\"read\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("%s\"write\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("%s\"flag\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("%s\"func\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("%s\"stack\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("%s\"heap\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("%s\"reg\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("%s\"ascii\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("%s\"sequence\":true", COMMA);
r_cons_print ("}");
break;
default:
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("program\n");
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("library\n");
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("exec\n");
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("read\n");
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("write\n");
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("flag\n");
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("func\n");
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("stack\n");
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("heap\n");
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("reg\n");
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("ascii\n");
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("sequence\n");
}
}
static void cmd_anal_info(RCore *core, const char *input) {
switch (input[0]) {
case '?':
eprintf ("Usage: ai @ rsp\n");
break;
case ' ':
cmd_address_info (core, input, 0);
break;
case 'j': // "aij"
cmd_address_info (core, input + 1, 'j');
break;
default:
cmd_address_info (core, NULL, 0);
break;
}
}
static void initialize_stack (RCore *core, ut64 addr, ut64 size) {
const char *mode = r_config_get (core->config, "esil.fillstack");
if (mode && *mode && *mode != '0') {
const ut64 bs = 4096 * 32;
ut64 i;
for (i = 0; i < size; i += bs) {
ut64 left = R_MIN (bs, size - i);
// r_core_cmdf (core, "wx 10203040 @ 0x%llx", addr);
switch (*mode) {
case 'd': // "debrujn"
r_core_cmdf (core, "wopD %"PFMT64u" @ 0x%"PFMT64x, left, addr + i);
break;
case 's': // "seq"
r_core_cmdf (core, "woe 1 0xff 1 4 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
case 'r': // "random"
r_core_cmdf (core, "woR %"PFMT64u" @ 0x%"PFMT64x"!0x%"PFMT64x, left, addr + i, left);
break;
case 'z': // "zero"
case '0':
r_core_cmdf (core, "wow 00 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
}
}
// eprintf ("[*] Initializing ESIL stack with pattern\n");
// r_core_cmdf (core, "woe 0 10 4 @ 0x%"PFMT64x, size, addr);
}
}
static void cmd_esil_mem(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
RIOMap *stack_map;
ut64 curoff = core->offset;
const char *patt = "";
ut64 addr = 0x100000;
ut32 size = 0xf0000;
char name[128];
RFlagItem *fi;
const char *sp, *pc;
char uri[32];
char nomalloc[256];
char *p;
if (!esil) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
if (*input == '?') {
eprintf ("Usage: aeim [addr] [size] [name] - initialize ESIL VM stack\n");
eprintf ("Default: 0x100000 0xf0000\n");
eprintf ("See ae? for more help\n");
return;
}
if (input[0] == 'p') {
fi = r_flag_get (core->flags, "aeim.stack");
if (fi) {
addr = fi->offset;
size = fi->size;
} else {
cmd_esil_mem (core, "");
}
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
return;
}
if (!*input) {
char *fi = sdb_get(core->sdb, "aeim.fd", 0);
if (fi) {
// Close the fd associated with the aeim stack
ut64 fd = sdb_atoi (fi);
(void)r_io_fd_close (core->io, fd);
}
}
addr = r_config_get_i (core->config, "esil.stack.addr");
size = r_config_get_i (core->config, "esil.stack.size");
patt = r_config_get (core->config, "esil.stack.pattern");
p = strncpy (nomalloc, input, 255);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
addr = r_num_math (core->num, p);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
size = (ut32)r_num_math (core->num, p);
if (size < 1) {
size = 0xf0000;
}
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
snprintf (name, sizeof (name), "mem.%s", p);
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
if (*input == '-') {
if (esil->stack_fd > 2) { //0, 1, 2 are reserved for stdio/stderr
r_io_fd_close (core->io, esil->stack_fd);
// no need to kill the maps, r_io_map_cleanup does that for us in the close
esil->stack_fd = 0;
} else {
eprintf ("Cannot deinitialize %s\n", name);
}
r_flag_unset_name (core->flags, name);
r_flag_unset_name (core->flags, "aeim.stack");
sdb_unset(core->sdb, "aeim.fd", 0);
// eprintf ("Deinitialized %s\n", name);
return;
}
snprintf (uri, sizeof (uri), "malloc://%d", (int)size);
esil->stack_fd = r_io_fd_open (core->io, uri, R_PERM_RW, 0);
if (!(stack_map = r_io_map_add (core->io, esil->stack_fd, R_PERM_RW, 0LL, addr, size))) {
r_io_fd_close (core->io, esil->stack_fd);
eprintf ("Cannot create map for tha stack, fd %d got closed again\n", esil->stack_fd);
esil->stack_fd = 0;
return;
}
r_io_map_set_name (stack_map, name);
// r_flag_set (core->flags, name, addr, size); //why is this here?
char val[128], *v;
v = sdb_itoa (esil->stack_fd, val, 10);
sdb_set(core->sdb, "aeim.fd", v, 0);
r_config_set_i (core->config, "io.va", true);
if (patt && *patt) {
switch (*patt) {
case '0':
// do nothing
break;
case 'd':
r_core_cmdf (core, "wopD %d @ 0x%"PFMT64x, size, addr);
break;
case 'i':
r_core_cmdf (core, "woe 0 255 1 @ 0x%"PFMT64x"!%d",addr, size);
break;
case 'w':
r_core_cmdf (core, "woe 0 0xffff 1 4 @ 0x%"PFMT64x"!%d",addr, size);
break;
}
}
// SP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_SP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// BP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_BP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// PC
pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
r_debug_reg_set (core->dbg, pc, curoff);
r_core_cmd0 (core, ".ar*");
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
r_core_seek (core, curoff, 0);
}
#if 0
static ut64 opc = UT64_MAX;
static ut8 *regstate = NULL;
static void esil_init (RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
int noNULL = r_config_get_i (core->config, "esil.noNULL");
opc = r_reg_getv (core->anal->reg, pc);
if (!opc || opc==UT64_MAX) {
opc = core->offset;
}
if (!core->anal->esil) {
int iotrap = r_config_get_i (core->config, "esil.iotrap");
ut64 stackSize = r_config_get_i (core->config, "esil.stack.size");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stackSize, iotrap, addrsize))) {
R_FREE (regstate);
return;
}
r_anal_esil_setup (core->anal->esil, core->anal, 0, 0, noNULL);
}
free (regstate);
regstate = r_reg_arena_peek (core->anal->reg);
}
static void esil_fini(RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
r_reg_arena_poke (core->anal->reg, regstate);
r_reg_setv (core->anal->reg, pc, opc);
R_FREE (regstate);
}
#endif
typedef struct {
RList *regs;
RList *regread;
RList *regwrite;
RList *inputregs;
} AeaStats;
static void aea_stats_init (AeaStats *stats) {
stats->regs = r_list_newf (free);
stats->regread = r_list_newf (free);
stats->regwrite = r_list_newf (free);
stats->inputregs = r_list_newf (free);
}
static void aea_stats_fini (AeaStats *stats) {
R_FREE (stats->regs);
R_FREE (stats->regread);
R_FREE (stats->regwrite);
R_FREE (stats->inputregs);
}
static bool contains(RList *list, const char *name) {
RListIter *iter;
const char *n;
r_list_foreach (list, iter, n) {
if (!strcmp (name, n))
return true;
}
return false;
}
static char *oldregread = NULL;
static RList *mymemxsr = NULL;
static RList *mymemxsw = NULL;
#define R_NEW_DUP(x) memcpy((void*)malloc(sizeof(x)), &(x), sizeof(x))
typedef struct {
ut64 addr;
int size;
} AeaMemItem;
static int mymemwrite(RAnalEsil *esil, ut64 addr, const ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsw, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsw, n);
}
return len;
}
static int mymemread(RAnalEsil *esil, ut64 addr, ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsr, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsr, n);
}
return len;
}
static int myregwrite(RAnalEsil *esil, const char *name, ut64 *val) {
AeaStats *stats = esil->user;
if (oldregread && !strcmp (name, oldregread)) {
r_list_pop (stats->regread);
R_FREE (oldregread)
}
if (!IS_DIGIT (*name)) {
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regwrite, name)) {
r_list_push (stats->regwrite, strdup (name));
}
}
return 0;
}
static int myregread(RAnalEsil *esil, const char *name, ut64 *val, int *len) {
AeaStats *stats = esil->user;
if (!IS_DIGIT (*name)) {
if (!contains (stats->inputregs, name)) {
if (!contains (stats->regwrite, name)) {
r_list_push (stats->inputregs, strdup (name));
}
}
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regread, name)) {
r_list_push (stats->regread, strdup (name));
}
}
return 0;
}
static void showregs (RList *list) {
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_print (reg);
if (iter->n) {
r_cons_printf (" ");
}
}
}
r_cons_newline();
}
static void showregs_json (RList *list) {
r_cons_printf ("[");
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_printf ("\"%s\"", reg);
if (iter->n) {
r_cons_printf (",");
}
}
}
r_cons_printf ("]");
}
static bool cmd_aea(RCore* core, int mode, ut64 addr, int length) {
RAnalEsil *esil;
int ptr, ops, ops_end = 0, len, buf_sz, maxopsize;
ut64 addr_end;
AeaStats stats;
const char *esilstr;
RAnalOp aop = R_EMPTY;
ut8 *buf;
RList* regnow;
if (!core) {
return false;
}
maxopsize = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (maxopsize < 1) {
maxopsize = 16;
}
if (mode & 1) {
// number of bytes / length
buf_sz = length;
} else {
// number of instructions / opcodes
ops_end = length;
if (ops_end < 1) {
ops_end = 1;
}
buf_sz = ops_end * maxopsize;
}
if (buf_sz < 1) {
buf_sz = maxopsize;
}
addr_end = addr + buf_sz;
buf = malloc (buf_sz);
if (!buf) {
return false;
}
(void)r_io_read_at (core->io, addr, (ut8 *)buf, buf_sz);
aea_stats_init (&stats);
//esil_init (core);
//esil = core->anal->esil;
r_reg_arena_push (core->anal->reg);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats1 = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
r_anal_esil_setup (esil, core->anal, romem, stats1, noNULL); // setup io
# define hasNext(x) (x&1) ? (addr<addr_end) : (ops<ops_end)
mymemxsr = r_list_new ();
mymemxsw = r_list_new ();
esil->user = &stats;
esil->cb.hook_reg_write = myregwrite;
esil->cb.hook_reg_read = myregread;
esil->cb.hook_mem_write = mymemwrite;
esil->cb.hook_mem_read = mymemread;
esil->nowrite = true;
for (ops = ptr = 0; ptr < buf_sz && hasNext (mode); ops++, ptr += len) {
len = r_anal_op (core->anal, &aop, addr + ptr, buf + ptr, buf_sz - ptr, R_ANAL_OP_MASK_ESIL);
esilstr = R_STRBUF_SAFEGET (&aop.esil);
if (len < 1) {
eprintf ("Invalid 0x%08"PFMT64x" instruction %02x %02x\n",
addr + ptr, buf[ptr], buf[ptr + 1]);
break;
}
if (r_config_get_i (core->config, "cfg.r2wars")) {
if (aop.prefix & R_ANAL_OP_PREFIX_REP) {
char * tmp = strstr (esilstr, ",ecx,?{,5,GOTO,}");
if (tmp) {
tmp[0] = 0;
}
}
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_stack_free (esil);
r_anal_op_fini (&aop);
}
esil->nowrite = false;
esil->cb.hook_reg_write = NULL;
esil->cb.hook_reg_read = NULL;
//esil_fini (core);
r_anal_esil_free (esil);
r_reg_arena_pop (core->anal->reg);
regnow = r_list_newf (free);
{
RListIter *iter;
char *reg;
r_list_foreach (stats.regs, iter, reg) {
if (!contains (stats.regwrite, reg)) {
r_list_push (regnow, strdup (reg));
}
}
}
if ((mode >> 5) & 1) {
RListIter *iter;
AeaMemItem *n;
int c = 0;
r_cons_printf ("f-mem.*\n");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf ("f mem.read.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
c = 0;
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf ("f mem.write.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
}
/* show registers used */
if ((mode >> 1) & 1) {
showregs (stats.regread);
} else if ((mode >> 2) & 1) {
showregs (stats.regwrite);
} else if ((mode >> 3) & 1) {
showregs (regnow);
} else if ((mode >> 4) & 1) {
r_cons_printf ("{\"A\":");
showregs_json (stats.regs);
r_cons_printf (",\"I\":");
showregs_json (stats.inputregs);
r_cons_printf (",\"R\":");
showregs_json (stats.regread);
r_cons_printf (",\"W\":");
showregs_json (stats.regwrite);
r_cons_printf (",\"N\":");
showregs_json (regnow);
r_cons_printf ("}");
r_cons_newline();
} else if ((mode >> 5) & 1) {
// nothing
} else {
r_cons_printf (" I: ");
showregs (stats.inputregs);
r_cons_printf (" A: ");
showregs (stats.regs);
r_cons_printf (" R: ");
showregs (stats.regread);
r_cons_printf (" W: ");
showregs (stats.regwrite);
r_cons_printf ("NW: ");
if (r_list_length (regnow)) {
showregs (regnow);
} else {
r_cons_newline();
}
RListIter *iter;
ut64 *n;
if (!r_list_empty (mymemxsr)) {
r_cons_printf ("@R:");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
if (!r_list_empty (mymemxsw)) {
r_cons_printf ("@W:");
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
}
r_list_free (mymemxsr);
r_list_free (mymemxsw);
mymemxsr = NULL;
mymemxsw = NULL;
aea_stats_fini (&stats);
free (buf);
R_FREE (regnow);
return true;
}
static void cmd_aespc(RCore *core, ut64 addr, int off) {
RAnalEsil *esil = core->anal->esil;
int i, j = 0;
int instr_size = 0;
ut8 *buf;
RAnalOp aop = {0};
int ret , bsize = R_MAX (64, core->blocksize);
const int mininstrsz = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
const int minopcode = R_MAX (1, mininstrsz);
const char *pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
RRegItem *r = r_reg_get (core->dbg->reg, pc, -1);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!esil) {
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
}
buf = malloc (bsize);
if (!buf) {
eprintf ("Cannot allocate %d byte(s)\n", bsize);
free (buf);
return;
}
if (addr == -1) {
addr = r_debug_reg_get (core->dbg, pc);
}
ut64 curpc = addr;
ut64 oldoff = core->offset;
for (i = 0, j = 0; j < off ; i++, j++) {
if (r_cons_is_breaked ()) {
break;
}
if (i >= (bsize - 32)) {
i = 0;
}
if (!i) {
r_io_read_at (core->io, addr, buf, bsize);
}
ret = r_anal_op (core->anal, &aop, addr, buf + i, bsize - i, R_ANAL_OP_MASK_BASIC);
instr_size += ret;
int inc = (core->search->align > 0)? core->search->align - 1: ret - 1;
if (inc < 0) {
inc = minopcode;
}
i += inc;
addr += inc;
r_anal_op_fini (&aop);
}
r_reg_set_value (core->dbg->reg, r, curpc);
r_core_esil_step (core, curpc + instr_size, NULL, NULL);
r_core_seek (core, oldoff, 1);
}
static const char _handler_no_name[] = "<no name>";
static int _aeli_iter(dictkv* kv, void* ud) {
RAnalEsilInterrupt* interrupt = kv->u;
r_cons_printf ("%3x: %s\n", kv->k, interrupt->handler->name ? interrupt->handler->name : _handler_no_name);
return 0;
}
static void r_anal_aefa (RCore *core, const char *arg) {
ut64 to = r_num_math (core->num, arg);
ut64 at, from = core->offset;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, to, -1);
if (!from || from == UT64_MAX) {
if (fcn) {
from = fcn->addr;
} else {
eprintf ("Usage: aefa [from] # if no from address is given, uses fcn.addr\n");
return;
}
}
eprintf ("Emulate from 0x%08"PFMT64x" to 0x%08"PFMT64x"\n", from, to);
eprintf ("Resolve call args for 0x%08"PFMT64x"\n", to);
// emulate
// XXX do not use commands, here, just use the api
r_core_cmd0 (core, "aeim"); // XXX
ut64 off = core->offset;
for (at = from; at < to ; at++) {
r_core_cmdf (core, "aepc 0x%08"PFMT64x, at);
r_core_cmd0 (core, "aeso");
r_core_seek (core, at, 1);
int delta = r_num_get (core->num, "$l");
if (delta < 1) {
break;
}
at += delta - 1;
}
r_core_seek (core, off, 1);
// the logic of identifying args by function types and
// show json format and arg name goes into arA
r_core_cmd0 (core, "arA");
#if 0
// get results
const char *fcn_type = r_type_func_ret (core->anal->sdb_types, fcn->name);
const char *key = resolve_fcn_name (core->anal, fcn->name);
RList *list = r_core_get_func_args (core, key);
if (!r_list_empty (list)) {
eprintf ("HAS signature\n");
}
int i, nargs = 3; // r_type_func_args_count (core->anal->sdb_types, fcn->name);
if (nargs > 0) {
int i;
eprintf ("NARGS %d (%s)\n", nargs, key);
for (i = 0; i < nargs; i++) {
ut64 v = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_STDCALL, i);
eprintf ("arg: 0x%08"PFMT64x"\n", v);
}
}
#endif
}
static void cmd_anal_esil(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
ut64 addr = core->offset;
ut64 adr ;
char *n, *n1;
int off;
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
ut64 until_addr = UT64_MAX;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
const char *until_expr = NULL;
RAnalOp *op = NULL;
switch (input[0]) {
case 'p': // "aep"
switch (input[1]) {
case 'c':
if (input[2] == ' ') {
// seek to this address
r_core_cmdf (core, "ar PC=%s", input + 3);
r_core_cmd0 (core, ".ar*");
} else {
eprintf ("Missing argument\n");
}
break;
case 0:
r_anal_pin_list (core->anal);
break;
case '-':
if (input[2])
addr = r_num_math (core->num, input + 2);
r_anal_pin_unset (core->anal, addr);
break;
case ' ':
r_anal_pin (core->anal, addr, input + 2);
break;
default:
r_core_cmd_help (core, help_msg_aep);
break;
}
break;
case 'r': // "aer"
// 'aer' is an alias for 'ar'
cmd_anal_reg (core, input + 1);
break;
case '*':
// XXX: this is wip, not working atm
if (core->anal->esil) {
r_cons_printf ("trap: %d\n", core->anal->esil->trap);
r_cons_printf ("trap-code: %d\n", core->anal->esil->trap_code);
} else {
eprintf ("esil vm not initialized. run `aei`\n");
}
break;
case ' ':
//r_anal_esil_eval (core->anal, input+1);
if (!esil) {
if (!(core->anal->esil = esil = r_anal_esil_new (stacksize, iotrap, addrsize)))
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 1);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
break;
case 's': // "aes"
// "aes" "aeso" "aesu" "aesue"
// aes -> single step
// aesb -> single step back
// aeso -> single step over
// aesu -> until address
// aesue -> until esil expression
switch (input[1]) {
case '?':
eprintf ("See: ae?~aes\n");
break;
case 'l': // "aesl"
{
ut64 pc = r_debug_reg_get (core->dbg, "PC");
RAnalOp *op = r_core_anal_op (core, pc, R_ANAL_OP_MASK_BASIC);
// TODO: honor hint
if (!op) {
break;
}
r_core_esil_step (core, UT64_MAX, NULL, NULL);
r_debug_reg_set (core->dbg, "PC", pc + op->size);
r_anal_esil_set_pc (esil, pc + op->size);
r_core_cmd0 (core, ".ar*");
r_anal_op_free (op);
} break;
case 'b': // "aesb"
if (!r_core_esil_step_back (core)) {
eprintf ("cannnot step back\n");
}
r_core_cmd0 (core, ".ar*");
break;
case 'u': // "aesu"
if (input[2] == 'e') {
until_expr = input + 3;
} else {
until_addr = r_num_math (core->num, input + 2);
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
case 'o': // "aeso"
// step over
op = r_core_anal_op (core, r_reg_getv (core->anal->reg,
r_reg_get_name (core->anal->reg, R_REG_NAME_PC)), R_ANAL_OP_MASK_BASIC);
if (op && op->type == R_ANAL_OP_TYPE_CALL) {
until_addr = op->addr + op->size;
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_anal_op_free (op);
r_core_cmd0 (core, ".ar*");
break;
case 'p': //"aesp"
n = strchr (input, ' ');
n1 = n ? strchr (n + 1, ' ') : NULL;
if ((!n || !n1) || (!(n + 1) || !(n1 + 1))) {
eprintf ("aesp [offset] [num]\n");
break;
}
adr = r_num_math (core->num, n + 1);
off = r_num_math (core->num, n1 + 1);
cmd_aespc (core, adr, off);
break;
case ' ':
n = strchr (input, ' ');
if (!(n + 1)) {
r_core_esil_step (core, until_addr, until_expr, NULL);
break;
}
off = r_num_math (core->num, n + 1);
cmd_aespc (core, -1, off);
break;
default:
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
}
break;
case 'c': // "aec"
if (input[1] == '?') { // "aec?"
r_core_cmd_help (core, help_msg_aec);
} else if (input[1] == 's') { // "aecs"
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
for (;;) {
if (!r_core_esil_step (core, UT64_MAX, NULL, NULL)) {
break;
}
r_core_cmd0 (core, ".ar*");
addr = r_num_get (core->num, pc);
op = r_core_anal_op (core, addr, R_ANAL_OP_MASK_BASIC);
if (!op) {
break;
}
if (op->type == R_ANAL_OP_TYPE_SWI) {
eprintf ("syscall at 0x%08" PFMT64x "\n", addr);
break;
} else if (op->type == R_ANAL_OP_TYPE_TRAP) {
eprintf ("trap at 0x%08" PFMT64x "\n", addr);
break;
}
r_anal_op_free (op);
op = NULL;
if (core->anal->esil->trap || core->anal->esil->trap_code) {
break;
}
}
if (op) {
r_anal_op_free (op);
op = NULL;
}
} else if (input[1] == 'c') { // "aecc"
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
for (;;) {
if (!r_core_esil_step (core, UT64_MAX, NULL, NULL)) {
break;
}
r_core_cmd0 (core, ".ar*");
addr = r_num_get (core->num, pc);
op = r_core_anal_op (core, addr, R_ANAL_OP_MASK_BASIC);
if (!op) {
break;
}
if (op->type == R_ANAL_OP_TYPE_CALL || op->type == R_ANAL_OP_TYPE_UCALL) {
eprintf ("call at 0x%08" PFMT64x "\n", addr);
break;
}
r_anal_op_free (op);
op = NULL;
if (core->anal->esil->trap || core->anal->esil->trap_code) {
break;
}
}
if (op) {
r_anal_op_free (op);
}
} else {
// "aec" -> continue until ^C
// "aecu" -> until address
// "aecue" -> until esil expression
if (input[1] == 'u' && input[2] == 'e')
until_expr = input + 3;
else if (input[1] == 'u')
until_addr = r_num_math (core->num, input + 2);
else until_expr = "0";
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
}
break;
case 'i': // "aei"
switch (input[1]) {
case 's': // "aeis"
case 'm': // "aeim"
cmd_esil_mem (core, input + 2);
break;
case 'p': // "aeip" // initialize pc = $$
r_core_cmd0 (core, "ar PC=$$");
break;
case '?':
cmd_esil_mem (core, "?");
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
r_anal_esil_free (esil);
core->anal->esil = NULL;
break;
case 0: //lolololol
r_anal_esil_free (esil);
// reinitialize
{
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (r_reg_getv (core->anal->reg, pc) == 0LL) {
r_core_cmd0 (core, "ar PC=$$");
}
}
if (!(esil = core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->verbose = (int)r_config_get_i (core->config, "esil.verbose");
/* restore user settings for interrupt handling */
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
break;
}
break;
case 'k': // "aek"
switch (input[1]) {
case '\0':
input = "123*";
/* fall through */
case ' ':
if (esil && esil->stats) {
char *out = sdb_querys (esil->stats, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else {
eprintf ("esil.stats is empty. Run 'aei'\n");
}
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
break;
}
break;
case 'l': // ael commands
switch (input[1]) {
case 'i': // aeli interrupts
switch (input[2]) {
case ' ': // "aeli" with arguments
if (!r_anal_esil_load_interrupts_from_lib (esil, input + 3)) {
eprintf ("Failed to load interrupts from '%s'.", input + 3);
}
break;
case 0: // "aeli" with no args
if (esil && esil->interrupts) {
dict_foreach (esil->interrupts, _aeli_iter, NULL);
}
break;
case 'r': // "aelir"
if (esil && esil->interrupts) {
RAnalEsilInterrupt* interrupt = dict_getu (esil->interrupts, r_num_math (core->num, input + 3));
r_anal_esil_interrupt_free (esil, interrupt);
}
break;
// TODO: display help?
}
}
break;
case 'f': // "aef"
if (input[1] == 'a') { // "aefa"
r_anal_aefa (core, r_str_trim_ro (input + 2));
} else {
RListIter *iter;
RAnalBlock *bb;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal,
core->offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
// emulate every instruction in the function recursively across all the basic blocks
r_list_foreach (fcn->bbs, iter, bb) {
ut64 pc = bb->addr;
ut64 end = bb->addr + bb->size;
RAnalOp op;
ut8 *buf;
int ret, bbs = end - pc;
if (bbs < 1 || bbs > 0xfffff) {
eprintf ("Invalid block size\n");
}
// eprintf ("[*] Emulating 0x%08"PFMT64x" basic block 0x%08" PFMT64x " - 0x%08" PFMT64x "\r[", fcn->addr, pc, end);
buf = calloc (1, bbs + 1);
r_io_read_at (core->io, pc, buf, bbs);
int left;
while (pc < end) {
left = R_MIN (end - pc, 32);
r_asm_set_pc (core->assembler, pc);
ret = r_anal_op (core->anal, &op, addr, buf, left, R_ANAL_OP_MASK_ESIL); // read overflow
if (ret) {
r_reg_set_value_by_role (core->anal->reg, R_REG_NAME_PC, pc);
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
pc += op.size;
} else {
pc += 4; // XXX
}
}
}
} else {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
}
} break;
case 't': // "aet"
switch (input[1]) {
case 'r': // "aetr"
{
// anal ESIL to REIL.
RAnalEsil *esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 2);
r_anal_esil_dumpstack (esil);
r_anal_esil_free (esil);
break;
}
case 's': // "aets"
switch (input[2]) {
case 0:
r_anal_esil_session_list (esil);
break;
case '+':
r_anal_esil_session_add (esil);
break;
default:
r_core_cmd_help (core, help_msg_aets);
break;
}
break;
default:
eprintf ("Unknown command. Use `aetr`.\n");
break;
}
break;
case 'A': // "aeA"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1 + (1<<1), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1 + (1<<2), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1 + (1<<3), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1 + (1<<4), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1 + (1<<5), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
}
} else {
cmd_aea (core, 1, core->offset, (int)r_num_math (core->num, input+2));
}
break;
case 'a': // "aea"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1<<1, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1<<2, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1<<3, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1<<4, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1<<5, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
// "aeafj"
if (fcn) {
switch (input[2]) {
case 'j': // "aeafj"
cmd_aea (core, 1<<4, fcn->addr, r_anal_fcn_size (fcn));
break;
default:
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
break;
}
break;
}
} else if (input[1] == 'b') { // "aeab"
RAnalBlock *bb = r_anal_bb_from_offset (core->anal, core->offset);
if (bb) {
switch (input[2]) {
case 'j': // "aeabj"
cmd_aea (core, 1<<4, bb->addr, bb->size);
break;
default:
cmd_aea (core, 1, bb->addr, bb->size);
break;
}
}
} else {
const char *arg = input[1]? input + 2: "";
ut64 len = r_num_math (core->num, arg);
cmd_aea (core, 0, core->offset, len);
}
break;
case 'x': { // "aex"
char *hex;
int ret, bufsz;
input = r_str_trim_ro (input + 1);
hex = strdup (input);
if (!hex) {
break;
}
RAnalOp aop = R_EMPTY;
bufsz = r_hex_str2bin (hex, (ut8*)hex);
ret = r_anal_op (core->anal, &aop, core->offset,
(const ut8*)hex, bufsz, R_ANAL_OP_MASK_ESIL);
if (ret>0) {
const char *str = R_STRBUF_SAFEGET (&aop.esil);
char *str2 = r_str_newf (" %s", str);
cmd_anal_esil (core, str2);
free (str2);
}
r_anal_op_fini (&aop);
break;
}
case '?': // "ae?"
if (input[1] == '?') {
r_core_cmd_help (core, help_detail_ae);
break;
}
/* fallthrough */
default:
r_core_cmd_help (core, help_msg_ae);
break;
}
}
static void cmd_anal_bytes(RCore *core, const char *input) {
int len = core->blocksize;
int tbs = len;
if (input[0]) {
len = (int)r_num_get (core->num, input + 1);
if (len > tbs) {
r_core_block_size (core, len);
}
}
core_anal_bytes (core, core->block, len, 0, input[0]);
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
}
static void cmd_anal_opcode(RCore *core, const char *input) {
int l, len = core->blocksize;
ut32 tbs = core->blocksize;
switch (input[0]) {
case 's': // "aos"
case 'j': // "aoj"
case 'e': // "aoe"
case 'r': {
int count = 1;
int obs = core->blocksize;
if (input[1] && input[2]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
l *= 8;
if (l > obs) {
r_core_block_size (core, l);
}
} else {
count = 1;
}
core_anal_bytes (core, core->block, core->blocksize, count, input[0]);
if (obs != core->blocksize) {
r_core_block_size (core, obs);
}
}
break;
case 'm': // "aom"
if (input[1] == '?') {
r_cons_printf ("Usage: aom[ljd] [arg] .. list mnemonics for asm.arch\n");
r_cons_printf (". = current, l = list, d = describe, j=json)\n");
} else if (input[1] == 'd') {
const int id = (input[2]==' ')
?(int)r_num_math (core->num, input + 2): -1;
char *ops = r_asm_mnemonics (core->assembler, id, false);
if (ops) {
char *ptr = ops;
char *nl = strchr (ptr, '\n');
while (nl) {
*nl = 0;
char *desc = r_asm_describe (core->assembler, ptr);
if (desc) {
const char *pad = r_str_pad (' ', 16 - strlen (ptr));
r_cons_printf ("%s%s%s\n", ptr, pad, desc);
free (desc);
} else {
r_cons_printf ("%s\n", ptr);
}
ptr = nl + 1;
nl = strchr (ptr, '\n');
}
free (ops);
}
} else if (input[1] == 'l' || input[1] == '=' || input[1] == ' ' || input[1] == 'j') {
if (input[1] == ' ' && !IS_DIGIT (input[2])) {
r_cons_printf ("%d\n", r_asm_mnemonics_byname (core->assembler, input + 2));
} else {
const int id = (input[1] == ' ')
?(int)r_num_math (core->num, input + 2): -1;
char *ops = r_asm_mnemonics (core->assembler, id, input[1] == 'j');
if (ops) {
r_cons_println (ops);
free (ops);
}
}
} else {
r_core_cmd0 (core, "ao~mnemonic[1]");
}
break;
case 'd': // "aod"
if (input[1] == 'a') { // "aoda"
// list sdb database
sdb_foreach (core->assembler->pair, listOpDescriptions, core);
} else if (input[1] == 0) {
int cur = R_MAX (core->print->cur, 0);
// XXX: we need cmd_xxx.h (cmd_anal.h)
core_anal_bytes (core, core->block + cur, core->blocksize, 1, 'd');
} else if (input[1] == ' ') {
char *d = r_asm_describe (core->assembler, input + 2);
if (d && *d) {
r_cons_println (d);
free (d);
} else {
eprintf ("Unknown mnemonic\n");
}
} else {
eprintf ("Use: aod[?a] ([opcode]) describe current, [given] or all mnemonics\n");
}
break;
case '*':
r_core_anal_hint_list (core->anal, input[0]);
break;
case 0:
case ' ': {
int count = 0;
if (input[0]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
if (l > tbs) {
r_core_block_size (core, l * 4);
//len = l;
}
} else {
len = l = core->blocksize;
count = 1;
}
core_anal_bytes (core, core->block, len, count, 0);
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_ao);
break;
}
}
static void cmd_anal_jumps(RCore *core, const char *input) {
r_core_cmdf (core, "af @@= `ax~ref.code.jmp[1]`");
}
// TODO: cleanup to reuse code
static void cmd_anal_aftertraps(RCore *core, const char *input) {
int bufi, minop = 1; // 4
ut8 *buf;
RBinFile *binfile;
RAnalOp op = {0};
ut64 addr, addr_end;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
if (!binfile) {
eprintf ("cur binfile NULL\n");
return;
}
addr = core->offset;
if (!len) {
// ignore search.in to avoid problems. analysis != search
RIOSection *sec = r_io_section_vget (core->io, addr);
if (sec && (sec->perm & R_PERM_X)) {
// search in current section
if (sec->size > binfile->size) {
addr = sec->vaddr;
if (binfile->size > sec->paddr) {
len = binfile->size - sec->paddr;
} else {
eprintf ("Opps something went wrong aac\n");
return;
}
} else {
addr = sec->vaddr;
len = sec->size;
}
} else {
if (sec && sec->vaddr != sec->paddr && binfile->size > (core->offset - sec->vaddr + sec->paddr)) {
len = binfile->size - (core->offset - sec->vaddr + sec->paddr);
} else {
if (binfile->size > core->offset) {
len = binfile->size - core->offset;
} else {
eprintf ("Oops invalid range\n");
len = 0;
}
}
}
}
addr_end = addr + len;
if (!(buf = malloc (4096))) {
return;
}
bufi = 0;
int trapcount = 0;
int nopcount = 0;
r_cons_break_push (NULL, NULL);
while (addr < addr_end) {
if (r_cons_is_breaked ()) {
break;
}
// TODO: too many ioreads here
if (bufi > 4000) {
bufi = 0;
}
if (!bufi) {
r_io_read_at (core->io, addr, buf, 4096);
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, 4096 - bufi, R_ANAL_OP_MASK_BASIC)) {
if (op.size < 1) {
// XXX must be +4 on arm/mips/.. like we do in disasm.c
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_TRAP) {
trapcount ++;
} else if (op.type == R_ANAL_OP_TYPE_NOP) {
nopcount ++;
} else {
if (nopcount > 1) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
nopcount = 0;
}
if (trapcount > 0) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
trapcount = 0;
}
}
} else {
op.size = minop;
}
addr += (op.size > 0)? op.size : 1;
bufi += (op.size > 0)? op.size : 1;
r_anal_op_fini (&op);
}
r_cons_break_pop ();
free (buf);
}
static void cmd_anal_blocks(RCore *core, const char *input) {
ut64 from , to;
char *arg = strchr (input, ' ');
r_cons_break_push (NULL, NULL);
if (!arg) {
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
RListIter *iter;
RIOMap* map;
if (!list) {
goto ctrl_c;
}
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
goto ctrl_c;
}
if (!from && !to) {
eprintf ("Cannot determine search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, (to - from), from);
}
}
} else {
ut64 sz = r_num_math (core->num, arg + 1);
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, sz, core->offset);
}
ctrl_c:
r_cons_break_pop ();
}
static void _anal_calls(RCore *core, ut64 addr, ut64 addr_end, bool printCommands, bool importsOnly) {
RAnalOp op;
int depth = r_config_get_i (core->config, "anal.depth");
const int addrbytes = core->io->addrbytes;
const int bsz = 4096;
int bufi = 0;
int bufi_max = bsz - 16;
if (addr_end - addr > UT32_MAX) {
return;
}
ut8 *buf = malloc (bsz);
ut8 *block0 = calloc (1, bsz);
ut8 *block1 = malloc (bsz);
if (!buf || !block0 || !block1) {
eprintf ("Error: cannot allocate buf or block\n");
free (buf);
free (block0);
free (block1);
return;
}
memset (block1, -1, bsz);
int minop = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (minop < 1) {
minop = 1;
}
int setBits = r_config_get_i (core->config, "asm.bits");
r_cons_break_push (NULL, NULL);
while (addr < addr_end && !r_cons_is_breaked ()) {
// TODO: too many ioreads here
if (bufi > bufi_max) {
bufi = 0;
}
if (!bufi) {
(void)r_io_read_at (core->io, addr, buf, bsz);
}
if (!memcmp (buf, block0, bsz) || !memcmp (buf, block1, bsz)) {
//eprintf ("Error: skipping uninitialized block \n");
addr += bsz;
continue;
}
RAnalHint *hint = r_anal_hint_get (core->anal, addr);
if (hint && hint->bits) {
setBits = hint->bits;
}
if (setBits != core->assembler->bits) {
r_config_set_i (core->config, "asm.bits", setBits);
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, bsz - bufi, 0) > 0) {
if (op.size < 1) {
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_CALL) {
bool isValidCall = true;
if (importsOnly) {
RFlagItem *f = r_flag_get_i (core->flags, op.jump);
if (!f || !strstr (f->name, "imp.")) {
isValidCall = false;
}
}
if (isValidCall) {
#if JAYRO_03
if (!anal_is_bad_call (core, from, to, addr, buf, bufi)) {
fcn = r_anal_get_fcn_in (core->anal, op.jump, R_ANAL_FCN_TYPE_ROOT);
if (!fcn) {
r_core_anal_fcn (core, op.jump, addr, R_ANAL_REF_TYPE_CALL, depth);
}
}
#else
if (printCommands) {
r_cons_printf ("ax 0x%08" PFMT64x " 0x%08" PFMT64x "\n", op.jump, addr);
} else {
// add xref here
r_anal_xrefs_set (core->anal, addr, op.jump, R_ANAL_REF_TYPE_CALL);
if (r_io_is_valid_offset (core->io, op.jump, 1)) {
r_core_anal_fcn (core, op.jump, addr, R_ANAL_REF_TYPE_CALL, depth);
}
}
#endif
}
}
} else {
op.size = minop;
}
if ((int)op.size < 1) {
op.size = minop;
}
addr += op.size;
bufi += addrbytes * op.size;
r_anal_op_fini (&op);
}
r_cons_break_pop ();
free (buf);
free (block0);
free (block1);
}
static void cmd_anal_calls(RCore *core, const char *input, bool printCommands, bool importsOnly) {
RList *ranges = NULL;
RIOMap *r;
RBinFile *binfile;
ut64 addr;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
addr = core->offset;
if (binfile) {
if (len) {
RIOMap *m = R_NEW0 (RIOMap);
m->itv.addr = addr;
m->itv.size = len;
ranges = r_list_newf ((RListFree)free);
r_list_append (ranges, m);
} else {
ranges = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
}
}
r_cons_break_push (NULL, NULL);
if (!binfile || (ranges && !r_list_length (ranges))) {
RListIter *iter;
RIOMap *map;
r_list_free (ranges);
ranges = r_core_get_boundaries_prot (core, 0, NULL, "anal");
if (ranges) {
r_list_foreach (ranges, iter, map) {
ut64 addr = map->itv.addr;
_anal_calls (core, addr, r_itv_end (map->itv), printCommands, importsOnly);
}
}
} else {
RListIter *iter;
if (binfile) {
r_list_foreach (ranges, iter, r) {
addr = r->itv.addr;
//this normally will happen on fuzzed binaries, dunno if with huge
//binaries as well
if (r_cons_is_breaked ()) {
break;
}
_anal_calls (core, addr, r_itv_end (r->itv), printCommands, importsOnly);
}
}
}
r_cons_break_pop ();
r_list_free (ranges);
}
static void cmd_asf(RCore *core, const char *input) {
char *ret;
if (input[0] == ' ') {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, input + 1);
} else {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, "*");
}
if (ret && *ret) {
r_cons_println (ret);
}
free (ret);
}
static void cmd_anal_syscall(RCore *core, const char *input) {
RSyscallItem *si;
RListIter *iter;
RList *list;
RNum *num = NULL;
char *out;
int n;
switch (input[0]) {
case 'c': // "asc"
if (input[1] == 'a') {
if (input[2] == ' ') {
if (!isalpha ((ut8)input[3]) && (n = r_num_math (num, input + 3)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si) {
r_cons_printf (".equ SYS_%s %s\n", si->name, syscallNumber (n));
}
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 3);
if (n != -1) {
r_cons_printf (".equ SYS_%s %s\n", input + 3, syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf (".equ SYS_%s %s\n",
si->name, syscallNumber (si->num));
}
r_list_free (list);
}
} else {
if (input[1] == ' ') {
if (!isalpha ((ut8)input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si) {
r_cons_printf ("#define SYS_%s %s\n", si->name, syscallNumber (n));
}
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("#define SYS_%s %s\n", input + 2, syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("#define SYS_%s %d\n",
si->name, syscallNumber (si->num));
}
r_list_free (list);
}
}
break;
case 'f': // "asf"
cmd_asf (core, input + 1);
break;
case 'l': // "asl"
if (input[1] == ' ') {
if (!isalpha ((ut8)input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si)
r_cons_println (si->name);
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("%s\n", syscallNumber (n));
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("%s = 0x%02x.%s\n",
si->name, si->swi, syscallNumber (si->num));
}
r_list_free (list);
}
break;
case 'j': // "asj"
list = r_syscall_list (core->anal->syscall);
r_cons_printf ("[");
r_list_foreach (list, iter, si) {
r_cons_printf ("{\"name\":\"%s\","
"\"swi\":\"%d\",\"num\":\"%d\"}",
si->name, si->swi, si->num);
if (iter->n) {
r_cons_printf (",");
}
}
r_cons_printf ("]\n");
r_list_free (list);
// JSON support
break;
case '\0':
cmd_syscall_do (core, -1, core->offset);
break;
case ' ':
cmd_syscall_do (core, (int)r_num_get (core->num, input + 1), -1);
break;
case 'k': // "ask"
if (input[1] == ' ') {
out = sdb_querys (core->anal->syscall->db, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else eprintf ("|ERROR| Usage: ask [query]\n");
break;
default:
case '?':
r_core_cmd_help (core, help_msg_as);
break;
}
}
static void anal_axg (RCore *core, const char *input, int level, Sdb *db, int opts) {
char arg[32], pre[128];
RListIter *iter;
RAnalRef *ref;
ut64 addr = core->offset;
bool is_json = opts & R_CORE_ANAL_JSON;
bool is_r2 = opts & R_CORE_ANAL_GRAPHBODY;
if (input && *input) {
addr = r_num_math (core->num, input);
}
// eprintf ("Path between 0x%08"PFMT64x" .. 0x%08"PFMT64x"\n", core->offset, addr);
int spaces = (level + 1) * 2;
if (spaces > sizeof (pre) - 4) {
spaces = sizeof (pre) - 4;
}
memset (pre, ' ', sizeof (pre));
strcpy (pre + spaces, "- ");
RList *xrefs = r_anal_xrefs_get (core->anal, addr);
if (!r_list_empty (xrefs)) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" %s\n", fcn->addr, fcn->name);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"fcn\","
"\"fcn_addr\":%"PFMT64u",\"name\":\"%s\",\"refs\":[",
addr, fcn->addr, fcn->name);
} else {
//if (sdb_add (db, fcn->name, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n",
pre + 2, addr, fcn->addr, fcn->name);
//}
}
} else {
if (is_r2) {
r_cons_printf ("age 0x%08"PFMT64x"\n", fcn->addr);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"refs\":[", addr);
} else {
//snprintf (arg, sizeof (arg), "0x%08"PFMT64x, addr);
//if (sdb_add (db, arg, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x"\n", pre+2, addr);
//}
}
}
}
r_list_foreach (xrefs, iter, ref) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, ref->addr, -1);
if (fcn) {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" %s\n", fcn->addr, fcn->name);
r_cons_printf ("age 0x%08"PFMT64x" 0x%08"PFMT64x"\n", fcn->addr, addr);
} else if (is_json) {
if (level == 0) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64u",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
} else {
r_cons_printf ("]}},{\"%"PFMT64u"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64u",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
}
} else {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n", pre, ref->addr, fcn->addr, fcn->name);
}
if (sdb_add (db, fcn->name, "1", 0)) {
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, fcn->addr);
anal_axg (core, arg, level + 1, db, opts);
} else {
if (is_json) {
r_cons_printf ("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
} else {
if (is_r2) {
r_cons_printf ("agn 0x%08"PFMT64x" ???\n", ref->addr);
r_cons_printf ("age 0x%08"PFMT64x" 0x%08"PFMT64x"\n", ref->addr, addr);
} else if (is_json) {
r_cons_printf ("{\"%"PFMT64u"\":{\"type\":\"???\",\"refs\":[", ref->addr);
} else {
r_cons_printf ("%s0x%08"PFMT64x" ???\n", pre, ref->addr);
}
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, ref->addr);
if (sdb_add (db, arg, "1", 0)) {
anal_axg (core, arg, level + 1, db, opts);
} else {
if (is_json) {
r_cons_printf ("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
if (is_json) {
r_cons_printf ("]}}");
if (level == 0) {
r_cons_printf ("\n");
}
}
r_list_free (xrefs);
}
static void cmd_anal_ucall_ref (RCore *core, ut64 addr) {
RAnalFunction * fcn = r_anal_get_fcn_at (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf (" ; %s", fcn->name);
} else {
r_cons_printf (" ; 0x%" PFMT64x, addr);
}
}
static char *get_buf_asm(RCore *core, ut64 from, ut64 addr, RAnalFunction *fcn, bool color) {
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
char str[512];
const int size = 12;
ut8 buf[12];
RAsmOp asmop = {0};
char *buf_asm = NULL;
bool asm_varsub = r_config_get_i (core->config, "asm.var.sub");
core->parser->pseudo = r_config_get_i (core->config, "asm.pseudo");
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
core->parser->localvar_only = r_config_get_i (core->config, "asm.var.subonly");
if (core->parser->relsub) {
core->parser->relsub_addr = from;
}
r_io_read_at (core->io, addr, buf, size);
r_asm_set_pc (core->assembler, addr);
r_asm_disassemble (core->assembler, &asmop, buf, size);
int ba_len = r_strbuf_length (&asmop.buf_asm) + 128;
char *ba = malloc (ba_len);
strcpy (ba, r_strbuf_get (&asmop.buf_asm));
if (asm_varsub) {
r_parse_varsub (core->parser, fcn, addr, asmop.size,
ba, ba, sizeof (asmop.buf_asm));
}
r_parse_filter (core->parser, addr, core->flags,
ba, str, sizeof (str), core->print->big_endian);
r_asm_op_set_asm (&asmop, ba);
free (ba);
if (color && has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false, fcn ? fcn->addr : 0);
} else {
buf_asm = r_str_new (str);
}
return buf_asm;
}
#define var_ref_list(a,d,t) sdb_fmt ("var.0x%"PFMT64x".%d.%d.%s",\
a, 1, d, (t == 'R')?"reads":"writes");
static bool cmd_anal_refs(RCore *core, const char *input) {
ut64 addr = core->offset;
switch (input[0]) {
case '-': { // "ax-"
RList *list;
RListIter *iter;
RAnalRef *ref;
char *cp_inp = strdup (input + 1);
char *ptr = r_str_trim_head (cp_inp);
if (!strcmp (ptr, "*")) { // "ax-*"
r_anal_xrefs_init (core->anal);
} else {
int n = r_str_word_set0 (ptr);
ut64 from = UT64_MAX, to = UT64_MAX;
switch (n) {
case 2:
from = r_num_math (core->num, r_str_word_get0 (ptr, 1));
//fall through
case 1: // get addr
to = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
to = core->offset;
break;
}
list = r_anal_xrefs_get (core->anal, to);
if (list) {
r_list_foreach (list, iter, ref) {
if (from != UT64_MAX && from == ref->addr) {
r_anal_xref_del (core->anal, ref->addr, ref->at);
}
if (from == UT64_MAX) {
r_anal_xref_del (core->anal, ref->addr, ref->at);
}
}
}
r_list_free (list);
}
free (cp_inp);
} break;
case 'g': // "axg"
{
Sdb *db = sdb_new0 ();
if (input[1] == '*') {
anal_axg (core, input + 2, 0, db, R_CORE_ANAL_GRAPHBODY); // r2 commands
} else if (input[1] == 'j') {
anal_axg (core, input + 2, 0, db, R_CORE_ANAL_JSON);
} else {
anal_axg (core, input[1] ? input + 2 : NULL, 0, db, 0);
}
sdb_free (db);
}
break;
case '\0': // "ax"
case 'j': // "axj"
case 'q': // "axq"
case '*': // "ax*"
r_anal_xrefs_list (core->anal, input[0]);
break;
case 't': { // "axt"
RList *list = NULL;
RAnalFunction *fcn;
RAnalRef *ref;
RListIter *iter;
char *space = strchr (input, ' ');
char *tmp = NULL;
char *name = space ? strdup (space + 1): NULL;
if (name && (tmp = strchr (name, ' '))) {
char *varname = tmp + 1;
*tmp = '\0';
RAnalFunction *fcn = r_anal_fcn_find_name (core->anal, name);
if (fcn) {
RAnalVar *var = r_anal_var_get_byname (core->anal, fcn->addr, varname);
if (var) {
const char *rvar = var_ref_list (fcn->addr, var->delta, 'R');
const char *wvar = var_ref_list (fcn->addr, var->delta, 'W');
char *res = sdb_get (core->anal->sdb_fcns, rvar, 0);
char *res1 = sdb_get (core->anal->sdb_fcns, wvar, 0);
const char *ref;
RListIter *iter;
RList *list = (res && *res)? r_str_split_list (res, ","): NULL;
RList *list1 = (res1 && *res1)? r_str_split_list (res1, ","): NULL;
r_list_join (list , list1);
r_list_foreach (list, iter, ref) {
ut64 addr = r_num_math (NULL, ref);
char *op = get_buf_asm (core, core->offset, addr, fcn, true);
r_cons_printf ("%s 0x%"PFMT64x" [DATA] %s\n", fcn? fcn->name : "(nofunc)", addr, op);
free (op);
}
free (res);
free (res1);
free (name);
r_anal_var_free (var);
r_list_free (list);
r_list_free (list1);
break;
}
}
}
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
list = r_anal_xrefs_get (core->anal, addr);
if (list) {
if (input[1] == 'q') { // "axtq"
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->addr);
}
} else if (input[1] == 'j') { // "axtj"
r_cons_printf ("[");
r_list_foreach (list, iter, ref) {
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
char *str = get_buf_asm (core, addr, ref->addr, fcn, false);
r_cons_printf ("{\"from\":%" PFMT64u ",\"type\":\"%s\",\"opcode\":\"%s\"",
ref->addr, r_anal_xrefs_type_tostring (ref->type), str);
if (fcn) {
r_cons_printf (",\"fcn_addr\":%"PFMT64u",\"fcn_name\":\"%s\"", fcn->addr, fcn->name);
}
RFlagItem *fi = r_flag_get_at (core->flags, fcn? fcn->addr: ref->addr, true);
if (fi) {
if (fcn && strcmp (fcn->name, fi->name)) {
r_cons_printf (",\"flag\":\"%s\"", fi->name);
}
if (fi->realname && strcmp (fi->name, fi->realname)) {
char *escaped = r_str_escape (fi->realname);
if (escaped) {
r_cons_printf (",\"realname\":\"%s\"", escaped);
free (escaped);
}
}
}
r_cons_printf ("}%s", iter->n? ",": "");
free (str);
}
r_cons_printf ("]");
r_cons_newline ();
} else if (input[1] == 'g') { // axtg
r_list_foreach (list, iter, ref) {
char *str = r_core_cmd_strf (core, "fd 0x%"PFMT64x, ref->addr);
if (!str) {
str = strdup ("?\n");
}
r_str_trim_tail (str);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", ref->addr, str);
free (str);
}
if (input[2] != '*') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", addr, fcn?fcn->name: "$$");
}
r_list_foreach (list, iter, ref) {
r_cons_printf ("age 0x%" PFMT64x " 0x%"PFMT64x"\n", ref->addr, addr);
}
} else if (input[1] == '*') { // axt*
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref)
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF type %d at 0x%" PFMT64x"%s\n",
ref->addr, ref->type, addr, iter->n? ",": "");
} else { // axt
RAnalFunction *fcn;
char *comment;
r_list_foreach (list, iter, ref) {
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
char *buf_asm = get_buf_asm (core, addr, ref->addr, fcn, true);
comment = r_meta_get_string (core->anal, R_META_TYPE_COMMENT, ref->addr);
char *buf_fcn = comment
? r_str_newf ("%s; %s", fcn ? fcn->name : "(nofunc)", strtok (comment, "\n"))
: r_str_newf ("%s", fcn ? fcn->name : "(nofunc)");
r_cons_printf ("%s 0x%" PFMT64x " [%s] %s\n",
buf_fcn, ref->addr, r_anal_xrefs_type_tostring (ref->type), buf_asm);
free (buf_asm);
free (buf_fcn);
}
}
} else {
if (input[1] == 'j') { // "axtj"
r_cons_print ("[]\n");
}
}
r_list_free (list);
} break;
case 'f':
if (input[1] == 'f') {
RAnalFunction * fcn = r_anal_get_fcn_in (core->anal, addr, 0);
RListIter *iter;
RAnalRef *refi;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, refi) {
RFlagItem *f = r_flag_get_at (core->flags, refi->addr, true);
const char *name = f ? f->name: "";
r_cons_printf ("%c 0x%08"PFMT64x" 0x%08"PFMT64x" %s\n",
refi->type == R_ANAL_REF_TYPE_CALL?'C':'J',
refi->at, refi->addr, name);
}
} else { // "axf"
ut8 buf[12];
RAsmOp asmop;
char *buf_asm = NULL;
RList *list, *list_ = NULL;
RAnalRef *ref;
RListIter *iter;
char *space = strchr (input, ' ');
RAnalFunction * fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
if (input[1] == '.') { // "axf."
list = list_ = r_anal_xrefs_get_from (core->anal, addr);
if (!list) {
list = r_anal_fcn_get_refs (core->anal, fcn);
}
} else {
list = r_anal_refs_get (core->anal, addr);
}
if (list) {
if (input[1] == 'q') { // "axfq"
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->at);
}
} else if (input[1] == 'j') { // "axfj"
r_cons_print ("[");
r_list_foreach (list, iter, ref) {
r_io_read_at (core->io, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_cons_printf ("{\"from\":%" PFMT64u ",\"to\":%" PFMT64u ",\"type\":\"%s\",\"opcode\":\"%s\"}%s",
ref->at, ref->addr, r_anal_xrefs_type_tostring (ref->type), r_asm_op_get_asm (&asmop), iter->n? ",": "");
}
r_cons_print ("]\n");
} else if (input[1] == '*') { // "axf*"
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref) {
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF from 0x%" PFMT64x "\n",
ref->at, ref->type, r_asm_op_get_asm (&asmop), iter->n? ",": "");
}
} else { // "axf"
char str[512];
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
r_list_foreach (list, iter, ref) {
r_io_read_at (core->io, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_parse_filter (core->parser, ref->at, core->flags, r_asm_op_get_asm (&asmop),
str, sizeof (str), core->print->big_endian);
if (has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false, fcn ? fcn->addr : 0);
} else {
buf_asm = r_str_new (str);
}
r_cons_printf ("%c 0x%" PFMT64x " %s",
ref->type, ref->at, buf_asm);
if (ref->type == R_ANAL_REF_TYPE_CALL) {
RAnalOp aop;
r_anal_op (core->anal, &aop, ref->at, buf, 12, R_ANAL_OP_MASK_BASIC);
if (aop.type == R_ANAL_OP_TYPE_UCALL) {
cmd_anal_ucall_ref (core, ref->addr);
}
}
r_cons_newline ();
free (buf_asm);
}
}
} else {
if (input[1] == 'j') { // "axfj"
r_cons_print ("[]\n");
}
}
r_list_free (list);
}
break;
case 'F': // "axF"
find_refs (core, input + 1);
break;
case 'C': // "axC"
case 'c': // "axc"
case 'd': // "axd"
case 's': // "axs"
case ' ': // "ax "
{
char *ptr = strdup (r_str_trim_head ((char *)input + 1));
int n = r_str_word_set0 (ptr);
ut64 at = core->offset;
ut64 addr = UT64_MAX;
RAnalRefType reftype = r_anal_xrefs_type (input[0]);
switch (n) {
case 2: // get at
at = r_num_math (core->num, r_str_word_get0 (ptr, 1));
/* fall through */
case 1: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
free (ptr);
return false;
}
r_anal_xrefs_set (core->anal, at, addr, reftype);
free (ptr);
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_ax);
break;
}
return true;
}
static void cmd_anal_hint(RCore *core, const char *input) {
switch (input[0]) {
case '?':
if (input[1]) {
ut64 addr = r_num_math (core->num, input + 1);
r_core_anal_hint_print (core->anal, addr, 0);
} else {
r_core_cmd_help (core, help_msg_ah);
}
break;
case '.': // "ah."
r_core_anal_hint_print (core->anal, core->offset, 0);
break;
case 'a': // "aha" set arch
if (input[1]) {
int i;
char *ptr = strdup (input + 2);
i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
r_anal_hint_set_arch (core->anal, core->offset, r_str_word_get0 (ptr, 0));
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_arch (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'b': // "ahb" set bits
if (input[1]) {
char *ptr = strdup (input + 2);
int bits;
int i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
bits = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_anal_hint_set_bits (core->anal, core->offset, bits);
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_bits (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'i': // "ahi"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_ahi);
} else if (input[1] == ' ') {
// You can either specify immbase with letters, or numbers
const int base =
(input[2] == 's') ? 1 :
(input[2] == 'b') ? 2 :
(input[2] == 'p') ? 3 :
(input[2] == 'o') ? 8 :
(input[2] == 'd') ? 10 :
(input[2] == 'h') ? 16 :
(input[2] == 'i') ? 32 : // ip address
(input[2] == 'S') ? 80 : // syscall
(int) r_num_math (core->num, input + 1);
r_anal_hint_set_immbase (core->anal, core->offset, base);
} else if (input[1] == '-') { // "ahi-"
r_anal_hint_set_immbase (core->anal, core->offset, 0);
} else {
eprintf ("|ERROR| Usage: ahi [base]\n");
}
break;
case 'h': // "ahh"
if (input[1] == '-') {
r_anal_hint_unset_high (core->anal, core->offset);
} else if (input[1] == ' ') {
r_anal_hint_set_high (core->anal, r_num_math (core->num, input + 1));
} else {
r_anal_hint_set_high (core->anal, core->offset);
}
break;
case 'c': // "ahc"
if (input[1] == ' ') {
r_anal_hint_set_jump (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_jump (core->anal, core->offset);
}
break;
case 'f': // "ahf"
if (input[1] == ' ') {
r_anal_hint_set_fail (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_fail (core->anal, core->offset);
}
break;
case 's': // "ahs" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_size (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_size (core->anal, core->offset);
} else {
eprintf ("Usage: ahs 16\n");
}
break;
case 'S': // "ahS" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_syntax (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_syntax (core->anal, core->offset);
} else {
eprintf ("Usage: ahS att\n");
}
break;
case 'o': // "aho" set opcode string
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
} else {
eprintf ("Usage: aho popall\n");
}
break;
case 'e': // "ahe" set ESIL string
if (input[1] == ' ') {
r_anal_hint_set_esil (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_esil (core->anal, core->offset);
} else {
eprintf ("Usage: ahe r0,pc,=\n");
}
break;
#if 0
case 'e': // set endian
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
}
break;
#endif
case 'p': // "ahp"
if (input[1] == ' ') {
r_anal_hint_set_pointer (core->anal, core->offset, r_num_math (core->num, input + 1));
} else if (input[1] == '-') { // "ahp-"
r_anal_hint_unset_pointer (core->anal, core->offset);
}
break;
case 'r': // "ahr"
if (input[1] == ' ') {
r_anal_hint_set_ret (core->anal, core->offset, r_num_math (core->num, input + 1));
} else if (input[1] == '-') { // "ahr-"
r_anal_hint_unset_ret (core->anal, core->offset);
}
case '*': // "ah*"
if (input[1] == ' ') {
char *ptr = strdup (r_str_trim_ro (input + 2));
r_str_word_set0 (ptr);
ut64 addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_core_anal_hint_print (core->anal, addr, '*');
} else {
r_core_anal_hint_list (core->anal, input[0]);
}
break;
case 'j': // "ahj"
case '\0': // "ah"
r_core_anal_hint_list (core->anal, input[0]);
break;
case '-': // "ah-"
if (input[1]) {
if (input[1] == '*') {
r_anal_hint_clear (core->anal);
} else {
char *ptr = strdup (r_str_trim_ro (input + 1));
ut64 addr;
int size = 1;
int i = r_str_word_set0 (ptr);
if (i == 2) {
size = r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
const char *a0 = r_str_word_get0 (ptr, 0);
if (a0 && *a0) {
addr = r_num_math (core->num, a0);
} else {
addr = core->offset;
}
r_anal_hint_del (core->anal, addr, size);
free (ptr);
}
} else {
r_anal_hint_clear (core->anal);
}
break;
}
}
static void agraph_print_node_gml(RANode *n, void *user) {
r_cons_printf (" node [\n"
" id %d\n"
" label \"%s\"\n"
" ]\n", n->gnode->idx, n->title);
}
static void agraph_print_edge_gml(RANode *from, RANode *to, void *user) {
r_cons_printf (" edge [\n"
" source %d\n"
" target %d\n"
" ]\n", from->gnode->idx, to->gnode->idx
);
}
static void agraph_print_node_dot(RANode *n, void *user) {
char *label = strdup (n->body);
//label = r_str_replace (label, "\n", "\\l", 1);
if (!label || !*label) {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\"]\n",
n->title, n->title, n->title);
} else {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\\n%s\"]\n",
n->title, n->title, n->title, label);
}
free (label);
}
static void agraph_print_node(RANode *n, void *user) {
char *encbody, *cmd;
int len = strlen (n->body);
if (len > 0 && n->body[len - 1] == '\n') {
len--;
}
encbody = r_base64_encode_dyn (n->body, len);
cmd = r_str_newf ("agn \"%s\" base64:%s\n", n->title, encbody);
r_cons_printf (cmd);
free (cmd);
free (encbody);
}
static char *getViewerPath() {
int i;
const char *viewers[] = {
#if __WINDOWS__
"explorer",
#else
"open",
"geeqie",
"gqview",
"eog",
"xdg-open",
#endif
NULL
};
for (i = 0; viewers[i]; i++) {
char *viewerPath = r_file_path (viewers[i]);
if (viewerPath && strcmp (viewerPath, viewers[i])) {
return viewerPath;
}
free (viewerPath);
}
return NULL;
}
static char* graph_cmd(RCore *core, char *r2_cmd, const char *save_path) {
const char *dot = "dot";
char *cmd = NULL;
const char *ext = r_config_get (core->config, "graph.gv.format");
char *dotPath = r_file_path (dot);
if (!strcmp (dotPath, dot)) {
free (dotPath);
dot = "xdot";
dotPath = r_file_path (dot);
if (!strcmp (dotPath, dot)) {
free (dotPath);
return r_str_new ("agf");
}
}
if (save_path && *save_path) {
cmd = r_str_newf ("%s > a.dot;!%s -T%s -o%s a.dot;",
r2_cmd, dot, ext, save_path);
} else {
char *viewer = getViewerPath();
if (viewer) {
cmd = r_str_newf ("%s > a.dot;!%s -T%s -oa.%s a.dot;!%s a.%s",
r2_cmd, dot, ext, ext, viewer, ext);
free (viewer);
} else {
eprintf ("Cannot find a valid picture viewer\n");
}
}
free (dotPath);
return cmd;
}
static void agraph_print_edge_dot(RANode *from, RANode *to, void *user) {
r_cons_printf ("\"%s\" -> \"%s\"\n", from->title, to->title);
}
static void agraph_print_edge(RANode *from, RANode *to, void *user) {
r_cons_printf ("age \"%s\" \"%s\"\n", from->title, to->title);
}
static void cmd_agraph_node(RCore *core, const char *input) {
switch (*input) {
case ' ': { // "agn"
char *newbody = NULL;
char **args, *body;
int n_args, B_LEN = strlen ("base64:");
input++;
args = r_str_argv (input, &n_args);
if (n_args < 1 || n_args > 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
// strdup cause there is double free in r_str_argv_free due to a realloc call
if (n_args > 1) {
body = strdup (args[1]);
if (strncmp (body, "base64:", B_LEN) == 0) {
body = r_str_replace (body, "\\n", "", true);
newbody = (char *)r_base64_decode_dyn (body + B_LEN, -1);
free (body);
if (!newbody) {
eprintf ("Cannot allocate buffer\n");
r_str_argv_free (args);
break;
}
body = newbody;
}
body = r_str_append (body, "\n");
} else {
body = strdup ("");
}
r_agraph_add_node (core->graph, args[0], body);
r_str_argv_free (args);
free (body);
//free newbody it's not necessary since r_str_append reallocate the space
break;
}
case '-': { // "agn-"
char **args;
int n_args;
input++;
args = r_str_argv (input, &n_args);
if (n_args != 1) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
r_agraph_del_node (core->graph, args[0]);
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_agn);
break;
}
}
static void cmd_agraph_edge(RCore *core, const char *input) {
switch (*input) {
case ' ': // "age"
case '-': { // "age-"
RANode *u, *v;
char **args;
int n_args;
args = r_str_argv (input + 1, &n_args);
if (n_args != 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
u = r_agraph_get_node (core->graph, args[0]);
v = r_agraph_get_node (core->graph, args[1]);
if (!u || !v) {
if (!u) {
r_cons_printf ("Node %s not found!\n", args[0]);
} else {
r_cons_printf ("Node %s not found!\n", args[1]);
}
r_str_argv_free (args);
break;
}
if (*input == ' ') {
r_agraph_add_edge (core->graph, u, v);
} else {
r_agraph_del_edge (core->graph, u, v);
}
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_age);
break;
}
}
static void cmd_agraph_print(RCore *core, const char *input) {
switch (*input) {
case 0:
core->graph->can->linemode = r_config_get_i (core->config, "graph.linemode");
core->graph->can->color = r_config_get_i (core->config, "scr.color");
r_agraph_set_title (core->graph,
r_config_get (core->config, "graph.title"));
r_agraph_print (core->graph);
break;
case 't':{ // "aggt" - tiny graph
core->graph->is_tiny = true;
int e = r_config_get_i (core->config, "graph.edges");
r_config_set_i (core->config, "graph.edges", 0);
r_core_visual_graph (core, core->graph, NULL, false);
r_config_set_i (core->config, "graph.edges", e);
core->graph->is_tiny = false;
break;
}
case 'k': // "aggk"
{
Sdb *db = r_agraph_get_sdb (core->graph);
char *o = sdb_querys (db, "null", 0, "*");
r_cons_print (o);
free (o);
break;
}
case 'v': // "aggv"
case 'i': // "aggi" - open current core->graph in interactive mode
{
RANode *ran = r_agraph_get_first_node (core->graph);
if (ran) {
r_agraph_set_title (core->graph, r_config_get (core->config, "graph.title"));
r_agraph_set_curnode (core->graph, ran);
core->graph->force_update_seek = true;
core->graph->need_set_layout = true;
core->graph->layout = r_config_get_i (core->config, "graph.layout");
int ov = r_config_get_i (core->config, "scr.interactive");
core->graph->need_update_dim = true;
r_core_visual_graph (core, core->graph, NULL, true);
r_config_set_i (core->config, "scr.interactive", ov);
r_cons_show_cursor (true);
r_cons_enable_mouse (false);
} else {
eprintf ("This graph contains no nodes\n");
}
break;
}
case 'd': { // "aggd" - dot format
const char *font = r_config_get (core->config, "graph.font");
r_cons_printf ("digraph code {\ngraph [bgcolor=white];\n"
"node [color=lightgray, style=filled shape=box "
"fontname=\"%s\" fontsize=\"8\"];\n", font);
r_agraph_foreach (core->graph, agraph_print_node_dot, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge_dot, NULL);
r_cons_printf ("}\n");
break;
}
case '*': // "agg*" -
r_agraph_foreach (core->graph, agraph_print_node, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge, NULL);
break;
case 'J':
case 'j':
r_cons_printf ("{\"nodes\":[");
r_agraph_print_json (core->graph);
r_cons_printf ("]}\n");
break;
case 'g':
r_cons_printf ("graph\n[\n" "hierarchic 1\n" "label \"\"\n" "directed 1\n");
r_agraph_foreach (core->graph, agraph_print_node_gml, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge_gml, NULL);
r_cons_print ("]\n");
break;
case 'w':{ // "aggw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmd = graph_cmd (core, "aggd", input + 1);
if (cmd && *cmd) {
if (input[1]) {
r_cons_printf ("Saving to file %s ...\n", input + 1);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
}
break;
}
default:
eprintf ("Usage: see ag?\n");
}
}
static void cmd_anal_graph(RCore *core, const char *input) {
// Honor asm.graph=false in json as well
RConfigHold *hc = r_config_hold_new (core->config);
r_config_save_num (hc, "asm.offset", NULL);
const bool o_graph_offset = r_config_get_i (core->config, "graph.offset");
switch (input[0]) {
case 'f': // "agf"
switch (input[1]) {
case 0: // "agf"
r_core_visual_graph (core, NULL, NULL, false);
break;
case ' ':{ // "agf "
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_visual_graph (core, NULL, fcn, false);
break;
}
case 'v': // "agfv"
eprintf ("\rRendering graph...");
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (fcn) {
r_core_visual_graph (core, NULL, fcn, 1);
}
r_cons_enable_mouse (false);
r_cons_show_cursor (true);
break;
case 't': { // "agft" - tiny graph
int e = r_config_get_i (core->config, "graph.edges");
r_config_set_i (core->config, "graph.edges", 0);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_visual_graph (core, NULL, fcn, 2);
r_config_set_i (core->config, "graph.edges", e);
break;
}
case 'd': // "agfd"
if (input[2] == 'm') {
r_core_anal_graph (core, r_num_math (core->num, input + 3),
R_CORE_ANAL_GRAPHLINES);
} else {
r_core_anal_graph (core, r_num_math (core->num, input + 2),
R_CORE_ANAL_GRAPHBODY);
}
break;
case 'j': // "agfj"
r_core_anal_graph (core, r_num_math (core->num, input + 2), R_CORE_ANAL_JSON);
break;
case 'J': // "agfJ"
r_config_set_i (core->config, "asm.offset", o_graph_offset);
r_core_anal_graph (core, r_num_math (core->num, input + 2),
R_CORE_ANAL_JSON | R_CORE_ANAL_JSON_FORMAT_DISASM);
r_config_restore (hc);
r_config_hold_free (hc);
break;
case 'g':{ // "agfg"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_print_bb_gml (core, fcn);
break;
}
case 'k':{ // "agfk"
r_core_cmdf (core, "ag-; .agf* @ %"PFMT64u"; aggk", core->offset);
break;
}
case '*':{// "agf*"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
r_core_print_bb_custom (core, fcn);
break;
}
case 'w':// "agfw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmdargs = r_str_newf ("agfd @ 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 2);
if (cmd && *cmd) {
if (*(input + 2)) {
r_cons_printf ("Saving to file %s ...\n", input + 2);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
}
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case '-': // "ag-"
r_agraph_reset (core->graph);
break;
case 'n': // "agn"
cmd_agraph_node (core, input + 1);
break;
case 'e': // "age"
cmd_agraph_edge (core, input + 1);
break;
case 'g': // "agg"
cmd_agraph_print (core, input + 1);
break;
case 's': // "ags"
r_core_anal_graph (core, r_num_math (core->num, input + 1), 0);
break;
case 'C': // "agC"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case ' ':
case 0: {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agC*; agg%s;", input + 1);
core->graph->is_callgraph = false;
break;
}
case 'J':
case 'j':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_JSON);
break;
case 'g':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_GML);
break;
case 'd':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_DOT);
break;
case '*':
r_core_anal_callgraph (core, UT64_MAX, R_GRAPH_FORMAT_CMD);
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'r': // "agr" references graph
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ': {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agr* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
core->graph->is_callgraph = false;
break;
}
case '*': {
r_core_anal_coderefs (core, core->offset);
}
break;
case 0:
r_core_cmd0 (core, "ag-; .agr* $$; agg;");
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'R': // "agR" global refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0: {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agR*; agg%s;", input + 1);
core->graph->is_callgraph = false;
break;
}
case '*': {
ut64 from = r_config_get_i (core->config, "graph.from");
ut64 to = r_config_get_i (core->config, "graph.to");
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
if ((from == UT64_MAX && to == UT64_MAX) || R_BETWEEN (from, fcn->addr, to)) {
r_core_anal_coderefs (core, fcn->addr);
}
}
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'x': // "agx" cross refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ': {
r_core_cmdf (core, "ag-; .agx* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
break;
}
case '*': {
r_core_anal_codexrefs (core, core->offset);
}
break;
case 0:
r_core_cmd0 (core, "ag-; .agx* $$; agg;");
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'i': // "agi" import graph
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0:
r_core_cmdf (core, "ag-; .agi*; agg%s;", input + 1);
break;
case '*':
r_core_anal_importxrefs (core);
break;
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'c': // "agc"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case ' ': {
core->graph->is_callgraph = true;
r_core_cmdf (core, "ag-; .agc* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
core->graph->is_callgraph = false;
break;
}
case 0:
core->graph->is_callgraph = true;
r_core_cmd0 (core, "ag-; .agc* $$; agg;");
core->graph->is_callgraph = false;
break;
case 'g': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_GMLFCN);
break;
}
case 'd': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_DOT);
break;
}
case 'J':
case 'j': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_JSON);
break;
}
case '*': {
r_core_anal_callgraph (core, core->offset, R_GRAPH_FORMAT_CMD);
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'j': // "agj" alias for agfj
r_core_cmdf (core, "agfj%s", input + 1);
break;
case 'J': // "agJ" alias for agfJ
r_core_cmdf (core, "agfJ%s", input + 1);
break;
case 'k': // "agk" alias for agfk
r_core_cmdf (core, "agfk%s", input + 1);
break;
case 'l': // "agl"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_GRAPHLINES);
break;
case 'a': // "aga"
switch (input[1]) {
case 'v':
case 't':
case 'k':
case 'w':
case 'g':
case 'j':
case 'J':
case 'd':
case ' ': {
r_core_cmdf (core, "ag-; .aga* @ %"PFMT64u"; agg%s;", core->offset, input + 1);
break;
}
case 0:
r_core_cmd0 (core, "ag-; .aga* $$; agg;");
break;
case '*': {
r_core_anal_datarefs (core, core->offset);
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'A': // "agA" global data refs
switch (input[1]) {
case 'v':
case 't':
case 'd':
case 'J':
case 'j':
case 'g':
case 'k':
case 'w':
case ' ':
case 0: {
r_core_cmdf (core, "ag-; .agA*; agg%c;", input[1]);
break;
}
case '*': {
ut64 from = r_config_get_i (core->config, "graph.from");
ut64 to = r_config_get_i (core->config, "graph.to");
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
if ((from == UT64_MAX && to == UT64_MAX) || R_BETWEEN (from, fcn->addr, to)) {
r_core_anal_datarefs (core, fcn->addr);
}
}
break;
}
default:
eprintf ("Usage: see ag?\n");
break;
}
break;
case 'd': // "agd"
switch (input[1]) {
case 'v':
case 't':
case 'j':
case 'J':
case 'g':
case 'k':
case '*':
case ' ':
case 0:
eprintf ("Currently the only supported formats for the diff graph are 'agdd' and 'agdw'\n");
break;
case 'd': {
ut64 addr = input[2]? r_num_math (core->num, input + 2): core->offset;
r_core_gdiff_fcn (core, addr, core->offset);
r_core_anal_graph (core, addr, R_CORE_ANAL_GRAPHBODY | R_CORE_ANAL_GRAPHDIFF);
break;
}
case 'w': {
char *cmdargs = r_str_newf ("agdd 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 2);
if (cmd && *cmd) {
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
break;
}
}
break;
case 'v': // "agv" alias for "agfv"
r_core_cmdf (core, "agfv%s", input + 1);
break;
case 'w':// "agw"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
char *cmdargs = r_str_newf ("agfd @ 0x%"PFMT64x, core->offset);
char *cmd = graph_cmd (core, cmdargs, input + 1);
if (cmd && *cmd) {
if (input[1]) {
r_cons_printf ("Saving to file %s ...\n", input + 1);
r_cons_flush ();
}
r_core_cmd0 (core, cmd);
}
free (cmd);
free (cmdargs);
}
break;
default:
r_core_cmd_help (core, help_msg_ag);
break;
}
}
R_API int r_core_anal_refs(RCore *core, const char *input) {
int cfg_debug = r_config_get_i (core->config, "cfg.debug");
ut64 from, to;
char *ptr;
int rad, n;
if (*input == '?') {
r_core_cmd_help (core, help_msg_aar);
return 0;
}
if (*input == 'j' || *input == '*') {
rad = *input;
input++;
} else {
rad = 0;
}
from = to = 0;
ptr = r_str_trim_head (strdup (input));
n = r_str_word_set0 (ptr);
if (!n) {
// get boundaries of current memory map, section or io map
if (cfg_debug) {
RDebugMap *map = r_debug_map_get (core->dbg, core->offset);
if (map) {
from = map->addr;
to = map->addr_end;
}
} else {
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
RListIter *iter;
RIOMap* map;
if (!list) {
return 0;
}
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (!from && !to) {
eprintf ("Cannot determine xref search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_anal_search_xrefs (core, from, to, rad);
}
}
free (ptr);
r_list_free (list);
return 1;
}
} else if (n == 1) {
from = core->offset;
to = core->offset + r_num_math (core->num, r_str_word_get0 (ptr, 0));
} else {
eprintf ("Invalid number of arguments\n");
}
free (ptr);
if (from == UT64_MAX && to == UT64_MAX) {
return false;
}
if (!from && !to) {
return false;
}
if (to - from > r_io_size (core->io)) {
return false;
}
return r_core_anal_search_xrefs (core, from, to, rad);
}
static const char *oldstr = NULL;
static int compute_coverage(RCore *core) {
RListIter *iter;
SdbListIter *iter2;
RAnalFunction *fcn;
RIOSection *sec;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
ls_foreach (core->io->sections, iter2, sec) {
if (sec->perm & R_PERM_X) {
ut64 section_end = sec->vaddr + sec->vsize;
ut64 s = r_anal_fcn_realsize (fcn);
if (fcn->addr >= sec->vaddr && (fcn->addr + s) < section_end) {
cov += s;
}
}
}
}
return cov;
}
static int compute_code (RCore* core) {
int code = 0;
SdbListIter *iter;
RIOSection *sec;
ls_foreach (core->io->sections, iter, sec) {
if (sec->perm & R_PERM_X) {
code += sec->vsize;
}
}
return code;
}
static int compute_calls(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
RList *xrefs;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
xrefs = r_anal_fcn_get_xrefs (core->anal, fcn);
if (xrefs) {
cov += r_list_length (xrefs);
xrefs = NULL;
}
r_list_free (xrefs);
}
return cov;
}
static void r_core_anal_info (RCore *core, const char *input) {
int fcns = r_list_length (core->anal->fcns);
int strs = r_flag_count (core->flags, "str.*");
int syms = r_flag_count (core->flags, "sym.*");
int imps = r_flag_count (core->flags, "sym.imp.*");
int code = compute_code (core);
int covr = compute_coverage (core);
int call = compute_calls (core);
int xrfs = r_anal_xrefs_count (core->anal);
int cvpc = (code > 0)? (covr * 100 / code): 0;
if (*input == 'j') {
r_cons_printf ("{\"fcns\":%d", fcns);
r_cons_printf (",\"xrefs\":%d", xrfs);
r_cons_printf (",\"calls\":%d", call);
r_cons_printf (",\"strings\":%d", strs);
r_cons_printf (",\"symbols\":%d", syms);
r_cons_printf (",\"imports\":%d", imps);
r_cons_printf (",\"covrage\":%d", covr);
r_cons_printf (",\"codesz\":%d", code);
r_cons_printf (",\"percent\":%d}\n", cvpc);
} else {
r_cons_printf ("fcns %d\n", fcns);
r_cons_printf ("xrefs %d\n", xrfs);
r_cons_printf ("calls %d\n", call);
r_cons_printf ("strings %d\n", strs);
r_cons_printf ("symbols %d\n", syms);
r_cons_printf ("imports %d\n", imps);
r_cons_printf ("covrage %d\n", covr);
r_cons_printf ("codesz %d\n", code);
r_cons_printf ("percent %d%%\n", cvpc);
}
}
static void cmd_anal_aad(RCore *core, const char *input) {
RListIter *iter;
RAnalRef *ref;
RList *list = r_list_newf (NULL);
r_anal_xrefs_from (core->anal, list, "xref", R_ANAL_REF_TYPE_DATA, UT64_MAX);
r_list_foreach (list, iter, ref) {
if (r_io_is_valid_offset (core->io, ref->addr, false)) {
r_core_anal_fcn (core, ref->at, ref->addr, R_ANAL_REF_TYPE_NULL, 1);
}
}
r_list_free (list);
}
static bool archIsArmOrThumb(RCore *core) {
RAsm *as = core ? core->assembler : NULL;
if (as && as->cur && as->cur->arch) {
if (r_str_startswith (as->cur->arch, "mips")) {
return true;
}
if (r_str_startswith (as->cur->arch, "arm")) {
if (as->bits < 64) {
return true;
}
}
}
return false;
}
bool archIsMips (RCore *core) {
return strstr (core->assembler->cur->name, "mips");
}
void _CbInRangeAav(RCore *core, ut64 from, ut64 to, int vsize, bool asterisk, int count) {
bool isarm = archIsArmOrThumb (core);
if (isarm) {
if (to & 1) {
// .dword 0x000080b9 in reality is 0x000080b8
to--;
r_anal_hint_set_bits (core->anal, to, 16);
// can we assume is gonna be always a function?
} else {
r_core_seek_archbits (core, from);
ut64 bits = r_config_get_i (core->config, "asm.bits");
r_anal_hint_set_bits (core->anal, from, bits);
}
} else {
bool ismips = archIsMips (core);
if (ismips) {
if (from % 4 || to % 4) {
eprintf ("False positive\n");
return;
}
}
}
if (asterisk) {
r_cons_printf ("ax 0x%"PFMT64x " 0x%"PFMT64x "\n", to, from);
r_cons_printf ("Cd %d @ 0x%"PFMT64x "\n", vsize, from);
r_cons_printf ("f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
} else {
#if 1
r_anal_xrefs_set (core->anal, from, to, R_ANAL_REF_TYPE_NULL);
r_meta_add (core->anal, 'd', from, from + vsize, NULL);
if (!r_flag_get_at (core->flags, to, false)) {
char *name = r_str_newf ("aav.0x%08"PFMT64x, to);
r_flag_set (core->flags, name, to, vsize);
free (name);
}
#else
r_core_cmdf (core, "ax 0x%"PFMT64x " 0x%"PFMT64x, to, from);
r_core_cmdf (core, "Cd %d @ 0x%"PFMT64x, vsize, from);
r_core_cmdf (core, "f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
#endif
}
}
static void cmd_anal_aav(RCore *core, const char *input) {
#define seti(x,y) r_config_set_i(core->config, x, y);
#define geti(x) r_config_get_i(core->config, x);
ut64 o_align = geti ("search.align");
bool asterisk = strchr (input, '*');;
bool is_debug = r_config_get_i (core->config, "cfg.debug");
// pre
int archAlign = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_ALIGN);
seti ("search.align", archAlign);
int vsize = 4; // 32bit dword
if (core->assembler->bits == 64) {
vsize = 8;
}
// body
oldstr = r_print_rowlog (core->print, "Analyze value pointers (aav)");
r_print_rowlog_done (core->print, oldstr);
r_cons_break_push (NULL, NULL);
if (is_debug) {
RList *list = r_core_get_boundaries_prot (core, 0, "dbg.map", "anal");
RListIter *iter;
RIOMap *map;
if (!list) {
goto beach;
}
r_list_foreach (list, iter, map) {
if (r_cons_is_breaked ()) {
break;
}
oldstr = r_print_rowlog (core->print, sdb_fmt ("from 0x%"PFMT64x" to 0x%"PFMT64x" (aav)", map->itv.addr, r_itv_end (map->itv)));
r_print_rowlog_done (core->print, oldstr);
(void)r_core_search_value_in_range (core, map->itv,
map->itv.addr, r_itv_end (map->itv), vsize, asterisk, _CbInRangeAav);
}
r_list_free (list);
} else {
RList *list = r_core_get_boundaries_prot (core, 0, NULL, "anal");
if (!list) {
goto beach;
}
RListIter *iter, *iter2;
RIOMap *map, *map2;
ut64 from = UT64_MAX;
ut64 to = UT64_MAX;
// find values pointing to non-executable regions
r_list_foreach (list, iter2, map2) {
if (r_cons_is_breaked ()) {
break;
}
//TODO: Reduce multiple hits for same addr
from = r_itv_begin (map2->itv);
to = r_itv_end (map2->itv);
oldstr = r_print_rowlog (core->print, sdb_fmt ("Value from 0x%08"PFMT64x " to 0x%08" PFMT64x " (aav)", from, to));
r_print_rowlog_done (core->print, oldstr);
r_list_foreach (list, iter, map) {
ut64 begin = map->itv.addr;
ut64 end = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (end - begin > UT32_MAX) {
oldstr = r_print_rowlog (core->print, "Skipping huge range");
r_print_rowlog_done (core->print, oldstr);
continue;
}
oldstr = r_print_rowlog (core->print, sdb_fmt ("0x%08"PFMT64x"-0x%08"PFMT64x" in 0x%"PFMT64x"-0x%"PFMT64x" (aav)", from, to, begin, end));
r_print_rowlog_done (core->print, oldstr);
(void)r_core_search_value_in_range (core, map->itv, from, to, vsize, asterisk, _CbInRangeAav);
}
}
r_list_free (list);
}
beach:
r_cons_break_pop ();
// end
seti ("search.align", o_align);
}
static void cmd_anal_abt(RCore *core, const char *input) {
bool json = false;
switch (*input) {
case '?': r_core_cmd_help (core, help_msg_abt); break;
case 'j':
json = true;
input++;
case ' ': {
ut64 addr;
char *p;
int n = 1;
p = strchr (input + 1, ' ');
if (p) {
*p = '\0';
n = *(++p)? r_num_math (core->num, p): 1;
}
addr = r_num_math (core->num, input + 1);
RList *paths = r_core_anal_graph_to (core, addr, n);
if (paths) {
RAnalBlock *bb;
RList *path;
RListIter *pathi;
RListIter *bbi;
bool first_path = true, first_bb = true;
if (json) {
r_cons_printf ("[");
}
r_list_foreach (paths, pathi, path) {
if (json) {
if (!first_path) {
r_cons_printf (", ");
}
}
r_cons_printf ("[");
r_list_foreach (path, bbi, bb) {
if (json && !first_bb) {
r_cons_printf (", ");
}
r_cons_printf ("0x%08" PFMT64x, bb->addr);
if (!json) {
r_cons_printf ("\n");
}
first_bb = false;
}
r_cons_printf ("%s", json? "]": "\n");
first_bb = true;
first_path = false;
r_list_purge (path);
free (path);
}
if (json) {
r_cons_printf ("]\n");
}
r_list_purge (paths);
free (paths);
}
}
case '\0':
break;
}
}
static int cmd_anal_all(RCore *core, const char *input) {
switch (*input) {
case '?':
r_core_cmd_help (core, help_msg_aa);
break;
case 'b': // "aab"
cmd_anal_blocks (core, input + 1);
break;
case 'f': // "aaf"
{
const int analHasnext = r_config_get_i (core->config, "anal.hasnext");
r_config_set_i (core->config, "anal.hasnext", true);
r_core_cmd0 (core, "afr@@c:isq");
r_config_set_i (core->config, "anal.hasnext", analHasnext);
break;
}
case 'c': // "aac"
switch (input[1]) {
case '*': // "aac*"
cmd_anal_calls (core, input + 1, true, false);
break;
case 'i': // "aaci"
cmd_anal_calls (core, input + 1, input[2] == '*', true);
break;
case '?': // "aac?"
eprintf ("Usage: aac, aac* or aaci (imports xrefs only)\n");
break;
default: // "aac"
cmd_anal_calls (core, input + 1, false, false);
break;
}
case 'j': // "aaj"
cmd_anal_jumps (core, input + 1);
break;
case '*': // "aa*"
r_core_cmd0 (core, "af @@ sym.*");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'd': // "aad"
cmd_anal_aad (core, input);
break;
case 'v': // "aav"
cmd_anal_aav (core, input);
break;
case 'u': // "aau" - print areas not covered by functions
r_core_anal_nofunclist (core, input + 1);
break;
case 'i': // "aai"
r_core_anal_info (core, input + 1);
break;
case 's': // "aas"
r_core_cmd0 (core, "af @@= `isq~[0]`");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'n': // "aan"
switch (input[1]) {
case 'g': // "aang"
r_core_anal_autoname_all_golang_fcns (core);
break;
default: // "aan"
r_core_anal_autoname_all_fcns (core);
}
break;
case 'p': // "aap"
if (*input == '?') {
// TODO: accept parameters for ranges
eprintf ("Usage: /aap ; find in memory for function preludes");
} else {
r_core_search_preludes (core);
}
break;
case '\0': // "aa"
case 'a':
if (input[0] && (input[1] == '?' || (input[1] && input[2] == '?'))) {
r_cons_println ("Usage: See aa? for more help");
} else {
char *dh_orig = NULL;
if (!strncmp (input, "aaaaa", 5)) {
eprintf ("An r2 developer is coming to your place to manually analyze this program. Please wait for it\n");
if (r_config_get_i (core->config, "scr.interactive")) {
r_cons_any_key (NULL);
}
goto jacuzzi;
}
ut64 curseek = core->offset;
oldstr = r_print_rowlog (core->print, "Analyze all flags starting with sym. and entry0 (aa)");
r_cons_break_push (NULL, NULL);
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
r_core_anal_all (core);
r_print_rowlog_done (core->print, oldstr);
// Run pending analysis immediately after analysis
// Usefull when running commands with ";" or via r2 -c,-i
run_pending_anal (core);
dh_orig = core->dbg->h
? strdup (core->dbg->h->name)
: strdup ("esil");
if (core->io && core->io->desc && core->io->desc->plugin && !core->io->desc->plugin->isdbg) {
//use dh_origin if we are debugging
R_FREE (dh_orig);
}
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
r_cons_clear_line (1);
if (*input == 'a') { // "aaa"
if (r_str_startswith (r_config_get (core->config, "bin.lang"), "go")) {
oldstr = r_print_rowlog (core->print, "Find function and symbol names from golang binaries (aang)");
r_print_rowlog_done (core->print, oldstr);
r_core_anal_autoname_all_golang_fcns (core);
oldstr = r_print_rowlog (core->print, "Analyze all flags starting with sym.go. (aF @@ sym.go.*)");
r_core_cmd0 (core, "aF @@ sym.go.*");
r_print_rowlog_done (core->print, oldstr);
}
if (dh_orig && strcmp (dh_orig, "esil")) {
r_core_cmd0 (core, "dL esil");
}
int c = r_config_get_i (core->config, "anal.calls");
if (!r_str_startswith (r_config_get (core->config, "asm.arch"), "x86")) {
r_core_cmd0 (core, "aav");
bool ioCache = r_config_get_i (core->config, "io.pcache");
r_config_set_i (core->config, "io.pcache", 1);
oldstr = r_print_rowlog (core->print, "Emulate code to find computed references (aae)");
r_core_cmd0 (core, "aae $SS @ $S");
r_print_rowlog_done (core->print, oldstr);
if (!ioCache) {
r_core_cmd0 (core, "wc-*");
}
r_config_set_i (core->config, "io.pcache", ioCache);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
}
r_config_set_i (core->config, "anal.calls", 1);
r_core_cmd0 (core, "s $S");
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
oldstr = r_print_rowlog (core->print, "Analyze function calls (aac)");
(void)cmd_anal_calls (core, "", false, false); // "aac"
r_core_seek (core, curseek, 1);
// oldstr = r_print_rowlog (core->print, "Analyze data refs as code (LEA)");
// (void) cmd_anal_aad (core, NULL); // "aad"
r_print_rowlog_done (core->print, oldstr);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
oldstr = r_print_rowlog (core->print, "Analyze len bytes of instructions for references (aar)");
(void)r_core_anal_refs (core, ""); // "aar"
r_print_rowlog_done (core->print, oldstr);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
run_pending_anal (core);
r_config_set_i (core->config, "anal.calls", c);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
if (r_config_get_i (core->config, "anal.autoname")) {
oldstr = r_print_rowlog (core->print, "Constructing a function name for fcn.* and sym.func.* functions (aan)");
r_core_anal_autoname_all_fcns (core);
r_print_rowlog_done (core->print, oldstr);
}
if (core->anal->opt.vars) {
RAnalFunction *fcni;
RListIter *iter;
r_list_foreach (core->anal->fcns, iter, fcni) {
if (r_cons_is_breaked ()) {
break;
}
RList *list = r_anal_var_list (core->anal, fcni, 'r');
if (!r_list_empty (list)) {
r_list_free (list);
continue;
}
//extract only reg based var here
r_core_recover_vars (core, fcni, true);
r_list_free (list);
}
}
if (!sdb_isempty (core->anal->sdb_zigns)) {
oldstr = r_print_rowlog (core->print, "Check for zignature from zigns folder (z/)");
r_core_cmd0 (core, "z/");
r_print_rowlog_done (core->print, oldstr);
}
if (input[1] == 'a') { // "aaaa"
oldstr = r_print_rowlog (core->print, "Enable constraint types analysis for variables");
r_config_set (core->config, "anal.types.constraint", "true");
r_print_rowlog_done (core->print, oldstr);
} else {
oldstr = r_print_rowlog (core->print, "Type matching analysis for all functions (afta)");
r_core_cmd0 (core, "afta");
r_print_rowlog_done (core->print, oldstr);
oldstr = r_print_rowlog (core->print, "Use -AA or aaaa to perform additional experimental analysis.");
r_print_rowlog_done (core->print, oldstr);
}
r_core_cmd0 (core, "s-");
if (dh_orig) {
r_core_cmdf (core, "dL %s;dpa", dh_orig);
}
}
r_core_seek (core, curseek, 1);
jacuzzi:
flag_every_function (core);
r_cons_break_pop ();
R_FREE (dh_orig);
}
break;
case 't': { // "aat"
ut64 cur = core->offset;
bool hasnext = r_config_get_i (core->config, "anal.hasnext");
RListIter *iter;
RIOMap *map;
RList *list = r_core_get_boundaries_prot (core, R_PERM_X, NULL, "anal");
if (!list) {
break;
}
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_config_set_i (core->config, "anal.hasnext", 1);
r_core_cmd0 (core, "afr");
r_config_set_i (core->config, "anal.hasnext", hasnext);
}
r_list_free (list);
r_core_seek (core, cur, 1);
break;
}
case 'T': // "aaT"
cmd_anal_aftertraps (core, input + 1);
break;
case 'E': // "aaE"
r_core_cmd0 (core, "aef @@f");
break;
case 'e': // "aae"
if (input[1]) {
const char *len = (char *)input + 1;
char *addr = strchr (input + 2, ' ');
if (addr) {
*addr++ = 0;
}
r_core_anal_esil (core, len, addr);
} else {
ut64 at = core->offset;
RIOMap *map;
RListIter *iter;
RList *list = r_core_get_boundaries_prot (core, -1, NULL, "anal");
if (!list) {
break;
}
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_core_anal_esil (core, "$SS", NULL);
}
r_list_free (list);
r_core_seek (core, at, 1);
}
break;
case 'r':
(void)r_core_anal_refs (core, input + 1);
break;
default:
r_core_cmd_help (core, help_msg_aa);
break;
}
return true;
}
static bool anal_fcn_data (RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ut32 fcn_size = r_anal_fcn_size (fcn);
if (fcn) {
int i;
bool gap = false;
ut64 gap_addr = UT64_MAX;
char *bitmap = calloc (1, fcn_size);
if (bitmap) {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
int f = b->addr - fcn->addr;
int t = R_MIN (f + b->size, fcn_size);
if (f >= 0) {
while (f < t) {
bitmap[f++] = 1;
}
}
}
}
for (i = 0; i < fcn_size; i++) {
ut64 here = fcn->addr + i;
if (bitmap && bitmap[i]) {
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", here - gap_addr, gap_addr);
gap = false;
}
gap_addr = UT64_MAX;
} else {
if (!gap) {
gap = true;
gap_addr = here;
}
}
}
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", fcn->addr + fcn_size - gap_addr, gap_addr);
gap = false;
}
free (bitmap);
return true;
}
return false;
}
static bool anal_fcn_data_gaps (RCore *core, const char *input) {
ut64 end = UT64_MAX;
RAnalFunction *fcn;
RListIter *iter;
int i, wordsize = (core->assembler->bits == 64)? 8: 4;
r_list_sort (core->anal->fcns, cmpaddr);
r_list_foreach (core->anal->fcns, iter, fcn) {
if (end != UT64_MAX) {
int range = fcn->addr - end;
if (range > 0) {
for (i = 0; i + wordsize < range; i+= wordsize) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", wordsize, end + i);
}
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range - i, end + i);
//r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range, end);
}
}
end = fcn->addr + r_anal_fcn_size (fcn);
}
return true;
}
static void cmd_anal_rtti(RCore *core, const char *input) {
switch (input[0]) {
case '\0': // "avr"
case 'j': // "avrj"
r_anal_rtti_print_at_vtable (core->anal, core->offset, input[0]);
break;
case 'a': // "avra"
r_anal_rtti_print_all (core->anal, input[1]);
break;
case 'D': { // "avrD"
char *dup = strdup (input + 1);
if (!dup) {
break;
}
char *name = r_str_trim (dup);
char *demangled = r_anal_rtti_demangle_class_name (core->anal, dup);
free (name);
if (demangled) {
r_cons_println (demangled);
free (demangled);
}
break;
}
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static void cmd_anal_virtual_functions(RCore *core, const char* input) {
switch (input[0]) {
case '\0': // "av"
case '*': // "av*"
case 'j': // "avj"
r_anal_list_vtables (core->anal, input[0]);
break;
case 'r': // "avr"
cmd_anal_rtti (core, input + 1);
break;
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static int cmd_anal(void *data, const char *input) {
const char *r;
RCore *core = (RCore *)data;
ut32 tbs = core->blocksize;
switch (input[0]) {
case 'p': // "ap"
{
const ut8 *prelude = (const ut8*)"\xe9\x2d"; //:fffff000";
const int prelude_sz = 2;
const int bufsz = 4096;
ut8 *buf = calloc (1, bufsz);
ut64 off = core->offset;
if (input[1] == ' ') {
off = r_num_math (core->num, input+1);
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
} else {
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
}
//const char *prelude = "\x2d\xe9\xf0\x47"; //:fffff000";
r_mem_reverse (buf, bufsz);
//r_print_hexdump (NULL, off, buf, bufsz, 16, -16);
const ut8 *pos = r_mem_mem (buf, bufsz, prelude, prelude_sz);
if (pos) {
int delta = (size_t)(pos - buf);
eprintf ("POS = %d\n", delta);
eprintf ("HIT = 0x%"PFMT64x"\n", off - delta);
r_cons_printf ("0x%08"PFMT64x"\n", off - delta);
} else {
eprintf ("Cannot find prelude\n");
}
free (buf);
}
break;
case '8':
{
ut8 *buf = malloc (strlen (input) + 1);
if (buf) {
int len = r_hex_str2bin (input + 1, buf);
if (len > 0) {
core_anal_bytes (core, buf, len, 0, input[1]);
}
free (buf);
}
}
break;
case 'b':
if (input[1] == 'b') { // "abb"
core_anal_bbs (core, input + 2);
} else if (input[1] == 'r') { // "abr"
core_anal_bbs_range (core, input + 2);
} else if (input[1] == 't') {
cmd_anal_abt (core, input+2);
} else if (input[1] == 'j') { // "abj"
anal_fcn_list_bb (core, input + 1, false);
} else if (input[1] == ' ' || !input[1]) {
// find block
ut64 addr = core->offset;
if (input[1]) {
addr = r_num_math (core->num, input + 1);
}
r_core_cmdf (core, "afbi @ 0x%"PFMT64x, addr);
} else {
r_core_cmd_help (core, help_msg_ab);
}
break;
case 'L': return r_core_cmd0 (core, "e asm.arch=??"); break;
case 'i': cmd_anal_info (core, input + 1); break; // "ai"
case 'r': cmd_anal_reg (core, input + 1); break; // "ar"
case 'e': cmd_anal_esil (core, input + 1); break; // "ae"
case 'o': cmd_anal_opcode (core, input + 1); break; // "ao"
case 'O': cmd_anal_bytes (core, input + 1); break; // "aO"
case 'F': // "aF"
r_core_anal_fcn (core, core->offset, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
break;
case 'f': // "af"
{
int res = cmd_anal_fcn (core, input);
run_pending_anal (core);
if (!res) {
return false;
}
}
break;
case 'n': // 'an'
{
const char *name = NULL;
bool use_json = false;
if (input[1] == 'j') {
use_json = true;
input++;
}
if (input[1] == ' ') {
name = input + 1;
while (name[0] == ' ') {
name++;
}
char *end = strchr (name, ' ');
if (end) {
*end = '\0';
}
if (*name == '\0') {
name = NULL;
}
}
cmd_an (core, use_json, name);
}
break;
case 'g': // "ag"
cmd_anal_graph (core, input + 1);
break;
case 's': // "as"
cmd_anal_syscall (core, input + 1);
break;
case 'v': // "av"
cmd_anal_virtual_functions (core, input + 1);
break;
case 'x': // "ax"
if (!cmd_anal_refs (core, input + 1)) {
return false;
}
break;
case 'a': // "aa"
if (!cmd_anal_all (core, input + 1)) {
return false;
}
break;
case 'c': // "ac"
{
RList *hooks;
RListIter *iter;
RAnalCycleHook *hook;
char *instr_tmp = NULL;
int ccl = input[1]? r_num_math (core->num, &input[2]): 0; //get cycles to look for
int cr = r_config_get_i (core->config, "asm.cmt.right");
int fun = r_config_get_i (core->config, "asm.functions");
int li = r_config_get_i (core->config, "asm.lines");
int xr = r_config_get_i (core->config, "asm.xrefs");
r_config_set_i (core->config, "asm.cmt.right", true);
r_config_set_i (core->config, "asm.functions", false);
r_config_set_i (core->config, "asm.lines", false);
r_config_set_i (core->config, "asm.xrefs", false);
hooks = r_core_anal_cycles (core, ccl); //analyse
r_cons_clear_line (1);
r_list_foreach (hooks, iter, hook) {
instr_tmp = r_core_disassemble_instr (core, hook->addr, 1);
r_cons_printf ("After %4i cycles:\t%s", (ccl - hook->cycles), instr_tmp);
r_cons_flush ();
free (instr_tmp);
}
r_list_free (hooks);
r_config_set_i (core->config, "asm.cmt.right", cr); //reset settings
r_config_set_i (core->config, "asm.functions", fun);
r_config_set_i (core->config, "asm.lines", li);
r_config_set_i (core->config, "asm.xrefs", xr);
}
break;
case 'd': // "ad"
switch (input[1]) {
case 'f': // "adf"
if (input[2] == 'g') {
anal_fcn_data_gaps (core, input + 1);
} else {
anal_fcn_data (core, input + 1);
}
break;
case 't': // "adt"
cmd_anal_trampoline (core, input + 2);
break;
case ' ': { // "ad"
const int default_depth = 1;
const char *p;
int a, b;
a = r_num_math (core->num, input + 2);
p = strchr (input + 2, ' ');
b = p? r_num_math (core->num, p + 1): default_depth;
if (a < 1) {
a = 1;
}
if (b < 1) {
b = 1;
}
r_core_anal_data (core, core->offset, a, b, 0);
} break;
case 'k': // "adk"
r = r_anal_data_kind (core->anal,
core->offset, core->block, core->blocksize);
r_cons_println (r);
break;
case '\0': // "ad"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 0);
break;
case '4': // "ad4"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 4);
break;
case '8': // "ad8"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 8);
break;
default:
r_core_cmd_help (core, help_msg_ad);
break;
}
break;
case 'h': // "ah"
cmd_anal_hint (core, input + 1);
break;
case '!': // "a!"
if (core->anal && core->anal->cur && core->anal->cur->cmd_ext) {
return core->anal->cur->cmd_ext (core->anal, input + 1);
} else {
r_cons_printf ("No plugins for this analysis plugin\n");
}
break;
default:
r_core_cmd_help (core, help_msg_a);
#if 0
r_cons_printf ("Examples:\n"
" f ts @ `S*~text:0[3]`; f t @ section..text\n"
" f ds @ `S*~data:0[3]`; f d @ section..data\n"
" .ad t t+ts @ d:ds\n",
NULL);
#endif
break;
}
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
if (r_cons_is_breaked ()) {
r_cons_clear_line (1);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_504_0 |
crossvul-cpp_data_good_5009_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
* 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "opj_apps_config.h"
#include "openjpeg.h"
#include "color.h"
#ifdef OPJ_HAVE_LIBLCMS2
#include <lcms2.h>
#endif
#ifdef OPJ_HAVE_LIBLCMS1
#include <lcms.h>
#endif
#ifdef OPJ_USE_LEGACY
#define OPJ_CLRSPC_GRAY CLRSPC_GRAY
#define OPJ_CLRSPC_SRGB CLRSPC_SRGB
#endif
/*--------------------------------------------------------
Matrix for sYCC, Amendment 1 to IEC 61966-2-1
Y : 0.299 0.587 0.114 :R
Cb: -0.1687 -0.3312 0.5 :G
Cr: 0.5 -0.4187 -0.0812 :B
Inverse:
R: 1 -3.68213e-05 1.40199 :Y
G: 1.00003 -0.344125 -0.714128 :Cb - 2^(prec - 1)
B: 0.999823 1.77204 -8.04142e-06 :Cr - 2^(prec - 1)
-----------------------------------------------------------*/
static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr,
int *out_r, int *out_g, int *out_b)
{
int r, g, b;
cb -= offset; cr -= offset;
r = y + (int)(1.402 * (float)cr);
if(r < 0) r = 0; else if(r > upb) r = upb; *out_r = r;
g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
if(g < 0) g = 0; else if(g > upb) g = upb; *out_g = g;
b = y + (int)(1.772 * (float)cb);
if(b < 0) b = 0; else if(b > upb) b = upb; *out_b = b;
}
static void sycc444_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, i;
int offset, upb;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i = 0U; i < max; ++i)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++cb; ++cr; ++r; ++g; ++b;
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc444_to_rgb() */
static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
size_t maxw, maxh, max, offx, loopmaxw;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if(r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
for(i=0U; i < maxh; ++i)
{
size_t j;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
for(j=0U; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < loopmaxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc422_to_rgb() */
static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
size_t maxw, maxh, max, offx, loopmaxw, offy, loopmaxh;
int offset, upb;
size_t i;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (size_t)img->comps[0].w; maxh = (size_t)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * max);
d1 = g = (int*)malloc(sizeof(int) * max);
d2 = b = (int*)malloc(sizeof(int) * max);
if (r == NULL || g == NULL || b == NULL) goto fails;
/* if img->x0 is odd, then first column shall use Cb/Cr = 0 */
offx = img->x0 & 1U;
loopmaxw = maxw - offx;
/* if img->y0 is odd, then first line shall use Cb/Cr = 0 */
offy = img->y0 & 1U;
loopmaxh = maxh - offy;
if (offy > 0U) {
size_t j;
for(j=0; j < maxw; ++j)
{
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
}
}
for(i=0U; i < (loopmaxh & ~(size_t)1U); i += 2U)
{
size_t j;
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
if (offx > 0U) {
sycc_to_rgb(offset, upb, *y, 0, 0, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
}
for(j=0; j < (loopmaxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < loopmaxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < loopmaxh)
{
size_t j;
for(j=0U; j < (maxw & ~(size_t)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
img->comps[1].w = img->comps[2].w = img->comps[0].w;
img->comps[1].h = img->comps[2].h = img->comps[0].h;
img->comps[1].dx = img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[2].dy = img->comps[0].dy;
img->color_space = OPJ_CLRSPC_SRGB;
return;
fails:
free(r);
free(g);
free(b);
}/* sycc420_to_rgb() */
void color_sycc_to_rgb(opj_image_t *img)
{
if(img->numcomps < 3)
{
img->color_space = OPJ_CLRSPC_GRAY;
return;
}
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 2)
&& (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */
{
sycc420_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* horizontal sub-sample only */
{
sycc422_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 1)
&& (img->comps[2].dx == 1)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* no sub-sample */
{
sycc444_to_rgb(img);
}
else
{
fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
}/* color_sycc_to_rgb() */
#if defined(OPJ_HAVE_LIBLCMS2) || defined(OPJ_HAVE_LIBLCMS1)
#ifdef OPJ_HAVE_LIBLCMS1
/* Bob Friesenhahn proposed:*/
#define cmsSigXYZData icSigXYZData
#define cmsSigLabData icSigLabData
#define cmsSigCmykData icSigCmykData
#define cmsSigYCbCrData icSigYCbCrData
#define cmsSigLuvData icSigLuvData
#define cmsSigGrayData icSigGrayData
#define cmsSigRgbData icSigRgbData
#define cmsUInt32Number DWORD
#define cmsColorSpaceSignature icColorSpaceSignature
#define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent
#endif /* OPJ_HAVE_LIBLCMS1 */
/*#define DEBUG_PROFILE*/
void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples;
int prec, i, max, max_w, max_h, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof =
cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm","wb");
fwrite( image->icc_profile_buf,1, image->icc_profile_len,icm);
fclose(icm);
#endif
if(in_prof == NULL) return;
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = (int)image->comps[0].w;
max_h = (int)image->comps[0].h;
prec = (int)image->comps[0].prec;
if(out_space == cmsSigRgbData) /* enumCS 16 */
{
if( prec <= 8 )
{
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
}
else
{
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
if(out_space == cmsSigGrayData) /* enumCS 17 */
{
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
if(out_space == cmsSigYCbCrData) /* enumCS 18 */
{
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
{
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__,__LINE__,out_space,
(out_space>>24) & 0xff,(out_space>>16) & 0xff,
(out_space>>8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if(out_prof == NULL)
{
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec,
max_w,max_h, (void*)in_prof,(void*)out_prof);
fprintf(stderr,"\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space>>24) & 0xff,(in_space>>16) & 0xff,
(in_space>>8) & 0xff, in_space & 0xff,
out_space,
(out_space>>24) & 0xff,(out_space>>16) & 0xff,
(out_space>>8) & 0xff, out_space & 0xff,
in_type,out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type,
out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if(transform == NULL)
{
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n",__FILE__,__LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if(image->numcomps > 2)/* RGB, RGBA */
{
if( prec <= 8 )
{
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)malloc(nr_samples);
out = outbuf = (unsigned char*)malloc(nr_samples);
if(inbuf == NULL || outbuf == NULL) goto fails0;
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned char)*r++;
*in++ = (unsigned char)*g++;
*in++ = (unsigned char)*b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++;
*g++ = (int)*out++;
*b++ = (int)*out++;
}
ok = 1;
fails0:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
}
else /* prec > 8 */
{
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned short));
in = inbuf = (unsigned short*)malloc(nr_samples);
out = outbuf = (unsigned short*)malloc(nr_samples);
if(inbuf == NULL || outbuf == NULL) goto fails1;
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned short)*r++;
*in++ = (unsigned short)*g++;
*in++ = (unsigned short)*b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++;
*g++ = (int)*out++;
*b++ = (int)*out++;
}
ok = 1;
fails1:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
}
}
else /* image->numcomps <= 2 : GRAY, GRAYA */
{
if(prec <= 8)
{
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)malloc(nr_samples);
out = outbuf = (unsigned char*)malloc(nr_samples);
g = (int*)calloc((size_t)max, sizeof(int));
b = (int*)calloc((size_t)max, sizeof(int));
if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails2;
new_comps = (opj_image_comp_t*)
realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
if(new_comps == NULL) goto fails2;
image->comps = new_comps;
if(image->numcomps == 2)
image->comps[3] = image->comps[1];
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned char)*r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
}
r = g = b = NULL;
ok = 1;
fails2:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
if(g) free(g);
if(b) free(b);
}
else /* prec > 8 */
{
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned short));
in = inbuf = (unsigned short*)malloc(nr_samples);
out = outbuf = (unsigned short*)malloc(nr_samples);
g = (int*)calloc((size_t)max, sizeof(int));
b = (int*)calloc((size_t)max, sizeof(int));
if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails3;
new_comps = (opj_image_comp_t*)
realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
if(new_comps == NULL) goto fails3;
image->comps = new_comps;
if(image->numcomps == 2)
image->comps[3] = image->comps[1];
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned short)*r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
}
r = g = b = NULL;
ok = 1;
fails3:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
if(g) free(g);
if(b) free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if(ok)
{
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
void color_cielab_to_rgb(opj_image_t *image)
{
int *row;
int enumcs, numcomps;
OPJ_COLOR_SPACE new_space;
numcomps = (int)image->numcomps;
if(numcomps != 3)
{
fprintf(stderr,"%s:%d:\n\tnumcomps %d not handled. Quitting.\n",
__FILE__,__LINE__,numcomps);
return;
}
row = (int*)image->icc_profile_buf;
enumcs = row[0];
if(enumcs == 14) /* CIELab */
{
int *L, *a, *b, *red, *green, *blue;
int *src0, *src1, *src2, *dst0, *dst1, *dst2;
double rl, ol, ra, oa, rb, ob, prec0, prec1, prec2;
double minL, maxL, mina, maxa, minb, maxb;
unsigned int default_type;
unsigned int i, max;
cmsHPROFILE in, out;
cmsHTRANSFORM transform;
cmsUInt16Number RGB[3];
cmsCIELab Lab;
in = cmsCreateLab4Profile(NULL);
if(in == NULL){
return;
}
out = cmsCreate_sRGBProfile();
if(out == NULL){
cmsCloseProfile(in);
return;
}
transform = cmsCreateTransform(in, TYPE_Lab_DBL, out, TYPE_RGB_16, INTENT_PERCEPTUAL, 0);
#ifdef OPJ_HAVE_LIBLCMS2
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if(transform == NULL)
{
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
return;
}
new_space = OPJ_CLRSPC_SRGB;
prec0 = (double)image->comps[0].prec;
prec1 = (double)image->comps[1].prec;
prec2 = (double)image->comps[2].prec;
default_type = (unsigned int)row[1];
if(default_type == 0x44454600)/* DEF : default */
{
rl = 100; ra = 170; rb = 200;
ol = 0;
oa = pow(2, prec1 - 1);
ob = pow(2, prec2 - 2) + pow(2, prec2 - 3);
}
else
{
rl = row[2]; ra = row[4]; rb = row[6];
ol = row[3]; oa = row[5]; ob = row[7];
}
L = src0 = image->comps[0].data;
a = src1 = image->comps[1].data;
b = src2 = image->comps[2].data;
max = image->comps[0].w * image->comps[0].h;
red = dst0 = (int*)malloc(max * sizeof(int));
green = dst1 = (int*)malloc(max * sizeof(int));
blue = dst2 = (int*)malloc(max * sizeof(int));
if(red == NULL || green == NULL || blue == NULL) goto fails;
minL = -(rl * ol)/(pow(2, prec0)-1);
maxL = minL + rl;
mina = -(ra * oa)/(pow(2, prec1)-1);
maxa = mina + ra;
minb = -(rb * ob)/(pow(2, prec2)-1);
maxb = minb + rb;
for(i = 0; i < max; ++i)
{
Lab.L = minL + (double)(*L) * (maxL - minL)/(pow(2, prec0)-1); ++L;
Lab.a = mina + (double)(*a) * (maxa - mina)/(pow(2, prec1)-1); ++a;
Lab.b = minb + (double)(*b) * (maxb - minb)/(pow(2, prec2)-1); ++b;
cmsDoTransform(transform, &Lab, RGB, 1);
*red++ = RGB[0];
*green++ = RGB[1];
*blue++ = RGB[2];
}
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
free(src0); image->comps[0].data = dst0;
free(src1); image->comps[1].data = dst1;
free(src2); image->comps[2].data = dst2;
image->color_space = new_space;
image->comps[0].prec = 16;
image->comps[1].prec = 16;
image->comps[2].prec = 16;
return;
fails:
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if(red) free(red);
if(green) free(green);
if(blue) free(blue);
return;
}
fprintf(stderr,"%s:%d:\n\tenumCS %d not handled. Ignoring.\n", __FILE__,__LINE__, enumcs);
}/* color_cielab_to_rgb() */
#endif /* OPJ_HAVE_LIBLCMS2 || OPJ_HAVE_LIBLCMS1 */
void color_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if(image->numcomps < 4) return;
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for(i = 0; i < max; ++i)
{
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
free(image->comps[3].data); image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
/*
* This code has been adopted from sjpx_openjpeg.c of ghostscript
*/
void color_esycc_to_rgb(opj_image_t *image)
{
int y, cb, cr, sign1, sign2, val;
unsigned int w, h, max, i;
int flip_value = (1 << (image->comps[0].prec-1));
int max_value = (1 << image->comps[0].prec) - 1;
if (
(image->numcomps < 3)
|| (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)
) {
fprintf(stderr,"%s:%d:color_esycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
w = image->comps[0].w;
h = image->comps[0].h;
sign1 = (int)image->comps[1].sgnd;
sign2 = (int)image->comps[2].sgnd;
max = w * h;
for(i = 0; i < max; ++i)
{
y = image->comps[0].data[i]; cb = image->comps[1].data[i]; cr = image->comps[2].data[i];
if( !sign1) cb -= flip_value;
if( !sign2) cr -= flip_value;
val = (int)
((float)y - (float)0.0000368 * (float)cb
+ (float)1.40199 * (float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[0].data[i] = val;
val = (int)
((float)1.0003 * (float)y - (float)0.344125 * (float)cb
- (float)0.7141128 * (float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[1].data[i] = val;
val = (int)
((float)0.999823 * (float)y + (float)1.77204 * (float)cb
- (float)0.000008 *(float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[2].data[i] = val;
}
image->color_space = OPJ_CLRSPC_SRGB;
}/* color_esycc_to_rgb() */
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_5009_0 |
crossvul-cpp_data_good_669_3 | /*
* Record values functions
*
* Copyright (C) 2011-2018, Joachim Metz <joachim.metz@gmail.com>
*
* Refer to AUTHORS for acknowledgements.
*
* This software 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 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 Lesser General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
#include <common.h>
#include <byte_stream.h>
#include <memory.h>
#include <system_string.h>
#include <types.h>
#include "libevt_debug.h"
#include "libevt_io_handle.h"
#include "libevt_libbfio.h"
#include "libevt_libcerror.h"
#include "libevt_libcnotify.h"
#include "libevt_libfdatetime.h"
#include "libevt_libfvalue.h"
#include "libevt_libfwnt.h"
#include "libevt_record_values.h"
#include "libevt_unused.h"
#include "evt_file_header.h"
#include "evt_record.h"
const uint8_t evt_end_of_file_record_signature1[ 4 ] = { 0x11, 0x11, 0x11, 0x11 };
const uint8_t evt_end_of_file_record_signature2[ 4 ] = { 0x22, 0x22, 0x22, 0x22 };
const uint8_t evt_end_of_file_record_signature3[ 4 ] = { 0x33, 0x33, 0x33, 0x33 };
const uint8_t evt_end_of_file_record_signature4[ 4 ] = { 0x44, 0x44, 0x44, 0x44 };
/* Creates record values
* Make sure the value record_values is referencing, is set to NULL
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_initialize(
libevt_record_values_t **record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_initialize";
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( *record_values != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
"%s: invalid record values value already set.",
function );
return( -1 );
}
*record_values = memory_allocate_structure(
libevt_record_values_t );
if( *record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create record values.",
function );
goto on_error;
}
if( memory_set(
*record_values,
0,
sizeof( libevt_record_values_t ) ) == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_SET_FAILED,
"%s: unable to clear record values.",
function );
goto on_error;
}
return( 1 );
on_error:
if( *record_values != NULL )
{
memory_free(
*record_values );
*record_values = NULL;
}
return( -1 );
}
/* Frees record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_free(
libevt_record_values_t **record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_free";
int result = 1;
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( *record_values != NULL )
{
if( ( *record_values )->source_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->source_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free source name value.",
function );
result = -1;
}
}
if( ( *record_values )->computer_name != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->computer_name ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free computer name value.",
function );
result = -1;
}
}
if( ( *record_values )->user_security_identifier != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->user_security_identifier ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free user security identifier (SID).",
function );
result = -1;
}
}
if( ( *record_values )->strings != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->strings ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free strings.",
function );
result = -1;
}
}
if( ( *record_values )->data != NULL )
{
if( libfvalue_value_free(
&( ( *record_values )->data ),
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_FINALIZE_FAILED,
"%s: unable to free data.",
function );
result = -1;
}
}
memory_free(
*record_values );
*record_values = NULL;
}
return( result );
}
/* Clones the record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_clone(
libevt_record_values_t **destination_record_values,
libevt_record_values_t *source_record_values,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_clone";
if( destination_record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid destination record values.",
function );
return( -1 );
}
if( *destination_record_values != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_ALREADY_SET,
"%s: invalid destination record values value already set.",
function );
return( -1 );
}
if( source_record_values == NULL )
{
*destination_record_values = NULL;
return( 1 );
}
*destination_record_values = memory_allocate_structure(
libevt_record_values_t );
if( *destination_record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create destination record values.",
function );
goto on_error;
}
if( memory_copy(
*destination_record_values,
source_record_values,
sizeof( libevt_record_values_t ) ) == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_COPY_FAILED,
"%s: unable to copy source to destination record values.",
function );
goto on_error;
}
return( 1 );
on_error:
if( *destination_record_values != NULL )
{
memory_free(
*destination_record_values );
*destination_record_values = NULL;
}
return( -1 );
}
/* Reads a record_values
* Returns the number of bytes read if successful or -1 on error
*/
ssize_t libevt_record_values_read(
libevt_record_values_t *record_values,
libbfio_handle_t *file_io_handle,
libevt_io_handle_t *io_handle,
off64_t *file_offset,
uint8_t strict_mode,
libcerror_error_t **error )
{
uint8_t record_size_data[ 4 ];
uint8_t *record_data = NULL;
static char *function = "libevt_record_values_read";
size_t read_size = 0;
size_t record_data_offset = 0;
ssize_t read_count = 0;
ssize_t total_read_count = 0;
uint32_t record_data_size = 0;
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( io_handle == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid IO handle.",
function );
return( -1 );
}
if( file_offset == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid file offset.",
function );
return( -1 );
}
record_values->offset = *file_offset;
read_count = libbfio_handle_read_buffer(
file_io_handle,
record_size_data,
sizeof( uint32_t ),
error );
if( read_count != (ssize_t) sizeof( uint32_t ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record size data.",
function );
goto on_error;
}
*file_offset += read_count;
total_read_count = read_count;
byte_stream_copy_to_uint32_little_endian(
record_size_data,
record_data_size );
if( record_data_size < 4 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
goto on_error;
}
#if SIZEOF_SIZE_T <= 4
if( (size_t) record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
goto on_error;
}
#endif
/* Allocating record data as 4 bytes and then using realloc here
* corrupts the memory
*/
record_data = (uint8_t *) memory_allocate(
sizeof( uint8_t ) * record_data_size );
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_MEMORY,
LIBCERROR_MEMORY_ERROR_INSUFFICIENT,
"%s: unable to create record data.",
function );
goto on_error;
}
byte_stream_copy_from_uint32_little_endian(
record_data,
record_data_size );
record_data_offset = 4;
read_size = record_data_size - record_data_offset;
if( ( (size64_t) *file_offset + read_size ) > io_handle->file_size )
{
read_size = (size_t) ( io_handle->file_size - *file_offset );
}
read_count = libbfio_handle_read_buffer(
file_io_handle,
&( record_data[ record_data_offset ] ),
read_size,
error );
if( read_count != (ssize_t) read_size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record data.",
function );
goto on_error;
}
*file_offset += read_count;
record_data_offset += read_count;
total_read_count += read_count;
if( record_data_offset < (size_t) record_data_size )
{
if( libbfio_handle_seek_offset(
file_io_handle,
(off64_t) sizeof( evt_file_header_t ),
SEEK_SET,
error ) == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_SEEK_FAILED,
"%s: unable to seek file header offset: %" PRIzd ".",
function,
sizeof( evt_file_header_t ) );
goto on_error;
}
*file_offset = (off64_t) sizeof( evt_file_header_t );
read_size = (size_t) record_data_size - record_data_offset;
read_count = libbfio_handle_read_buffer(
file_io_handle,
&( record_data[ record_data_offset ] ),
read_size,
error );
if( read_count != (ssize_t) read_size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record data.",
function );
goto on_error;
}
*file_offset += read_count;
total_read_count += read_count;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: record data:\n",
function );
libcnotify_print_data(
record_data,
(size_t) record_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( memory_compare(
&( record_data[ 4 ] ),
evt_file_signature,
4 ) == 0 )
{
record_values->type = LIBEVT_RECORD_TYPE_EVENT;
}
else if( memory_compare(
&( record_data[ 4 ] ),
evt_end_of_file_record_signature1,
4 ) == 0 )
{
record_values->type = LIBEVT_RECORD_TYPE_END_OF_FILE;
}
else
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_UNSUPPORTED_VALUE,
"%s: unsupported record values signature.",
function );
goto on_error;
}
if( record_values->type == LIBEVT_RECORD_TYPE_EVENT )
{
if( libevt_record_values_read_event(
record_values,
record_data,
(size_t) record_data_size,
strict_mode,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read event record values.",
function );
goto on_error;
}
}
else if( record_values->type == LIBEVT_RECORD_TYPE_END_OF_FILE )
{
if( libevt_record_values_read_end_of_file(
record_values,
record_data,
(size_t) record_data_size,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read end of file record values.",
function );
goto on_error;
}
}
memory_free(
record_data );
return( total_read_count );
on_error:
if( record_data != NULL )
{
memory_free(
record_data );
}
return( -1 );
}
/* Reads the event record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_event(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
uint8_t strict_mode,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_event";
size_t record_data_offset = 0;
size_t strings_data_offset = 0;
ssize_t value_data_size = 0;
uint32_t data_offset = 0;
uint32_t data_size = 0;
uint32_t members_data_size = 0;
uint32_t size = 0;
uint32_t size_copy = 0;
uint32_t strings_offset = 0;
uint32_t strings_size = 0;
uint32_t user_sid_offset = 0;
uint32_t user_sid_size = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
uint16_t value_16bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < ( sizeof( evt_record_event_header_t ) + 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->record_number,
record_values->number );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->creation_time,
record_values->creation_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->written_time,
record_values->written_time );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->event_identifier,
record_values->event_identifier );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_type,
record_values->event_type );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_category,
record_values->event_category );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->strings_offset,
strings_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_size,
user_sid_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->user_sid_offset,
user_sid_offset );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_size,
data_size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->data_offset,
data_offset );
byte_stream_copy_to_uint32_little_endian(
&( record_data[ record_data_size - 4 ] ),
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t\t: %" PRIu32 "\n",
function,
size );
libcnotify_printf(
"%s: signature\t\t\t\t: %c%c%c%c\n",
function,
( (evt_record_event_header_t *) record_data )->signature[ 0 ],
( (evt_record_event_header_t *) record_data )->signature[ 1 ],
( (evt_record_event_header_t *) record_data )->signature[ 2 ],
( (evt_record_event_header_t *) record_data )->signature[ 3 ] );
libcnotify_printf(
"%s: record number\t\t\t\t: %" PRIu32 "\n",
function,
record_values->number );
if( libevt_debug_print_posix_time_value(
function,
"creation time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->creation_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
if( libevt_debug_print_posix_time_value(
function,
"written time\t\t\t\t",
( (evt_record_event_header_t *) record_data )->written_time,
4,
LIBFDATETIME_ENDIAN_LITTLE,
LIBFDATETIME_POSIX_TIME_VALUE_TYPE_SECONDS_32BIT_SIGNED,
LIBFDATETIME_STRING_FORMAT_TYPE_CTIME | LIBFDATETIME_STRING_FORMAT_FLAG_DATE_TIME,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print POSIX time value.",
function );
goto on_error;
}
libcnotify_printf(
"%s: event identifier\t\t\t: 0x%08" PRIx32 "\n",
function,
record_values->event_identifier );
libcnotify_printf(
"%s: event identifier: code\t\t\t: %" PRIu32 "\n",
function,
record_values->event_identifier & 0x0000ffffUL );
libcnotify_printf(
"%s: event identifier: facility\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x0fff0000UL ) >> 16 );
libcnotify_printf(
"%s: event identifier: reserved\t\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x10000000UL ) >> 28 );
libcnotify_printf(
"%s: event identifier: customer flags\t: %" PRIu32 "\n",
function,
( record_values->event_identifier & 0x20000000UL ) >> 29 );
libcnotify_printf(
"%s: event identifier: severity\t\t: %" PRIu32 " (",
function,
( record_values->event_identifier & 0xc0000000UL ) >> 30 );
libevt_debug_print_event_identifier_severity(
record_values->event_identifier );
libcnotify_printf(
")\n" );
libcnotify_printf(
"%s: event type\t\t\t\t: %" PRIu16 " (",
function,
record_values->event_type );
libevt_debug_print_event_type(
record_values->event_type );
libcnotify_printf(
")\n" );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->number_of_strings,
value_16bit );
libcnotify_printf(
"%s: number of strings\t\t\t: %" PRIu16 "\n",
function,
value_16bit );
libcnotify_printf(
"%s: event category\t\t\t\t: %" PRIu16 "\n",
function,
record_values->event_category );
byte_stream_copy_to_uint16_little_endian(
( (evt_record_event_header_t *) record_data )->event_flags,
value_16bit );
libcnotify_printf(
"%s: event flags\t\t\t\t: 0x%04" PRIx16 "\n",
function,
value_16bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_event_header_t *) record_data )->closing_record_number,
value_32bit );
libcnotify_printf(
"%s: closing record values number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: strings offset\t\t\t\t: %" PRIu32 "\n",
function,
strings_offset );
libcnotify_printf(
"%s: user security identifier (SID) size\t: %" PRIu32 "\n",
function,
user_sid_size );
libcnotify_printf(
"%s: user security identifier (SID) offset\t: %" PRIu32 "\n",
function,
user_sid_offset );
libcnotify_printf(
"%s: data size\t\t\t\t: %" PRIu32 "\n",
function,
data_size );
libcnotify_printf(
"%s: data offset\t\t\t\t: %" PRIu32 "\n",
function,
data_offset );
}
#endif
record_data_offset = sizeof( evt_record_event_header_t );
if( ( user_sid_offset == 0 )
&& ( user_sid_size != 0 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset or size value out of bounds.",
function );
goto on_error;
}
if( user_sid_offset != 0 )
{
if( ( (size_t) user_sid_offset < record_data_offset )
|| ( (size_t) user_sid_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID offset value out of bounds.",
function );
goto on_error;
}
if( user_sid_size != 0 )
{
if( (size_t) ( user_sid_offset + user_sid_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID size value out of bounds.",
function );
goto on_error;
}
}
}
/* If the strings offset is points at the offset at record data size - 4
* the strings are empty. For this to be sane the data offset should
* be the same as the strings offset or the data size 0.
*/
if( ( (size_t) strings_offset < user_sid_offset )
|| ( (size_t) strings_offset >= ( record_data_size - 4 ) ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( ( (size_t) data_offset < strings_offset )
|| ( (size_t) data_offset >= ( record_data_size - 4 ) ) )
{
if( data_size != 0 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data offset value out of bounds.",
function );
goto on_error;
}
data_offset = (uint32_t) record_data_size - 4;
}
if( ( (size_t) strings_offset >= ( record_data_size - 4 ) )
&& ( strings_offset != data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
if( strings_offset != 0 )
{
if( strings_offset < record_data_offset )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings offset value out of bounds.",
function );
goto on_error;
}
}
if( user_sid_offset != 0 )
{
members_data_size = user_sid_offset - (uint32_t) record_data_offset;
}
else if( strings_offset != 0 )
{
members_data_size = strings_offset - (uint32_t) record_data_offset;
}
if( strings_offset != 0 )
{
strings_size = data_offset - strings_offset;
}
if( data_size != 0 )
{
if( (size_t) ( data_offset + data_size ) > ( record_data_size - 4 ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
}
if( members_data_size != 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->source_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create source name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->source_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of source name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: source name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->source_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print source name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( libfvalue_value_type_initialize(
&( record_values->computer_name ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create computer name value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_string(
record_values->computer_name,
&( record_data[ record_data_offset ] ),
members_data_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of computer name value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: computer name\t\t\t\t: ",
function );
if( libfvalue_value_print(
record_values->computer_name,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print computer name value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += value_data_size;
members_data_size -= (uint32_t) value_data_size;
if( members_data_size > 0 )
{
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: members trailing data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
members_data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
record_data_offset += members_data_size;
}
}
if( user_sid_size != 0 )
{
if( user_sid_size > ( ( record_data_size - 4 ) - user_sid_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: user SID data size value out of bounds.",
function );
goto on_error;
}
if( libfvalue_value_type_initialize(
&( record_values->user_security_identifier ),
LIBFVALUE_VALUE_TYPE_NT_SECURITY_IDENTIFIER,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create user security identifier (SID) value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->user_security_identifier,
&( record_data[ user_sid_offset ] ),
(size_t) user_sid_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of user security identifier (SID) value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: user security identifier (SID)\t\t: ",
function );
if( libfvalue_value_print(
record_values->user_security_identifier,
0,
0,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_PRINT_FAILED,
"%s: unable to print user security identifier (SID) value.",
function );
goto on_error;
}
libcnotify_printf(
"\n" );
}
#endif
record_data_offset += user_sid_size;
}
if( strings_size != 0 )
{
if( strings_size > ( ( record_data_size - 4 ) - strings_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: strings size value out of bounds.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: strings data:\n",
function );
libcnotify_print_data(
&( record_data[ strings_offset ] ),
strings_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( size_copy == 0 )
{
/* If the strings data is truncated
*/
strings_data_offset = strings_offset + strings_size - 2;
while( strings_data_offset > strings_offset )
{
if( ( record_data[ strings_data_offset ] != 0 )
|| ( record_data[ strings_data_offset + 1 ] != 0 ) )
{
strings_size += 2;
break;
}
strings_data_offset -= 2;
strings_size -= 2;
}
}
if( libfvalue_value_type_initialize(
&( record_values->strings ),
LIBFVALUE_VALUE_TYPE_STRING_UTF16,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create strings value.",
function );
goto on_error;
}
value_data_size = libfvalue_value_type_set_data_strings_array(
record_values->strings,
&( record_data[ strings_offset ] ),
strings_size,
LIBFVALUE_CODEPAGE_UTF16_LITTLE_ENDIAN,
error );
if( value_data_size == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of strings value.",
function );
goto on_error;
}
record_data_offset += strings_size;
}
if( data_size != 0 )
{
if( data_size > ( ( record_data_size - 4 ) - data_offset ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: data size value out of bounds.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: data:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
#endif
if( libfvalue_value_type_initialize(
&( record_values->data ),
LIBFVALUE_VALUE_TYPE_BINARY_DATA,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create data value.",
function );
goto on_error;
}
if( libfvalue_value_set_data(
record_values->data,
&( record_data[ record_data_offset ] ),
(size_t) data_size,
LIBFVALUE_ENDIAN_LITTLE,
LIBFVALUE_VALUE_DATA_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set data of data value.",
function );
goto on_error;
}
#if defined( HAVE_DEBUG_OUTPUT )
record_data_offset += data_size;
#endif
}
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
if( record_data_offset < ( record_data_size - 4 ) )
{
libcnotify_printf(
"%s: padding:\n",
function );
libcnotify_print_data(
&( record_data[ record_data_offset ] ),
(size_t) record_data_size - record_data_offset - 4,
LIBCNOTIFY_PRINT_DATA_FLAG_GROUP_DATA );
}
libcnotify_printf(
"%s: size copy\t\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( ( strict_mode == 0 )
&& ( size_copy == 0 ) )
{
size_copy = size;
}
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
goto on_error;
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record_values data size and size.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values->data != NULL )
{
libfvalue_value_free(
&( record_values->data ),
NULL );
}
if( record_values->strings != NULL )
{
libfvalue_value_free(
&( record_values->strings ),
NULL );
}
if( record_values->user_security_identifier != NULL )
{
libfvalue_value_free(
&( record_values->user_security_identifier ),
NULL );
}
if( record_values->computer_name != NULL )
{
libfvalue_value_free(
&( record_values->computer_name ),
NULL );
}
if( record_values->source_name != NULL )
{
libfvalue_value_free(
&( record_values->source_name ),
NULL );
}
return( -1 );
}
/* Reads the end of file record values
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_end_of_file(
libevt_record_values_t *record_values,
uint8_t *record_data,
size_t record_data_size,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_read_end_of_file";
uint32_t size = 0;
uint32_t size_copy = 0;
#if defined( HAVE_DEBUG_OUTPUT )
uint32_t value_32bit = 0;
#endif
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( record_data == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record data.",
function );
return( -1 );
}
if( record_data_size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid record data size value exceeds maximum.",
function );
return( -1 );
}
if( record_data_size < sizeof( evt_record_end_of_file_t ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,
"%s: record data size value out of bounds.",
function );
return( -1 );
}
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->size,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->size_copy,
size_copy );
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: size\t\t\t\t: %" PRIu32 "\n",
function,
size );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature1,
value_32bit );
libcnotify_printf(
"%s: signature1\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature2,
value_32bit );
libcnotify_printf(
"%s: signature2\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature3,
value_32bit );
libcnotify_printf(
"%s: signature3\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->signature4,
value_32bit );
libcnotify_printf(
"%s: signature4\t\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->first_record_offset,
value_32bit );
libcnotify_printf(
"%s: first record offset\t\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->end_of_file_record_offset,
value_32bit );
libcnotify_printf(
"%s: end of file record offset\t: 0x%08" PRIx32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->last_record_number,
value_32bit );
libcnotify_printf(
"%s: last record number\t\t: %" PRIu32 "\n",
function,
value_32bit );
byte_stream_copy_to_uint32_little_endian(
( (evt_record_end_of_file_t *) record_data )->first_record_number,
value_32bit );
libcnotify_printf(
"%s: first record number\t\t: %" PRIu32 "\n",
function,
value_32bit );
libcnotify_printf(
"%s: size copy\t\t\t: %" PRIu32 "\n",
function,
size_copy );
libcnotify_printf(
"\n" );
}
#endif
if( size != size_copy )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for size and size copy.",
function );
return( -1 );
}
if( record_data_size != (size_t) size )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_INPUT,
LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,
"%s: value mismatch for record data size and size.",
function );
return( -1 );
}
/* TODO correct values in IO handle if necessary */
return( 1 );
}
/* Retrieves the type
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_get_type(
libevt_record_values_t *record_values,
uint8_t *type,
libcerror_error_t **error )
{
static char *function = "libevt_record_values_get_type";
if( record_values == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid record values.",
function );
return( -1 );
}
if( type == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid type.",
function );
return( -1 );
}
*type = record_values->type;
return( 1 );
}
/* Reads record values
* Callback for the (recovered) records list
* Returns 1 if successful or -1 on error
*/
int libevt_record_values_read_element_data(
libevt_io_handle_t *io_handle,
libbfio_handle_t *file_io_handle,
libfdata_list_element_t *element,
libfcache_cache_t *cache,
int element_file_index LIBEVT_ATTRIBUTE_UNUSED,
off64_t element_offset,
size64_t element_size LIBEVT_ATTRIBUTE_UNUSED,
uint32_t element_flags LIBEVT_ATTRIBUTE_UNUSED,
uint8_t read_flags LIBEVT_ATTRIBUTE_UNUSED,
libcerror_error_t **error )
{
libevt_record_values_t *record_values = NULL;
static char *function = "libevt_record_values_read_element_data";
off64_t file_offset = 0;
ssize_t read_count = 0;
LIBEVT_UNREFERENCED_PARAMETER( element_size )
LIBEVT_UNREFERENCED_PARAMETER( element_file_index )
LIBEVT_UNREFERENCED_PARAMETER( element_flags )
LIBEVT_UNREFERENCED_PARAMETER( read_flags )
#if defined( HAVE_DEBUG_OUTPUT )
if( libcnotify_verbose != 0 )
{
libcnotify_printf(
"%s: reading record at offset: %" PRIi64 " (0x%08" PRIx64 ")\n",
function,
element_offset,
element_offset );
}
#endif
if( libbfio_handle_seek_offset(
file_io_handle,
element_offset,
SEEK_SET,
error ) == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_SEEK_FAILED,
"%s: unable to seek record offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libevt_record_values_initialize(
&record_values,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_INITIALIZE_FAILED,
"%s: unable to create record values.",
function );
goto on_error;
}
/* File offset must be before being passed to libevt_record_values_read
*/
file_offset = element_offset;
read_count = libevt_record_values_read(
record_values,
file_io_handle,
io_handle,
&file_offset,
0,
error );
if( read_count == -1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read record at offset: %" PRIi64 ".",
function,
element_offset );
goto on_error;
}
if( libfdata_list_element_set_element_value(
element,
(intptr_t *) file_io_handle,
cache,
(intptr_t *) record_values,
(int (*)(intptr_t **, libcerror_error_t **)) &libevt_record_values_free,
LIBFDATA_LIST_ELEMENT_VALUE_FLAG_MANAGED,
error ) != 1 )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_SET_FAILED,
"%s: unable to set record values as element value.",
function );
goto on_error;
}
return( 1 );
on_error:
if( record_values != NULL )
{
libevt_record_values_free(
&record_values,
NULL );
}
return( -1 );
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_669_3 |
crossvul-cpp_data_bad_486_6 | /* -*- c-basic-offset: 8 -*-
rdesktop: A Remote Desktop Protocol client.
Protocol services - Multipoint Communications Service
Copyright (C) Matthew Chapman <matthewc.unsw.edu.au> 1999-2008
Copyright 2005-2011 Peter Astrand <astrand@cendio.se> for Cendio AB
Copyright 2018 Henrik Andersson <hean01@cendio.com> for Cendio AB
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/>.
*/
#include "rdesktop.h"
uint16 g_mcs_userid;
extern VCHANNEL g_channels[];
extern unsigned int g_num_channels;
/* Output a DOMAIN_PARAMS structure (ASN.1 BER) */
static void
mcs_out_domain_params(STREAM s, int max_channels, int max_users, int max_tokens, int max_pdusize)
{
ber_out_header(s, MCS_TAG_DOMAIN_PARAMS, 32);
ber_out_integer(s, max_channels);
ber_out_integer(s, max_users);
ber_out_integer(s, max_tokens);
ber_out_integer(s, 1); /* num_priorities */
ber_out_integer(s, 0); /* min_throughput */
ber_out_integer(s, 1); /* max_height */
ber_out_integer(s, max_pdusize);
ber_out_integer(s, 2); /* ver_protocol */
}
/* Parse a DOMAIN_PARAMS structure (ASN.1 BER) */
static RD_BOOL
mcs_parse_domain_params(STREAM s)
{
int length;
ber_parse_header(s, MCS_TAG_DOMAIN_PARAMS, &length);
in_uint8s(s, length);
return s_check(s);
}
/* Send an MCS_CONNECT_INITIAL message (ASN.1 BER) */
static void
mcs_send_connect_initial(STREAM mcs_data)
{
int datalen = mcs_data->end - mcs_data->data;
int length = 9 + 3 * 34 + 4 + datalen;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(length + 5);
ber_out_header(s, MCS_CONNECT_INITIAL, length);
ber_out_header(s, BER_TAG_OCTET_STRING, 1); /* calling domain */
out_uint8(s, 1);
ber_out_header(s, BER_TAG_OCTET_STRING, 1); /* called domain */
out_uint8(s, 1);
ber_out_header(s, BER_TAG_BOOLEAN, 1);
out_uint8(s, 0xff); /* upward flag */
mcs_out_domain_params(s, 34, 2, 0, 0xffff); /* target params */
mcs_out_domain_params(s, 1, 1, 1, 0x420); /* min params */
mcs_out_domain_params(s, 0xffff, 0xfc17, 0xffff, 0xffff); /* max params */
ber_out_header(s, BER_TAG_OCTET_STRING, datalen);
out_uint8p(s, mcs_data->data, datalen);
s_mark_end(s);
iso_send(s);
}
/* Expect a MCS_CONNECT_RESPONSE message (ASN.1 BER) */
static RD_BOOL
mcs_recv_connect_response(STREAM mcs_data)
{
UNUSED(mcs_data);
uint8 result;
int length;
STREAM s;
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
ber_parse_header(s, MCS_CONNECT_RESPONSE, &length);
ber_parse_header(s, BER_TAG_RESULT, &length);
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_connect_response(), result=%d", result);
return False;
}
ber_parse_header(s, BER_TAG_INTEGER, &length);
in_uint8s(s, length); /* connect id */
mcs_parse_domain_params(s);
ber_parse_header(s, BER_TAG_OCTET_STRING, &length);
sec_process_mcs_data(s);
/*
if (length > mcs_data->size)
{
logger(Protocol, Error, "mcs_recv_connect_response(), expected length=%d, got %d",length, mcs_data->size);
length = mcs_data->size;
}
in_uint8a(s, mcs_data->data, length);
mcs_data->p = mcs_data->data;
mcs_data->end = mcs_data->data + length;
*/
return s_check_end(s);
}
/* Send an EDrq message (ASN.1 PER) */
static void
mcs_send_edrq(void)
{
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(5);
out_uint8(s, (MCS_EDRQ << 2));
out_uint16_be(s, 1); /* height */
out_uint16_be(s, 1); /* interval */
s_mark_end(s);
iso_send(s);
}
/* Send an AUrq message (ASN.1 PER) */
static void
mcs_send_aurq(void)
{
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_init(1);
out_uint8(s, (MCS_AURQ << 2));
s_mark_end(s);
iso_send(s);
}
/* Expect a AUcf message (ASN.1 PER) */
static RD_BOOL
mcs_recv_aucf(uint16 * mcs_userid)
{
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
uint8 opcode, result;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
in_uint8(s, opcode);
if ((opcode >> 2) != MCS_AUCF)
{
logger(Protocol, Error, "mcs_recv_aucf(), expected opcode AUcf, got %d", opcode);
return False;
}
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_aucf(), expected result 0, got %d", result);
return False;
}
if (opcode & 2)
in_uint16_be(s, *mcs_userid);
return s_check_end(s);
}
/* Send a CJrq message (ASN.1 PER) */
static void
mcs_send_cjrq(uint16 chanid)
{
STREAM s;
logger(Protocol, Debug, "mcs_send_cjrq(), chanid=%d", chanid);
s = iso_init(5);
out_uint8(s, (MCS_CJRQ << 2));
out_uint16_be(s, g_mcs_userid);
out_uint16_be(s, chanid);
s_mark_end(s);
iso_send(s);
}
/* Expect a CJcf message (ASN.1 PER) */
static RD_BOOL
mcs_recv_cjcf(void)
{
RD_BOOL is_fastpath;
uint8 fastpath_hdr;
uint8 opcode, result;
STREAM s;
logger(Protocol, Debug, "%s()", __func__);
s = iso_recv(&is_fastpath, &fastpath_hdr);
if (s == NULL)
return False;
in_uint8(s, opcode);
if ((opcode >> 2) != MCS_CJCF)
{
logger(Protocol, Error, "mcs_recv_cjcf(), expected opcode CJcf, got %d", opcode);
return False;
}
in_uint8(s, result);
if (result != 0)
{
logger(Protocol, Error, "mcs_recv_cjcf(), expected result 0, got %d", result);
return False;
}
in_uint8s(s, 4); /* mcs_userid, req_chanid */
if (opcode & 2)
in_uint8s(s, 2); /* join_chanid */
return s_check_end(s);
}
/* Send MCS Disconnect provider ultimatum PDU */
void
mcs_send_dpu(unsigned short reason)
{
STREAM s, contents;
logger(Protocol, Debug, "mcs_send_dpu(), reason=%d", reason);
contents = malloc(sizeof(struct stream));
memset(contents, 0, sizeof(struct stream));
s_realloc(contents, 6);
s_reset(contents);
ber_out_integer(contents, reason); /* Reason */
ber_out_sequence(contents, NULL); /* SEQUENCE OF NonStandradParameters OPTIONAL */
s_mark_end(contents);
s = iso_init(8);
ber_out_sequence(s, contents);
s_free(contents);
s_mark_end(s);
iso_send(s);
}
/* Initialise an MCS transport data packet */
STREAM
mcs_init(int length)
{
STREAM s;
s = iso_init(length + 8);
s_push_layer(s, mcs_hdr, 8);
return s;
}
/* Send an MCS transport data packet to a specific channel */
void
mcs_send_to_channel(STREAM s, uint16 channel)
{
uint16 length;
s_pop_layer(s, mcs_hdr);
length = s->end - s->p - 8;
length |= 0x8000;
out_uint8(s, (MCS_SDRQ << 2));
out_uint16_be(s, g_mcs_userid);
out_uint16_be(s, channel);
out_uint8(s, 0x70); /* flags */
out_uint16_be(s, length);
iso_send(s);
}
/* Send an MCS transport data packet to the global channel */
void
mcs_send(STREAM s)
{
mcs_send_to_channel(s, MCS_GLOBAL_CHANNEL);
}
/* Receive an MCS transport data packet */
STREAM
mcs_recv(uint16 * channel, RD_BOOL * is_fastpath, uint8 * fastpath_hdr)
{
uint8 opcode, appid, length;
STREAM s;
s = iso_recv(is_fastpath, fastpath_hdr);
if (s == NULL)
return NULL;
if (*is_fastpath == True)
return s;
in_uint8(s, opcode);
appid = opcode >> 2;
if (appid != MCS_SDIN)
{
if (appid != MCS_DPUM)
{
logger(Protocol, Error, "mcs_recv(), expected data, got %d", opcode);
}
return NULL;
}
in_uint8s(s, 2); /* userid */
in_uint16_be(s, *channel);
in_uint8s(s, 1); /* flags */
in_uint8(s, length);
if (length & 0x80)
in_uint8s(s, 1); /* second byte of length */
return s;
}
RD_BOOL
mcs_connect_start(char *server, char *username, char *domain, char *password,
RD_BOOL reconnect, uint32 * selected_protocol)
{
logger(Protocol, Debug, "%s()", __func__);
return iso_connect(server, username, domain, password, reconnect, selected_protocol);
}
RD_BOOL
mcs_connect_finalize(STREAM mcs_data)
{
unsigned int i;
logger(Protocol, Debug, "%s()", __func__);
mcs_send_connect_initial(mcs_data);
if (!mcs_recv_connect_response(mcs_data))
goto error;
mcs_send_edrq();
mcs_send_aurq();
if (!mcs_recv_aucf(&g_mcs_userid))
goto error;
mcs_send_cjrq(g_mcs_userid + MCS_USERCHANNEL_BASE);
if (!mcs_recv_cjcf())
goto error;
mcs_send_cjrq(MCS_GLOBAL_CHANNEL);
if (!mcs_recv_cjcf())
goto error;
for (i = 0; i < g_num_channels; i++)
{
mcs_send_cjrq(g_channels[i].mcs_id);
if (!mcs_recv_cjcf())
goto error;
}
return True;
error:
iso_disconnect();
return False;
}
/* Disconnect from the MCS layer */
void
mcs_disconnect(int reason)
{
mcs_send_dpu(reason);
iso_disconnect();
}
/* reset the state of the mcs layer */
void
mcs_reset_state(void)
{
g_mcs_userid = 0;
iso_reset_state();
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_486_6 |
crossvul-cpp_data_bad_5009_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
* 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
#include "opj_apps_config.h"
#include "openjpeg.h"
#include "color.h"
#ifdef OPJ_HAVE_LIBLCMS2
#include <lcms2.h>
#endif
#ifdef OPJ_HAVE_LIBLCMS1
#include <lcms.h>
#endif
#ifdef OPJ_USE_LEGACY
#define OPJ_CLRSPC_GRAY CLRSPC_GRAY
#define OPJ_CLRSPC_SRGB CLRSPC_SRGB
#endif
/*--------------------------------------------------------
Matrix for sYCC, Amendment 1 to IEC 61966-2-1
Y : 0.299 0.587 0.114 :R
Cb: -0.1687 -0.3312 0.5 :G
Cr: 0.5 -0.4187 -0.0812 :B
Inverse:
R: 1 -3.68213e-05 1.40199 :Y
G: 1.00003 -0.344125 -0.714128 :Cb - 2^(prec - 1)
B: 0.999823 1.77204 -8.04142e-06 :Cr - 2^(prec - 1)
-----------------------------------------------------------*/
static void sycc_to_rgb(int offset, int upb, int y, int cb, int cr,
int *out_r, int *out_g, int *out_b)
{
int r, g, b;
cb -= offset; cr -= offset;
r = y + (int)(1.402 * (float)cr);
if(r < 0) r = 0; else if(r > upb) r = upb; *out_r = r;
g = y - (int)(0.344 * (float)cb + 0.714 * (float)cr);
if(g < 0) g = 0; else if(g > upb) g = upb; *out_g = g;
b = y + (int)(1.772 * (float)cb);
if(b < 0) b = 0; else if(b > upb) b = upb; *out_b = b;
}
static void sycc444_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
unsigned int maxw, maxh, max, i;
int offset, upb;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i = 0U; i < max; ++i)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++cb; ++cr; ++r; ++g; ++b;
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc444_to_rgb() */
static void sycc422_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b;
const int *y, *cb, *cr;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < maxh; ++i)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if (j < maxw) {
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc422_to_rgb() */
static void sycc420_to_rgb(opj_image_t *img)
{
int *d0, *d1, *d2, *r, *g, *b, *nr, *ng, *nb;
const int *y, *cb, *cr, *ny;
unsigned int maxw, maxh, max;
int offset, upb;
unsigned int i, j;
upb = (int)img->comps[0].prec;
offset = 1<<(upb - 1); upb = (1<<upb)-1;
maxw = (unsigned int)img->comps[0].w; maxh = (unsigned int)img->comps[0].h;
max = maxw * maxh;
y = img->comps[0].data;
cb = img->comps[1].data;
cr = img->comps[2].data;
d0 = r = (int*)malloc(sizeof(int) * (size_t)max);
d1 = g = (int*)malloc(sizeof(int) * (size_t)max);
d2 = b = (int*)malloc(sizeof(int) * (size_t)max);
if(r == NULL || g == NULL || b == NULL) goto fails;
for(i=0U; i < (maxh & ~(unsigned int)1U); i += 2U)
{
ny = y + maxw;
nr = r + maxw; ng = g + maxw; nb = b + maxw;
for(j=0; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *ny, *cb, *cr, nr, ng, nb);
++ny; ++nr; ++ng; ++nb; ++cb; ++cr;
}
y += maxw; r += maxw; g += maxw; b += maxw;
}
if(i < maxh)
{
for(j=0U; j < (maxw & ~(unsigned int)1U); j += 2U)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b;
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
++y; ++r; ++g; ++b; ++cb; ++cr;
}
if(j < maxw)
{
sycc_to_rgb(offset, upb, *y, *cb, *cr, r, g, b);
}
}
free(img->comps[0].data); img->comps[0].data = d0;
free(img->comps[1].data); img->comps[1].data = d1;
free(img->comps[2].data); img->comps[2].data = d2;
#if defined(USE_JPWL) || defined(USE_MJ2)
img->comps[1].w = maxw; img->comps[1].h = maxh;
img->comps[2].w = maxw; img->comps[2].h = maxh;
#else
img->comps[1].w = (OPJ_UINT32)maxw; img->comps[1].h = (OPJ_UINT32)maxh;
img->comps[2].w = (OPJ_UINT32)maxw; img->comps[2].h = (OPJ_UINT32)maxh;
#endif
img->comps[1].dx = img->comps[0].dx;
img->comps[2].dx = img->comps[0].dx;
img->comps[1].dy = img->comps[0].dy;
img->comps[2].dy = img->comps[0].dy;
return;
fails:
if(r) free(r);
if(g) free(g);
if(b) free(b);
}/* sycc420_to_rgb() */
void color_sycc_to_rgb(opj_image_t *img)
{
if(img->numcomps < 3)
{
img->color_space = OPJ_CLRSPC_GRAY;
return;
}
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 2)
&& (img->comps[2].dy == 2))/* horizontal and vertical sub-sample */
{
sycc420_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 2)
&& (img->comps[2].dx == 2)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* horizontal sub-sample only */
{
sycc422_to_rgb(img);
}
else
if((img->comps[0].dx == 1)
&& (img->comps[1].dx == 1)
&& (img->comps[2].dx == 1)
&& (img->comps[0].dy == 1)
&& (img->comps[1].dy == 1)
&& (img->comps[2].dy == 1))/* no sub-sample */
{
sycc444_to_rgb(img);
}
else
{
fprintf(stderr,"%s:%d:color_sycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
img->color_space = OPJ_CLRSPC_SRGB;
}/* color_sycc_to_rgb() */
#if defined(OPJ_HAVE_LIBLCMS2) || defined(OPJ_HAVE_LIBLCMS1)
#ifdef OPJ_HAVE_LIBLCMS1
/* Bob Friesenhahn proposed:*/
#define cmsSigXYZData icSigXYZData
#define cmsSigLabData icSigLabData
#define cmsSigCmykData icSigCmykData
#define cmsSigYCbCrData icSigYCbCrData
#define cmsSigLuvData icSigLuvData
#define cmsSigGrayData icSigGrayData
#define cmsSigRgbData icSigRgbData
#define cmsUInt32Number DWORD
#define cmsColorSpaceSignature icColorSpaceSignature
#define cmsGetHeaderRenderingIntent cmsTakeRenderingIntent
#endif /* OPJ_HAVE_LIBLCMS1 */
/*#define DEBUG_PROFILE*/
void color_apply_icc_profile(opj_image_t *image)
{
cmsHPROFILE in_prof, out_prof;
cmsHTRANSFORM transform;
cmsColorSpaceSignature in_space, out_space;
cmsUInt32Number intent, in_type, out_type;
int *r, *g, *b;
size_t nr_samples;
int prec, i, max, max_w, max_h, ok = 0;
OPJ_COLOR_SPACE new_space;
in_prof =
cmsOpenProfileFromMem(image->icc_profile_buf, image->icc_profile_len);
#ifdef DEBUG_PROFILE
FILE *icm = fopen("debug.icm","wb");
fwrite( image->icc_profile_buf,1, image->icc_profile_len,icm);
fclose(icm);
#endif
if(in_prof == NULL) return;
in_space = cmsGetPCS(in_prof);
out_space = cmsGetColorSpace(in_prof);
intent = cmsGetHeaderRenderingIntent(in_prof);
max_w = (int)image->comps[0].w;
max_h = (int)image->comps[0].h;
prec = (int)image->comps[0].prec;
if(out_space == cmsSigRgbData) /* enumCS 16 */
{
if( prec <= 8 )
{
in_type = TYPE_RGB_8;
out_type = TYPE_RGB_8;
}
else
{
in_type = TYPE_RGB_16;
out_type = TYPE_RGB_16;
}
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
if(out_space == cmsSigGrayData) /* enumCS 17 */
{
in_type = TYPE_GRAY_8;
out_type = TYPE_RGB_8;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
if(out_space == cmsSigYCbCrData) /* enumCS 18 */
{
in_type = TYPE_YCbCr_16;
out_type = TYPE_RGB_16;
out_prof = cmsCreate_sRGBProfile();
new_space = OPJ_CLRSPC_SRGB;
}
else
{
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
"output colorspace(%#x)(%c%c%c%c)\n\tICC Profile ignored.\n",
__FILE__,__LINE__,out_space,
(out_space>>24) & 0xff,(out_space>>16) & 0xff,
(out_space>>8) & 0xff, out_space & 0xff);
#endif
cmsCloseProfile(in_prof);
return;
}
if(out_prof == NULL)
{
cmsCloseProfile(in_prof);
return;
}
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tchannels(%d) prec(%d) w(%d) h(%d)"
"\n\tprofile: in(%p) out(%p)\n",__FILE__,__LINE__,image->numcomps,prec,
max_w,max_h, (void*)in_prof,(void*)out_prof);
fprintf(stderr,"\trender_intent (%u)\n\t"
"color_space: in(%#x)(%c%c%c%c) out:(%#x)(%c%c%c%c)\n\t"
" type: in(%u) out:(%u)\n",
intent,
in_space,
(in_space>>24) & 0xff,(in_space>>16) & 0xff,
(in_space>>8) & 0xff, in_space & 0xff,
out_space,
(out_space>>24) & 0xff,(out_space>>16) & 0xff,
(out_space>>8) & 0xff, out_space & 0xff,
in_type,out_type
);
#else
(void)prec;
(void)in_space;
#endif /* DEBUG_PROFILE */
transform = cmsCreateTransform(in_prof, in_type,
out_prof, out_type, intent, 0);
#ifdef OPJ_HAVE_LIBLCMS2
/* Possible for: LCMS_VERSION >= 2000 :*/
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if(transform == NULL)
{
#ifdef DEBUG_PROFILE
fprintf(stderr,"%s:%d:color_apply_icc_profile\n\tcmsCreateTransform failed. "
"ICC Profile ignored.\n",__FILE__,__LINE__);
#endif
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
return;
}
if(image->numcomps > 2)/* RGB, RGBA */
{
if( prec <= 8 )
{
unsigned char *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)malloc(nr_samples);
out = outbuf = (unsigned char*)malloc(nr_samples);
if(inbuf == NULL || outbuf == NULL) goto fails0;
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned char)*r++;
*in++ = (unsigned char)*g++;
*in++ = (unsigned char)*b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++;
*g++ = (int)*out++;
*b++ = (int)*out++;
}
ok = 1;
fails0:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
}
else /* prec > 8 */
{
unsigned short *inbuf, *outbuf, *in, *out;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned short));
in = inbuf = (unsigned short*)malloc(nr_samples);
out = outbuf = (unsigned short*)malloc(nr_samples);
if(inbuf == NULL || outbuf == NULL) goto fails1;
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned short)*r++;
*in++ = (unsigned short)*g++;
*in++ = (unsigned short)*b++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++;
*g++ = (int)*out++;
*b++ = (int)*out++;
}
ok = 1;
fails1:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
}
}
else /* image->numcomps <= 2 : GRAY, GRAYA */
{
if(prec <= 8)
{
unsigned char *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned char));
in = inbuf = (unsigned char*)malloc(nr_samples);
out = outbuf = (unsigned char*)malloc(nr_samples);
g = (int*)calloc((size_t)max, sizeof(int));
b = (int*)calloc((size_t)max, sizeof(int));
if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails2;
new_comps = (opj_image_comp_t*)
realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
if(new_comps == NULL) goto fails2;
image->comps = new_comps;
if(image->numcomps == 2)
image->comps[3] = image->comps[1];
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned char)*r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
}
r = g = b = NULL;
ok = 1;
fails2:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
if(g) free(g);
if(b) free(b);
}
else /* prec > 8 */
{
unsigned short *in, *inbuf, *out, *outbuf;
opj_image_comp_t *new_comps;
max = max_w * max_h;
nr_samples = (size_t)(max * 3 * sizeof(unsigned short));
in = inbuf = (unsigned short*)malloc(nr_samples);
out = outbuf = (unsigned short*)malloc(nr_samples);
g = (int*)calloc((size_t)max, sizeof(int));
b = (int*)calloc((size_t)max, sizeof(int));
if(inbuf == NULL || outbuf == NULL || g == NULL || b == NULL) goto fails3;
new_comps = (opj_image_comp_t*)
realloc(image->comps, (image->numcomps+2)*sizeof(opj_image_comp_t));
if(new_comps == NULL) goto fails3;
image->comps = new_comps;
if(image->numcomps == 2)
image->comps[3] = image->comps[1];
image->comps[1] = image->comps[0];
image->comps[2] = image->comps[0];
image->comps[1].data = g;
image->comps[2].data = b;
image->numcomps += 2;
r = image->comps[0].data;
for(i = 0; i < max; ++i)
{
*in++ = (unsigned short)*r++;
}
cmsDoTransform(transform, inbuf, outbuf, (cmsUInt32Number)max);
r = image->comps[0].data;
g = image->comps[1].data;
b = image->comps[2].data;
for(i = 0; i < max; ++i)
{
*r++ = (int)*out++; *g++ = (int)*out++; *b++ = (int)*out++;
}
r = g = b = NULL;
ok = 1;
fails3:
if(inbuf) free(inbuf);
if(outbuf) free(outbuf);
if(g) free(g);
if(b) free(b);
}
}/* if(image->numcomps > 2) */
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in_prof);
cmsCloseProfile(out_prof);
#endif
if(ok)
{
image->color_space = new_space;
}
}/* color_apply_icc_profile() */
void color_cielab_to_rgb(opj_image_t *image)
{
int *row;
int enumcs, numcomps;
OPJ_COLOR_SPACE new_space;
numcomps = (int)image->numcomps;
if(numcomps != 3)
{
fprintf(stderr,"%s:%d:\n\tnumcomps %d not handled. Quitting.\n",
__FILE__,__LINE__,numcomps);
return;
}
row = (int*)image->icc_profile_buf;
enumcs = row[0];
if(enumcs == 14) /* CIELab */
{
int *L, *a, *b, *red, *green, *blue;
int *src0, *src1, *src2, *dst0, *dst1, *dst2;
double rl, ol, ra, oa, rb, ob, prec0, prec1, prec2;
double minL, maxL, mina, maxa, minb, maxb;
unsigned int default_type;
unsigned int i, max;
cmsHPROFILE in, out;
cmsHTRANSFORM transform;
cmsUInt16Number RGB[3];
cmsCIELab Lab;
in = cmsCreateLab4Profile(NULL);
if(in == NULL){
return;
}
out = cmsCreate_sRGBProfile();
if(out == NULL){
cmsCloseProfile(in);
return;
}
transform = cmsCreateTransform(in, TYPE_Lab_DBL, out, TYPE_RGB_16, INTENT_PERCEPTUAL, 0);
#ifdef OPJ_HAVE_LIBLCMS2
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if(transform == NULL)
{
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
return;
}
new_space = OPJ_CLRSPC_SRGB;
prec0 = (double)image->comps[0].prec;
prec1 = (double)image->comps[1].prec;
prec2 = (double)image->comps[2].prec;
default_type = (unsigned int)row[1];
if(default_type == 0x44454600)/* DEF : default */
{
rl = 100; ra = 170; rb = 200;
ol = 0;
oa = pow(2, prec1 - 1);
ob = pow(2, prec2 - 2) + pow(2, prec2 - 3);
}
else
{
rl = row[2]; ra = row[4]; rb = row[6];
ol = row[3]; oa = row[5]; ob = row[7];
}
L = src0 = image->comps[0].data;
a = src1 = image->comps[1].data;
b = src2 = image->comps[2].data;
max = image->comps[0].w * image->comps[0].h;
red = dst0 = (int*)malloc(max * sizeof(int));
green = dst1 = (int*)malloc(max * sizeof(int));
blue = dst2 = (int*)malloc(max * sizeof(int));
if(red == NULL || green == NULL || blue == NULL) goto fails;
minL = -(rl * ol)/(pow(2, prec0)-1);
maxL = minL + rl;
mina = -(ra * oa)/(pow(2, prec1)-1);
maxa = mina + ra;
minb = -(rb * ob)/(pow(2, prec2)-1);
maxb = minb + rb;
for(i = 0; i < max; ++i)
{
Lab.L = minL + (double)(*L) * (maxL - minL)/(pow(2, prec0)-1); ++L;
Lab.a = mina + (double)(*a) * (maxa - mina)/(pow(2, prec1)-1); ++a;
Lab.b = minb + (double)(*b) * (maxb - minb)/(pow(2, prec2)-1); ++b;
cmsDoTransform(transform, &Lab, RGB, 1);
*red++ = RGB[0];
*green++ = RGB[1];
*blue++ = RGB[2];
}
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
free(src0); image->comps[0].data = dst0;
free(src1); image->comps[1].data = dst1;
free(src2); image->comps[2].data = dst2;
image->color_space = new_space;
image->comps[0].prec = 16;
image->comps[1].prec = 16;
image->comps[2].prec = 16;
return;
fails:
cmsDeleteTransform(transform);
#ifdef OPJ_HAVE_LIBLCMS1
cmsCloseProfile(in);
cmsCloseProfile(out);
#endif
if(red) free(red);
if(green) free(green);
if(blue) free(blue);
return;
}
fprintf(stderr,"%s:%d:\n\tenumCS %d not handled. Ignoring.\n", __FILE__,__LINE__, enumcs);
}/* color_cielab_to_rgb() */
#endif /* OPJ_HAVE_LIBLCMS2 || OPJ_HAVE_LIBLCMS1 */
void color_cmyk_to_rgb(opj_image_t *image)
{
float C, M, Y, K;
float sC, sM, sY, sK;
unsigned int w, h, max, i;
w = image->comps[0].w;
h = image->comps[0].h;
if(image->numcomps < 4) return;
max = w * h;
sC = 1.0F / (float)((1 << image->comps[0].prec) - 1);
sM = 1.0F / (float)((1 << image->comps[1].prec) - 1);
sY = 1.0F / (float)((1 << image->comps[2].prec) - 1);
sK = 1.0F / (float)((1 << image->comps[3].prec) - 1);
for(i = 0; i < max; ++i)
{
/* CMYK values from 0 to 1 */
C = (float)(image->comps[0].data[i]) * sC;
M = (float)(image->comps[1].data[i]) * sM;
Y = (float)(image->comps[2].data[i]) * sY;
K = (float)(image->comps[3].data[i]) * sK;
/* Invert all CMYK values */
C = 1.0F - C;
M = 1.0F - M;
Y = 1.0F - Y;
K = 1.0F - K;
/* CMYK -> RGB : RGB results from 0 to 255 */
image->comps[0].data[i] = (int)(255.0F * C * K); /* R */
image->comps[1].data[i] = (int)(255.0F * M * K); /* G */
image->comps[2].data[i] = (int)(255.0F * Y * K); /* B */
}
free(image->comps[3].data); image->comps[3].data = NULL;
image->comps[0].prec = 8;
image->comps[1].prec = 8;
image->comps[2].prec = 8;
image->numcomps -= 1;
image->color_space = OPJ_CLRSPC_SRGB;
for (i = 3; i < image->numcomps; ++i) {
memcpy(&(image->comps[i]), &(image->comps[i+1]), sizeof(image->comps[i]));
}
}/* color_cmyk_to_rgb() */
/*
* This code has been adopted from sjpx_openjpeg.c of ghostscript
*/
void color_esycc_to_rgb(opj_image_t *image)
{
int y, cb, cr, sign1, sign2, val;
unsigned int w, h, max, i;
int flip_value = (1 << (image->comps[0].prec-1));
int max_value = (1 << image->comps[0].prec) - 1;
if (
(image->numcomps < 3)
|| (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)
) {
fprintf(stderr,"%s:%d:color_esycc_to_rgb\n\tCAN NOT CONVERT\n", __FILE__,__LINE__);
return;
}
w = image->comps[0].w;
h = image->comps[0].h;
sign1 = (int)image->comps[1].sgnd;
sign2 = (int)image->comps[2].sgnd;
max = w * h;
for(i = 0; i < max; ++i)
{
y = image->comps[0].data[i]; cb = image->comps[1].data[i]; cr = image->comps[2].data[i];
if( !sign1) cb -= flip_value;
if( !sign2) cr -= flip_value;
val = (int)
((float)y - (float)0.0000368 * (float)cb
+ (float)1.40199 * (float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[0].data[i] = val;
val = (int)
((float)1.0003 * (float)y - (float)0.344125 * (float)cb
- (float)0.7141128 * (float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[1].data[i] = val;
val = (int)
((float)0.999823 * (float)y + (float)1.77204 * (float)cb
- (float)0.000008 *(float)cr + (float)0.5);
if(val > max_value) val = max_value; else if(val < 0) val = 0;
image->comps[2].data[i] = val;
}
image->color_space = OPJ_CLRSPC_SRGB;
}/* color_esycc_to_rgb() */
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5009_0 |
crossvul-cpp_data_bad_3956_0 | /**
* FreeRDP: A Remote Desktop Protocol Implementation
* Bitmap Cache V2
*
* Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
*
* 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 <winpr/crt.h>
#include <freerdp/freerdp.h>
#include <freerdp/constants.h>
#include <winpr/stream.h>
#include <freerdp/log.h>
#include <freerdp/cache/bitmap.h>
#include <freerdp/gdi/bitmap.h>
#include "../gdi/gdi.h"
#include "../core/graphics.h"
#include "bitmap.h"
#define TAG FREERDP_TAG("cache.bitmap")
static rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index);
static BOOL bitmap_cache_put(rdpBitmapCache* bitmap_cache, UINT32 id, UINT32 index,
rdpBitmap* bitmap);
static BOOL update_gdi_memblt(rdpContext* context, MEMBLT_ORDER* memblt)
{
rdpBitmap* bitmap;
rdpCache* cache = context->cache;
if (memblt->cacheId == 0xFF)
bitmap = offscreen_cache_get(cache->offscreen, memblt->cacheIndex);
else
bitmap = bitmap_cache_get(cache->bitmap, (BYTE)memblt->cacheId, memblt->cacheIndex);
/* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */
if (bitmap == NULL)
return TRUE;
memblt->bitmap = bitmap;
return IFCALLRESULT(TRUE, cache->bitmap->MemBlt, context, memblt);
}
static BOOL update_gdi_mem3blt(rdpContext* context, MEM3BLT_ORDER* mem3blt)
{
BYTE style;
rdpBitmap* bitmap;
rdpCache* cache = context->cache;
rdpBrush* brush = &mem3blt->brush;
BOOL ret = TRUE;
if (mem3blt->cacheId == 0xFF)
bitmap = offscreen_cache_get(cache->offscreen, mem3blt->cacheIndex);
else
bitmap = bitmap_cache_get(cache->bitmap, (BYTE)mem3blt->cacheId, mem3blt->cacheIndex);
/* XP-SP2 servers sometimes ask for cached bitmaps they've never defined. */
if (!bitmap)
return TRUE;
style = brush->style;
if (brush->style & CACHED_BRUSH)
{
brush->data = brush_cache_get(cache->brush, brush->index, &brush->bpp);
if (!brush->data)
return FALSE;
brush->style = 0x03;
}
mem3blt->bitmap = bitmap;
IFCALLRET(cache->bitmap->Mem3Blt, ret, context, mem3blt);
brush->style = style;
return ret;
}
static BOOL update_gdi_cache_bitmap(rdpContext* context, const CACHE_BITMAP_ORDER* cacheBitmap)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
rdpCache* cache = context->cache;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
Bitmap_SetDimensions(bitmap, cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight);
if (!bitmap->Decompress(context, bitmap, cacheBitmap->bitmapDataStream,
cacheBitmap->bitmapWidth, cacheBitmap->bitmapHeight,
cacheBitmap->bitmapBpp, cacheBitmap->bitmapLength,
cacheBitmap->compressed, RDP_CODEC_ID_NONE))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex);
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmap->cacheId, cacheBitmap->cacheIndex, bitmap);
}
static BOOL update_gdi_cache_bitmap_v2(rdpContext* context, CACHE_BITMAP_V2_ORDER* cacheBitmapV2)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
rdpCache* cache = context->cache;
rdpSettings* settings = context->settings;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
if (!cacheBitmapV2->bitmapBpp)
cacheBitmapV2->bitmapBpp = settings->ColorDepth;
if ((settings->ColorDepth == 15) && (cacheBitmapV2->bitmapBpp == 16))
cacheBitmapV2->bitmapBpp = settings->ColorDepth;
Bitmap_SetDimensions(bitmap, cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight);
if (!bitmap->Decompress(context, bitmap, cacheBitmapV2->bitmapDataStream,
cacheBitmapV2->bitmapWidth, cacheBitmapV2->bitmapHeight,
cacheBitmapV2->bitmapBpp, cacheBitmapV2->bitmapLength,
cacheBitmapV2->compressed, RDP_CODEC_ID_NONE))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex);
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmapV2->cacheId, cacheBitmapV2->cacheIndex,
bitmap);
}
static BOOL update_gdi_cache_bitmap_v3(rdpContext* context, CACHE_BITMAP_V3_ORDER* cacheBitmapV3)
{
rdpBitmap* bitmap;
rdpBitmap* prevBitmap;
BOOL compressed = TRUE;
rdpCache* cache = context->cache;
rdpSettings* settings = context->settings;
BITMAP_DATA_EX* bitmapData = &cacheBitmapV3->bitmapData;
bitmap = Bitmap_Alloc(context);
if (!bitmap)
return FALSE;
if (!cacheBitmapV3->bpp)
cacheBitmapV3->bpp = settings->ColorDepth;
compressed = (bitmapData->codecID != RDP_CODEC_ID_NONE);
Bitmap_SetDimensions(bitmap, bitmapData->width, bitmapData->height);
if (!bitmap->Decompress(context, bitmap, bitmapData->data, bitmapData->width,
bitmapData->height, bitmapData->bpp, bitmapData->length, compressed,
bitmapData->codecID))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
if (!bitmap->New(context, bitmap))
{
Bitmap_Free(context, bitmap);
return FALSE;
}
prevBitmap = bitmap_cache_get(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex);
Bitmap_Free(context, prevBitmap);
return bitmap_cache_put(cache->bitmap, cacheBitmapV3->cacheId, cacheBitmapV3->cacheIndex,
bitmap);
}
rdpBitmap* bitmap_cache_get(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index)
{
rdpBitmap* bitmap;
if (id > bitmapCache->maxCells)
{
WLog_ERR(TAG, "get invalid bitmap cell id: %" PRIu32 "", id);
return NULL;
}
if (index == BITMAP_CACHE_WAITING_LIST_INDEX)
{
index = bitmapCache->cells[id].number;
}
else if (index > bitmapCache->cells[id].number)
{
WLog_ERR(TAG, "get invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id);
return NULL;
}
bitmap = bitmapCache->cells[id].entries[index];
return bitmap;
}
BOOL bitmap_cache_put(rdpBitmapCache* bitmapCache, UINT32 id, UINT32 index, rdpBitmap* bitmap)
{
if (id > bitmapCache->maxCells)
{
WLog_ERR(TAG, "put invalid bitmap cell id: %" PRIu32 "", id);
return FALSE;
}
if (index == BITMAP_CACHE_WAITING_LIST_INDEX)
{
index = bitmapCache->cells[id].number;
}
else if (index > bitmapCache->cells[id].number)
{
WLog_ERR(TAG, "put invalid bitmap index %" PRIu32 " in cell id: %" PRIu32 "", index, id);
return FALSE;
}
bitmapCache->cells[id].entries[index] = bitmap;
return TRUE;
}
void bitmap_cache_register_callbacks(rdpUpdate* update)
{
rdpCache* cache = update->context->cache;
cache->bitmap->MemBlt = update->primary->MemBlt;
cache->bitmap->Mem3Blt = update->primary->Mem3Blt;
update->primary->MemBlt = update_gdi_memblt;
update->primary->Mem3Blt = update_gdi_mem3blt;
update->secondary->CacheBitmap = update_gdi_cache_bitmap;
update->secondary->CacheBitmapV2 = update_gdi_cache_bitmap_v2;
update->secondary->CacheBitmapV3 = update_gdi_cache_bitmap_v3;
update->BitmapUpdate = gdi_bitmap_update;
}
rdpBitmapCache* bitmap_cache_new(rdpSettings* settings)
{
int i;
rdpBitmapCache* bitmapCache;
bitmapCache = (rdpBitmapCache*)calloc(1, sizeof(rdpBitmapCache));
if (!bitmapCache)
return NULL;
bitmapCache->settings = settings;
bitmapCache->update = ((freerdp*)settings->instance)->update;
bitmapCache->context = bitmapCache->update->context;
bitmapCache->maxCells = settings->BitmapCacheV2NumCells;
bitmapCache->cells = (BITMAP_V2_CELL*)calloc(bitmapCache->maxCells, sizeof(BITMAP_V2_CELL));
if (!bitmapCache->cells)
goto fail;
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
bitmapCache->cells[i].number = settings->BitmapCacheV2CellInfo[i].numEntries;
/* allocate an extra entry for BITMAP_CACHE_WAITING_LIST_INDEX */
bitmapCache->cells[i].entries =
(rdpBitmap**)calloc((bitmapCache->cells[i].number + 1), sizeof(rdpBitmap*));
if (!bitmapCache->cells[i].entries)
goto fail;
}
return bitmapCache;
fail:
if (bitmapCache->cells)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
free(bitmapCache->cells[i].entries);
}
free(bitmapCache);
return NULL;
}
void bitmap_cache_free(rdpBitmapCache* bitmapCache)
{
int i, j;
rdpBitmap* bitmap;
if (bitmapCache)
{
for (i = 0; i < (int)bitmapCache->maxCells; i++)
{
for (j = 0; j < (int)bitmapCache->cells[i].number + 1; j++)
{
bitmap = bitmapCache->cells[i].entries[j];
Bitmap_Free(bitmapCache->context, bitmap);
}
free(bitmapCache->cells[i].entries);
}
free(bitmapCache->cells);
free(bitmapCache);
}
}
static void free_bitmap_data(BITMAP_DATA* data, size_t count)
{
size_t x;
if (!data)
return;
for (x = 0; x < count; x++)
free(data[x].bitmapDataStream);
free(data);
}
static BITMAP_DATA* copy_bitmap_data(const BITMAP_DATA* data, size_t count)
{
size_t x;
BITMAP_DATA* dst = (BITMAP_DATA*)calloc(count, sizeof(BITMAP_DATA));
if (!dst)
goto fail;
for (x = 0; x < count; x++)
{
dst[x] = data[x];
if (data[x].bitmapLength > 0)
{
dst[x].bitmapDataStream = malloc(data[x].bitmapLength);
if (!dst[x].bitmapDataStream)
goto fail;
memcpy(dst[x].bitmapDataStream, data[x].bitmapDataStream, data[x].bitmapLength);
}
}
return dst;
fail:
free_bitmap_data(dst, count);
return NULL;
}
void free_bitmap_update(rdpContext* context, BITMAP_UPDATE* pointer)
{
if (!pointer)
return;
free_bitmap_data(pointer->rectangles, pointer->number);
free(pointer);
}
BITMAP_UPDATE* copy_bitmap_update(rdpContext* context, const BITMAP_UPDATE* pointer)
{
BITMAP_UPDATE* dst = calloc(1, sizeof(BITMAP_UPDATE));
if (!dst || !pointer)
goto fail;
*dst = *pointer;
dst->rectangles = copy_bitmap_data(pointer->rectangles, pointer->number);
if (!dst->rectangles)
goto fail;
return dst;
fail:
free_bitmap_update(context, dst);
return NULL;
}
CACHE_BITMAP_ORDER* copy_cache_bitmap_order(rdpContext* context, const CACHE_BITMAP_ORDER* order)
{
CACHE_BITMAP_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapLength > 0)
{
dst->bitmapDataStream = malloc(order->bitmapLength);
if (!dst->bitmapDataStream)
goto fail;
memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength);
}
return dst;
fail:
free_cache_bitmap_order(context, dst);
return NULL;
}
void free_cache_bitmap_order(rdpContext* context, CACHE_BITMAP_ORDER* order)
{
if (order)
free(order->bitmapDataStream);
free(order);
}
CACHE_BITMAP_V2_ORDER* copy_cache_bitmap_v2_order(rdpContext* context,
const CACHE_BITMAP_V2_ORDER* order)
{
CACHE_BITMAP_V2_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapLength > 0)
{
dst->bitmapDataStream = malloc(order->bitmapLength);
if (!dst->bitmapDataStream)
goto fail;
memcpy(dst->bitmapDataStream, order->bitmapDataStream, order->bitmapLength);
}
return dst;
fail:
free_cache_bitmap_v2_order(context, dst);
return NULL;
}
void free_cache_bitmap_v2_order(rdpContext* context, CACHE_BITMAP_V2_ORDER* order)
{
if (order)
free(order->bitmapDataStream);
free(order);
}
CACHE_BITMAP_V3_ORDER* copy_cache_bitmap_v3_order(rdpContext* context,
const CACHE_BITMAP_V3_ORDER* order)
{
CACHE_BITMAP_V3_ORDER* dst = calloc(1, sizeof(CACHE_BITMAP_V3_ORDER));
if (!dst || !order)
goto fail;
*dst = *order;
if (order->bitmapData.length > 0)
{
dst->bitmapData.data = malloc(order->bitmapData.length);
if (!dst->bitmapData.data)
goto fail;
memcpy(dst->bitmapData.data, order->bitmapData.data, order->bitmapData.length);
}
return dst;
fail:
free_cache_bitmap_v3_order(context, dst);
return NULL;
}
void free_cache_bitmap_v3_order(rdpContext* context, CACHE_BITMAP_V3_ORDER* order)
{
if (order)
free(order->bitmapData.data);
free(order);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_3956_0 |
crossvul-cpp_data_good_376_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2015, 2017, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "tool_setup.h"
#define ENABLE_CURLX_PRINTF
/* use our own printf() functions */
#include "curlx.h"
#include "tool_cfgable.h"
#include "tool_msgs.h"
#include "memdebug.h" /* keep this as LAST include */
#define WARN_PREFIX "Warning: "
#define NOTE_PREFIX "Note: "
static void voutf(struct GlobalConfig *config,
const char *prefix,
const char *fmt,
va_list ap)
{
size_t width = (79 - strlen(prefix));
if(!config->mute) {
size_t len;
char *ptr;
char *print_buffer;
print_buffer = curlx_mvaprintf(fmt, ap);
if(!print_buffer)
return;
len = strlen(print_buffer);
ptr = print_buffer;
while(len > 0) {
fputs(prefix, config->errors);
if(len > width) {
size_t cut = width-1;
while(!ISSPACE(ptr[cut]) && cut) {
cut--;
}
if(0 == cut)
/* not a single cutting position was found, just cut it at the
max text width then! */
cut = width-1;
(void)fwrite(ptr, cut + 1, 1, config->errors);
fputs("\n", config->errors);
ptr += cut + 1; /* skip the space too */
len -= cut + 1;
}
else {
fputs(ptr, config->errors);
len = 0;
}
}
curl_free(print_buffer);
}
}
/*
* Emit 'note' formatted message on configured 'errors' stream, if verbose was
* selected.
*/
void notef(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if(config->tracetype)
voutf(config, NOTE_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit warning formatted message on configured 'errors' stream unless
* mute (--silent) was selected.
*/
void warnf(struct GlobalConfig *config, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
voutf(config, WARN_PREFIX, fmt, ap);
va_end(ap);
}
/*
* Emit help formatted message on given stream.
*/
void helpf(FILE *errors, const char *fmt, ...)
{
if(fmt) {
va_list ap;
va_start(ap, fmt);
fputs("curl: ", errors); /* prefix it */
vfprintf(errors, fmt, ap);
va_end(ap);
}
fprintf(errors, "curl: try 'curl --help' "
#ifdef USE_MANUAL
"or 'curl --manual' "
#endif
"for more information\n");
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_376_0 |
crossvul-cpp_data_good_2707_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 fragmentation header printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "ip6.h"
int
frag6_print(netdissect_options *ndo, register const u_char *bp, register const u_char *bp2)
{
register const struct ip6_frag *dp;
register const struct ip6_hdr *ip6;
dp = (const struct ip6_frag *)bp;
ip6 = (const struct ip6_hdr *)bp2;
ND_TCHECK(*dp);
if (ndo->ndo_vflag) {
ND_PRINT((ndo, "frag (0x%08x:%d|%ld)",
EXTRACT_32BITS(&dp->ip6f_ident),
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
} else {
ND_PRINT((ndo, "frag (%d|%ld)",
EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK,
sizeof(struct ip6_hdr) + EXTRACT_16BITS(&ip6->ip6_plen) -
(long)(bp - bp2) - sizeof(struct ip6_frag)));
}
/* it is meaningless to decode non-first fragment */
if ((EXTRACT_16BITS(&dp->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return -1;
else
{
ND_PRINT((ndo, " "));
return sizeof(struct ip6_frag);
}
trunc:
ND_PRINT((ndo, "[|frag]"));
return -1;
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2707_0 |
crossvul-cpp_data_bad_2696_0 | /*
* Copyright (c) 1988, 1989, 1990, 1991, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code distributions
* retain the above copyright notice and this paragraph in its entirety, (2)
* distributions including binary code include the above copyright notice and
* this paragraph in its entirety in the documentation or other materials
* provided with the distribution, and (3) all advertising materials mentioning
* features or use of this software display the following acknowledgement:
* ``This product includes software developed by the University of California,
* Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
* the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
/* \summary: IPv6 Internet Control Message Protocol (ICMPv6) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "addrtostr.h"
#include "extract.h"
#include "ip6.h"
#include "ipproto.h"
#include "udp.h"
#include "ah.h"
/* NetBSD: icmp6.h,v 1.13 2000/08/03 16:30:37 itojun Exp */
/* $KAME: icmp6.h,v 1.22 2000/08/03 15:25:16 jinmei Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* 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.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
struct icmp6_hdr {
uint8_t icmp6_type; /* type field */
uint8_t icmp6_code; /* code field */
uint16_t icmp6_cksum; /* checksum field */
union {
uint32_t icmp6_un_data32[1]; /* type-specific field */
uint16_t icmp6_un_data16[2]; /* type-specific field */
uint8_t icmp6_un_data8[4]; /* type-specific field */
} icmp6_dataun;
};
#define icmp6_data32 icmp6_dataun.icmp6_un_data32
#define icmp6_data16 icmp6_dataun.icmp6_un_data16
#define icmp6_data8 icmp6_dataun.icmp6_un_data8
#define icmp6_pptr icmp6_data32[0] /* parameter prob */
#define icmp6_mtu icmp6_data32[0] /* packet too big */
#define icmp6_id icmp6_data16[0] /* echo request/reply */
#define icmp6_seq icmp6_data16[1] /* echo request/reply */
#define icmp6_maxdelay icmp6_data16[0] /* mcast group membership */
#define ICMP6_DST_UNREACH 1 /* dest unreachable, codes: */
#define ICMP6_PACKET_TOO_BIG 2 /* packet too big */
#define ICMP6_TIME_EXCEEDED 3 /* time exceeded, code: */
#define ICMP6_PARAM_PROB 4 /* ip6 header bad */
#define ICMP6_ECHO_REQUEST 128 /* echo service */
#define ICMP6_ECHO_REPLY 129 /* echo reply */
#define ICMP6_MEMBERSHIP_QUERY 130 /* group membership query */
#define MLD6_LISTENER_QUERY 130 /* multicast listener query */
#define ICMP6_MEMBERSHIP_REPORT 131 /* group membership report */
#define MLD6_LISTENER_REPORT 131 /* multicast listener report */
#define ICMP6_MEMBERSHIP_REDUCTION 132 /* group membership termination */
#define MLD6_LISTENER_DONE 132 /* multicast listener done */
#define ND_ROUTER_SOLICIT 133 /* router solicitation */
#define ND_ROUTER_ADVERT 134 /* router advertisement */
#define ND_NEIGHBOR_SOLICIT 135 /* neighbor solicitation */
#define ND_NEIGHBOR_ADVERT 136 /* neighbor advertisement */
#define ND_REDIRECT 137 /* redirect */
#define ICMP6_ROUTER_RENUMBERING 138 /* router renumbering */
#define ICMP6_WRUREQUEST 139 /* who are you request */
#define ICMP6_WRUREPLY 140 /* who are you reply */
#define ICMP6_FQDN_QUERY 139 /* FQDN query */
#define ICMP6_FQDN_REPLY 140 /* FQDN reply */
#define ICMP6_NI_QUERY 139 /* node information request */
#define ICMP6_NI_REPLY 140 /* node information reply */
#define IND_SOLICIT 141 /* inverse neighbor solicitation */
#define IND_ADVERT 142 /* inverse neighbor advertisement */
#define ICMP6_V2_MEMBERSHIP_REPORT 143 /* v2 membership report */
#define MLDV2_LISTENER_REPORT 143 /* v2 multicast listener report */
#define ICMP6_HADISCOV_REQUEST 144
#define ICMP6_HADISCOV_REPLY 145
#define ICMP6_MOBILEPREFIX_SOLICIT 146
#define ICMP6_MOBILEPREFIX_ADVERT 147
#define MLD6_MTRACE_RESP 200 /* mtrace response(to sender) */
#define MLD6_MTRACE 201 /* mtrace messages */
#define ICMP6_MAXTYPE 201
#define ICMP6_DST_UNREACH_NOROUTE 0 /* no route to destination */
#define ICMP6_DST_UNREACH_ADMIN 1 /* administratively prohibited */
#define ICMP6_DST_UNREACH_NOTNEIGHBOR 2 /* not a neighbor(obsolete) */
#define ICMP6_DST_UNREACH_BEYONDSCOPE 2 /* beyond scope of source address */
#define ICMP6_DST_UNREACH_ADDR 3 /* address unreachable */
#define ICMP6_DST_UNREACH_NOPORT 4 /* port unreachable */
#define ICMP6_TIME_EXCEED_TRANSIT 0 /* ttl==0 in transit */
#define ICMP6_TIME_EXCEED_REASSEMBLY 1 /* ttl==0 in reass */
#define ICMP6_PARAMPROB_HEADER 0 /* erroneous header field */
#define ICMP6_PARAMPROB_NEXTHEADER 1 /* unrecognized next header */
#define ICMP6_PARAMPROB_OPTION 2 /* unrecognized option */
#define ICMP6_INFOMSG_MASK 0x80 /* all informational messages */
#define ICMP6_NI_SUBJ_IPV6 0 /* Query Subject is an IPv6 address */
#define ICMP6_NI_SUBJ_FQDN 1 /* Query Subject is a Domain name */
#define ICMP6_NI_SUBJ_IPV4 2 /* Query Subject is an IPv4 address */
#define ICMP6_NI_SUCCESS 0 /* node information successful reply */
#define ICMP6_NI_REFUSED 1 /* node information request is refused */
#define ICMP6_NI_UNKNOWN 2 /* unknown Qtype */
#define ICMP6_ROUTER_RENUMBERING_COMMAND 0 /* rr command */
#define ICMP6_ROUTER_RENUMBERING_RESULT 1 /* rr result */
#define ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET 255 /* rr seq num reset */
/* Used in kernel only */
#define ND_REDIRECT_ONLINK 0 /* redirect to an on-link node */
#define ND_REDIRECT_ROUTER 1 /* redirect to a better router */
/*
* Multicast Listener Discovery
*/
struct mld6_hdr {
struct icmp6_hdr mld6_hdr;
struct in6_addr mld6_addr; /* multicast address */
};
#define mld6_type mld6_hdr.icmp6_type
#define mld6_code mld6_hdr.icmp6_code
#define mld6_cksum mld6_hdr.icmp6_cksum
#define mld6_maxdelay mld6_hdr.icmp6_data16[0]
#define mld6_reserved mld6_hdr.icmp6_data16[1]
#define MLD_MINLEN 24
#define MLDV2_MINLEN 28
/*
* Neighbor Discovery
*/
struct nd_router_solicit { /* router solicitation */
struct icmp6_hdr nd_rs_hdr;
/* could be followed by options */
};
#define nd_rs_type nd_rs_hdr.icmp6_type
#define nd_rs_code nd_rs_hdr.icmp6_code
#define nd_rs_cksum nd_rs_hdr.icmp6_cksum
#define nd_rs_reserved nd_rs_hdr.icmp6_data32[0]
struct nd_router_advert { /* router advertisement */
struct icmp6_hdr nd_ra_hdr;
uint32_t nd_ra_reachable; /* reachable time */
uint32_t nd_ra_retransmit; /* retransmit timer */
/* could be followed by options */
};
#define nd_ra_type nd_ra_hdr.icmp6_type
#define nd_ra_code nd_ra_hdr.icmp6_code
#define nd_ra_cksum nd_ra_hdr.icmp6_cksum
#define nd_ra_curhoplimit nd_ra_hdr.icmp6_data8[0]
#define nd_ra_flags_reserved nd_ra_hdr.icmp6_data8[1]
#define ND_RA_FLAG_MANAGED 0x80
#define ND_RA_FLAG_OTHER 0x40
#define ND_RA_FLAG_HOME_AGENT 0x20
/*
* Router preference values based on draft-draves-ipngwg-router-selection-01.
* These are non-standard definitions.
*/
#define ND_RA_FLAG_RTPREF_MASK 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_HIGH 0x08 /* 00001000 */
#define ND_RA_FLAG_RTPREF_MEDIUM 0x00 /* 00000000 */
#define ND_RA_FLAG_RTPREF_LOW 0x18 /* 00011000 */
#define ND_RA_FLAG_RTPREF_RSV 0x10 /* 00010000 */
#define nd_ra_router_lifetime nd_ra_hdr.icmp6_data16[1]
struct nd_neighbor_solicit { /* neighbor solicitation */
struct icmp6_hdr nd_ns_hdr;
struct in6_addr nd_ns_target; /*target address */
/* could be followed by options */
};
#define nd_ns_type nd_ns_hdr.icmp6_type
#define nd_ns_code nd_ns_hdr.icmp6_code
#define nd_ns_cksum nd_ns_hdr.icmp6_cksum
#define nd_ns_reserved nd_ns_hdr.icmp6_data32[0]
struct nd_neighbor_advert { /* neighbor advertisement */
struct icmp6_hdr nd_na_hdr;
struct in6_addr nd_na_target; /* target address */
/* could be followed by options */
};
#define nd_na_type nd_na_hdr.icmp6_type
#define nd_na_code nd_na_hdr.icmp6_code
#define nd_na_cksum nd_na_hdr.icmp6_cksum
#define nd_na_flags_reserved nd_na_hdr.icmp6_data32[0]
#define ND_NA_FLAG_ROUTER 0x80000000
#define ND_NA_FLAG_SOLICITED 0x40000000
#define ND_NA_FLAG_OVERRIDE 0x20000000
struct nd_redirect { /* redirect */
struct icmp6_hdr nd_rd_hdr;
struct in6_addr nd_rd_target; /* target address */
struct in6_addr nd_rd_dst; /* destination address */
/* could be followed by options */
};
#define nd_rd_type nd_rd_hdr.icmp6_type
#define nd_rd_code nd_rd_hdr.icmp6_code
#define nd_rd_cksum nd_rd_hdr.icmp6_cksum
#define nd_rd_reserved nd_rd_hdr.icmp6_data32[0]
struct nd_opt_hdr { /* Neighbor discovery option header */
uint8_t nd_opt_type;
uint8_t nd_opt_len;
/* followed by option specific data*/
};
#define ND_OPT_SOURCE_LINKADDR 1
#define ND_OPT_TARGET_LINKADDR 2
#define ND_OPT_PREFIX_INFORMATION 3
#define ND_OPT_REDIRECTED_HEADER 4
#define ND_OPT_MTU 5
#define ND_OPT_ADVINTERVAL 7
#define ND_OPT_HOMEAGENT_INFO 8
#define ND_OPT_ROUTE_INFO 24 /* RFC4191 */
#define ND_OPT_RDNSS 25
#define ND_OPT_DNSSL 31
struct nd_opt_prefix_info { /* prefix information */
nd_uint8_t nd_opt_pi_type;
nd_uint8_t nd_opt_pi_len;
nd_uint8_t nd_opt_pi_prefix_len;
nd_uint8_t nd_opt_pi_flags_reserved;
nd_uint32_t nd_opt_pi_valid_time;
nd_uint32_t nd_opt_pi_preferred_time;
nd_uint32_t nd_opt_pi_reserved2;
struct in6_addr nd_opt_pi_prefix;
};
#define ND_OPT_PI_FLAG_ONLINK 0x80
#define ND_OPT_PI_FLAG_AUTO 0x40
#define ND_OPT_PI_FLAG_ROUTER 0x20 /*2292bis*/
struct nd_opt_rd_hdr { /* redirected header */
uint8_t nd_opt_rh_type;
uint8_t nd_opt_rh_len;
uint16_t nd_opt_rh_reserved1;
uint32_t nd_opt_rh_reserved2;
/* followed by IP header and data */
};
struct nd_opt_mtu { /* MTU option */
uint8_t nd_opt_mtu_type;
uint8_t nd_opt_mtu_len;
uint16_t nd_opt_mtu_reserved;
uint32_t nd_opt_mtu_mtu;
};
struct nd_opt_rdnss { /* RDNSS RFC 6106 5.1 */
uint8_t nd_opt_rdnss_type;
uint8_t nd_opt_rdnss_len;
uint16_t nd_opt_rdnss_reserved;
uint32_t nd_opt_rdnss_lifetime;
struct in6_addr nd_opt_rdnss_addr[1]; /* variable-length */
};
struct nd_opt_dnssl { /* DNSSL RFC 6106 5.2 */
uint8_t nd_opt_dnssl_type;
uint8_t nd_opt_dnssl_len;
uint16_t nd_opt_dnssl_reserved;
uint32_t nd_opt_dnssl_lifetime;
/* followed by list of DNS search domains, variable-length */
};
struct nd_opt_advinterval { /* Advertisement interval option */
uint8_t nd_opt_adv_type;
uint8_t nd_opt_adv_len;
uint16_t nd_opt_adv_reserved;
uint32_t nd_opt_adv_interval;
};
struct nd_opt_homeagent_info { /* Home Agent info */
uint8_t nd_opt_hai_type;
uint8_t nd_opt_hai_len;
uint16_t nd_opt_hai_reserved;
int16_t nd_opt_hai_preference;
uint16_t nd_opt_hai_lifetime;
};
struct nd_opt_route_info { /* route info */
uint8_t nd_opt_rti_type;
uint8_t nd_opt_rti_len;
uint8_t nd_opt_rti_prefixlen;
uint8_t nd_opt_rti_flags;
uint32_t nd_opt_rti_lifetime;
/* prefix follows */
};
/*
* icmp6 namelookup
*/
struct icmp6_namelookup {
struct icmp6_hdr icmp6_nl_hdr;
uint8_t icmp6_nl_nonce[8];
int32_t icmp6_nl_ttl;
#if 0
uint8_t icmp6_nl_len;
uint8_t icmp6_nl_name[3];
#endif
/* could be followed by options */
};
/*
* icmp6 node information
*/
struct icmp6_nodeinfo {
struct icmp6_hdr icmp6_ni_hdr;
uint8_t icmp6_ni_nonce[8];
/* could be followed by reply data */
};
#define ni_type icmp6_ni_hdr.icmp6_type
#define ni_code icmp6_ni_hdr.icmp6_code
#define ni_cksum icmp6_ni_hdr.icmp6_cksum
#define ni_qtype icmp6_ni_hdr.icmp6_data16[0]
#define ni_flags icmp6_ni_hdr.icmp6_data16[1]
#define NI_QTYPE_NOOP 0 /* NOOP */
#define NI_QTYPE_SUPTYPES 1 /* Supported Qtypes */
#define NI_QTYPE_FQDN 2 /* FQDN (draft 04) */
#define NI_QTYPE_DNSNAME 2 /* DNS Name */
#define NI_QTYPE_NODEADDR 3 /* Node Addresses */
#define NI_QTYPE_IPV4ADDR 4 /* IPv4 Addresses */
/* network endian */
#define NI_SUPTYPE_FLAG_COMPRESS ((uint16_t)htons(0x1))
#define NI_FQDN_FLAG_VALIDTTL ((uint16_t)htons(0x1))
/* network endian */
#define NI_NODEADDR_FLAG_TRUNCATE ((uint16_t)htons(0x1))
#define NI_NODEADDR_FLAG_ALL ((uint16_t)htons(0x2))
#define NI_NODEADDR_FLAG_COMPAT ((uint16_t)htons(0x4))
#define NI_NODEADDR_FLAG_LINKLOCAL ((uint16_t)htons(0x8))
#define NI_NODEADDR_FLAG_SITELOCAL ((uint16_t)htons(0x10))
#define NI_NODEADDR_FLAG_GLOBAL ((uint16_t)htons(0x20))
#define NI_NODEADDR_FLAG_ANYCAST ((uint16_t)htons(0x40)) /* just experimental. not in spec */
struct ni_reply_fqdn {
uint32_t ni_fqdn_ttl; /* TTL */
uint8_t ni_fqdn_namelen; /* length in octets of the FQDN */
uint8_t ni_fqdn_name[3]; /* XXX: alignment */
};
/*
* Router Renumbering. as router-renum-08.txt
*/
struct icmp6_router_renum { /* router renumbering header */
struct icmp6_hdr rr_hdr;
uint8_t rr_segnum;
uint8_t rr_flags;
uint16_t rr_maxdelay;
uint32_t rr_reserved;
};
#define ICMP6_RR_FLAGS_TEST 0x80
#define ICMP6_RR_FLAGS_REQRESULT 0x40
#define ICMP6_RR_FLAGS_FORCEAPPLY 0x20
#define ICMP6_RR_FLAGS_SPECSITE 0x10
#define ICMP6_RR_FLAGS_PREVDONE 0x08
#define rr_type rr_hdr.icmp6_type
#define rr_code rr_hdr.icmp6_code
#define rr_cksum rr_hdr.icmp6_cksum
#define rr_seqnum rr_hdr.icmp6_data32[0]
struct rr_pco_match { /* match prefix part */
uint8_t rpm_code;
uint8_t rpm_len;
uint8_t rpm_ordinal;
uint8_t rpm_matchlen;
uint8_t rpm_minlen;
uint8_t rpm_maxlen;
uint16_t rpm_reserved;
struct in6_addr rpm_prefix;
};
#define RPM_PCO_ADD 1
#define RPM_PCO_CHANGE 2
#define RPM_PCO_SETGLOBAL 3
#define RPM_PCO_MAX 4
struct rr_pco_use { /* use prefix part */
uint8_t rpu_uselen;
uint8_t rpu_keeplen;
uint8_t rpu_ramask;
uint8_t rpu_raflags;
uint32_t rpu_vltime;
uint32_t rpu_pltime;
uint32_t rpu_flags;
struct in6_addr rpu_prefix;
};
#define ICMP6_RR_PCOUSE_RAFLAGS_ONLINK 0x80
#define ICMP6_RR_PCOUSE_RAFLAGS_AUTO 0x40
/* network endian */
#define ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME ((uint32_t)htonl(0x80000000))
#define ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME ((uint32_t)htonl(0x40000000))
struct rr_result { /* router renumbering result message */
uint16_t rrr_flags;
uint8_t rrr_ordinal;
uint8_t rrr_matchedlen;
uint32_t rrr_ifid;
struct in6_addr rrr_prefix;
};
/* network endian */
#define ICMP6_RR_RESULT_FLAGS_OOB ((uint16_t)htons(0x0002))
#define ICMP6_RR_RESULT_FLAGS_FORBIDDEN ((uint16_t)htons(0x0001))
static const char *get_rtpref(u_int);
static const char *get_lifetime(uint32_t);
static void print_lladdr(netdissect_options *ndo, const u_char *, size_t);
static void icmp6_opt_print(netdissect_options *ndo, const u_char *, int);
static void mld6_print(netdissect_options *ndo, const u_char *);
static void mldv2_report_print(netdissect_options *ndo, const u_char *, u_int);
static void mldv2_query_print(netdissect_options *ndo, const u_char *, u_int);
static const struct udphdr *get_upperlayer(netdissect_options *ndo, const u_char *, u_int *);
static void dnsname_print(netdissect_options *ndo, const u_char *, const u_char *);
static void icmp6_nodeinfo_print(netdissect_options *ndo, u_int, const u_char *, const u_char *);
static void icmp6_rrenum_print(netdissect_options *ndo, const u_char *, const u_char *);
#ifndef abs
#define abs(a) ((0 < (a)) ? (a) : -(a))
#endif
#include "rpl.h"
static const struct tok icmp6_type_values[] = {
{ ICMP6_DST_UNREACH, "destination unreachable"},
{ ICMP6_PACKET_TOO_BIG, "packet too big"},
{ ICMP6_TIME_EXCEEDED, "time exceeded in-transit"},
{ ICMP6_PARAM_PROB, "parameter problem"},
{ ICMP6_ECHO_REQUEST, "echo request"},
{ ICMP6_ECHO_REPLY, "echo reply"},
{ MLD6_LISTENER_QUERY, "multicast listener query"},
{ MLD6_LISTENER_REPORT, "multicast listener report"},
{ MLD6_LISTENER_DONE, "multicast listener done"},
{ ND_ROUTER_SOLICIT, "router solicitation"},
{ ND_ROUTER_ADVERT, "router advertisement"},
{ ND_NEIGHBOR_SOLICIT, "neighbor solicitation"},
{ ND_NEIGHBOR_ADVERT, "neighbor advertisement"},
{ ND_REDIRECT, "redirect"},
{ ICMP6_ROUTER_RENUMBERING, "router renumbering"},
{ IND_SOLICIT, "inverse neighbor solicitation"},
{ IND_ADVERT, "inverse neighbor advertisement"},
{ MLDV2_LISTENER_REPORT, "multicast listener report v2"},
{ ICMP6_HADISCOV_REQUEST, "ha discovery request"},
{ ICMP6_HADISCOV_REPLY, "ha discovery reply"},
{ ICMP6_MOBILEPREFIX_SOLICIT, "mobile router solicitation"},
{ ICMP6_MOBILEPREFIX_ADVERT, "mobile router advertisement"},
{ ICMP6_WRUREQUEST, "who-are-you request"},
{ ICMP6_WRUREPLY, "who-are-you reply"},
{ ICMP6_NI_QUERY, "node information query"},
{ ICMP6_NI_REPLY, "node information reply"},
{ MLD6_MTRACE, "mtrace message"},
{ MLD6_MTRACE_RESP, "mtrace response"},
{ ND_RPL_MESSAGE, "RPL"},
{ 0, NULL }
};
static const struct tok icmp6_dst_unreach_code_values[] = {
{ ICMP6_DST_UNREACH_NOROUTE, "unreachable route" },
{ ICMP6_DST_UNREACH_ADMIN, " unreachable prohibited"},
{ ICMP6_DST_UNREACH_BEYONDSCOPE, "beyond scope"},
{ ICMP6_DST_UNREACH_ADDR, "unreachable address"},
{ ICMP6_DST_UNREACH_NOPORT, "unreachable port"},
{ 0, NULL }
};
static const struct tok icmp6_opt_pi_flag_values[] = {
{ ND_OPT_PI_FLAG_ONLINK, "onlink" },
{ ND_OPT_PI_FLAG_AUTO, "auto" },
{ ND_OPT_PI_FLAG_ROUTER, "router" },
{ 0, NULL }
};
static const struct tok icmp6_opt_ra_flag_values[] = {
{ ND_RA_FLAG_MANAGED, "managed" },
{ ND_RA_FLAG_OTHER, "other stateful"},
{ ND_RA_FLAG_HOME_AGENT, "home agent"},
{ 0, NULL }
};
static const struct tok icmp6_nd_na_flag_values[] = {
{ ND_NA_FLAG_ROUTER, "router" },
{ ND_NA_FLAG_SOLICITED, "solicited" },
{ ND_NA_FLAG_OVERRIDE, "override" },
{ 0, NULL }
};
static const struct tok icmp6_opt_values[] = {
{ ND_OPT_SOURCE_LINKADDR, "source link-address"},
{ ND_OPT_TARGET_LINKADDR, "destination link-address"},
{ ND_OPT_PREFIX_INFORMATION, "prefix info"},
{ ND_OPT_REDIRECTED_HEADER, "redirected header"},
{ ND_OPT_MTU, "mtu"},
{ ND_OPT_RDNSS, "rdnss"},
{ ND_OPT_DNSSL, "dnssl"},
{ ND_OPT_ADVINTERVAL, "advertisement interval"},
{ ND_OPT_HOMEAGENT_INFO, "homeagent information"},
{ ND_OPT_ROUTE_INFO, "route info"},
{ 0, NULL }
};
/* mldv2 report types */
static const struct tok mldv2report2str[] = {
{ 1, "is_in" },
{ 2, "is_ex" },
{ 3, "to_in" },
{ 4, "to_ex" },
{ 5, "allow" },
{ 6, "block" },
{ 0, NULL }
};
static const char *
get_rtpref(u_int v)
{
static const char *rtpref_str[] = {
"medium", /* 00 */
"high", /* 01 */
"rsv", /* 10 */
"low" /* 11 */
};
return rtpref_str[((v & ND_RA_FLAG_RTPREF_MASK) >> 3) & 0xff];
}
static const char *
get_lifetime(uint32_t v)
{
static char buf[20];
if (v == (uint32_t)~0UL)
return "infinity";
else {
snprintf(buf, sizeof(buf), "%us", v);
return buf;
}
}
static void
print_lladdr(netdissect_options *ndo, const uint8_t *p, size_t l)
{
const uint8_t *ep, *q;
q = p;
ep = p + l;
while (l > 0 && q < ep) {
if (q > p)
ND_PRINT((ndo,":"));
ND_PRINT((ndo,"%02x", *q++));
l--;
}
}
static int icmp6_cksum(netdissect_options *ndo, const struct ip6_hdr *ip6,
const struct icmp6_hdr *icp, u_int len)
{
return nextproto6_cksum(ndo, ip6, (const uint8_t *)(const void *)icp, len, len,
IPPROTO_ICMPV6);
}
static const struct tok rpl_mop_values[] = {
{ RPL_DIO_NONSTORING, "nonstoring"},
{ RPL_DIO_STORING, "storing"},
{ RPL_DIO_NONSTORING_MULTICAST, "nonstoring-multicast"},
{ RPL_DIO_STORING_MULTICAST, "storing-multicast"},
{ 0, NULL},
};
static const struct tok rpl_subopt_values[] = {
{ RPL_OPT_PAD0, "pad0"},
{ RPL_OPT_PADN, "padN"},
{ RPL_DIO_METRICS, "metrics"},
{ RPL_DIO_ROUTINGINFO, "routinginfo"},
{ RPL_DIO_CONFIG, "config"},
{ RPL_DAO_RPLTARGET, "rpltarget"},
{ RPL_DAO_TRANSITINFO, "transitinfo"},
{ RPL_DIO_DESTPREFIX, "destprefix"},
{ RPL_DAO_RPLTARGET_DESC, "rpltargetdesc"},
{ 0, NULL},
};
static void
rpl_dio_printopt(netdissect_options *ndo,
const struct rpl_dio_genoption *opt,
u_int length)
{
if(length < RPL_DIO_GENOPTION_LEN) return;
length -= RPL_DIO_GENOPTION_LEN;
ND_TCHECK(opt->rpl_dio_len);
while((opt->rpl_dio_type == RPL_OPT_PAD0 &&
(const u_char *)opt < ndo->ndo_snapend) ||
ND_TTEST2(*opt,(opt->rpl_dio_len+2))) {
unsigned int optlen = opt->rpl_dio_len+2;
if(opt->rpl_dio_type == RPL_OPT_PAD0) {
optlen = 1;
ND_PRINT((ndo, " opt:pad0"));
} else {
ND_PRINT((ndo, " opt:%s len:%u ",
tok2str(rpl_subopt_values, "subopt:%u", opt->rpl_dio_type),
optlen));
if(ndo->ndo_vflag > 2) {
unsigned int paylen = opt->rpl_dio_len;
if(paylen > length) paylen = length;
hex_print(ndo,
" ",
((const uint8_t *)opt) + RPL_DIO_GENOPTION_LEN, /* content of DIO option */
paylen);
}
}
opt = (const struct rpl_dio_genoption *)(((const char *)opt) + optlen);
length -= optlen;
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dio_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dio *dio = (const struct nd_rpl_dio *)bp;
const char *dagid_str;
ND_TCHECK(*dio);
dagid_str = ip6addr_string (ndo, dio->rpl_dagid);
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,rank:%u,%smop:%s,prf:%u]",
dagid_str,
dio->rpl_dtsn,
dio->rpl_instanceid,
EXTRACT_16BITS(&dio->rpl_dagrank),
RPL_DIO_GROUNDED(dio->rpl_mopprf) ? "grounded,":"",
tok2str(rpl_mop_values, "mop%u", RPL_DIO_MOP(dio->rpl_mopprf)),
RPL_DIO_PRF(dio->rpl_mopprf)));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)&dio[1];
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
}
static void
rpl_dao_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_dao *dao = (const struct nd_rpl_dao *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK(*dao);
if (length < ND_RPL_DAO_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAO_MIN_LEN;
length -= ND_RPL_DAO_MIN_LEN;
if(RPL_DAO_D(dao->rpl_flags)) {
ND_TCHECK2(dao->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, dao->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u%s%s,%02x]",
dagid_str,
dao->rpl_daoseq,
dao->rpl_instanceid,
RPL_DAO_K(dao->rpl_flags) ? ",acK":"",
RPL_DAO_D(dao->rpl_flags) ? ",Dagid":"",
dao->rpl_flags));
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|length too short]"));
return;
}
static void
rpl_daoack_print(netdissect_options *ndo,
const u_char *bp, u_int length)
{
const struct nd_rpl_daoack *daoack = (const struct nd_rpl_daoack *)bp;
const char *dagid_str = "<elided>";
ND_TCHECK2(*daoack, ND_RPL_DAOACK_MIN_LEN);
if (length < ND_RPL_DAOACK_MIN_LEN)
goto tooshort;
bp += ND_RPL_DAOACK_MIN_LEN;
length -= ND_RPL_DAOACK_MIN_LEN;
if(RPL_DAOACK_D(daoack->rpl_flags)) {
ND_TCHECK2(daoack->rpl_dagid, DAGID_LEN);
if (length < DAGID_LEN)
goto tooshort;
dagid_str = ip6addr_string (ndo, daoack->rpl_dagid);
bp += DAGID_LEN;
length -= DAGID_LEN;
}
ND_PRINT((ndo, " [dagid:%s,seq:%u,instance:%u,status:%u]",
dagid_str,
daoack->rpl_daoseq,
daoack->rpl_instanceid,
daoack->rpl_status));
/* no officially defined options for DAOACK, but print any we find */
if(ndo->ndo_vflag > 1) {
const struct rpl_dio_genoption *opt = (const struct rpl_dio_genoption *)bp;
rpl_dio_printopt(ndo, opt, length);
}
return;
trunc:
ND_PRINT((ndo," [|dao-truncated]"));
return;
tooshort:
ND_PRINT((ndo," [|dao-length too short]"));
return;
}
static void
rpl_print(netdissect_options *ndo,
const struct icmp6_hdr *hdr,
const u_char *bp, u_int length)
{
int secured = hdr->icmp6_code & 0x80;
int basecode= hdr->icmp6_code & 0x7f;
if(secured) {
ND_PRINT((ndo, ", (SEC) [worktodo]"));
/* XXX
* the next header pointer needs to move forward to
* skip the secure part.
*/
return;
} else {
ND_PRINT((ndo, ", (CLR)"));
}
switch(basecode) {
case ND_RPL_DAG_IS:
ND_PRINT((ndo, "DODAG Information Solicitation"));
if(ndo->ndo_vflag) {
}
break;
case ND_RPL_DAG_IO:
ND_PRINT((ndo, "DODAG Information Object"));
if(ndo->ndo_vflag) {
rpl_dio_print(ndo, bp, length);
}
break;
case ND_RPL_DAO:
ND_PRINT((ndo, "Destination Advertisement Object"));
if(ndo->ndo_vflag) {
rpl_dao_print(ndo, bp, length);
}
break;
case ND_RPL_DAO_ACK:
ND_PRINT((ndo, "Destination Advertisement Object Ack"));
if(ndo->ndo_vflag) {
rpl_daoack_print(ndo, bp, length);
}
break;
default:
ND_PRINT((ndo, "RPL message, unknown code %u",hdr->icmp6_code));
break;
}
return;
#if 0
trunc:
ND_PRINT((ndo," [|truncated]"));
return;
#endif
}
void
icmp6_print(netdissect_options *ndo,
const u_char *bp, u_int length, const u_char *bp2, int fragmented)
{
const struct icmp6_hdr *dp;
const struct ip6_hdr *ip;
const struct ip6_hdr *oip;
const struct udphdr *ouh;
int dport;
const u_char *ep;
u_int prot;
dp = (const struct icmp6_hdr *)bp;
ip = (const struct ip6_hdr *)bp2;
oip = (const struct ip6_hdr *)(dp + 1);
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
ND_TCHECK(dp->icmp6_cksum);
if (ndo->ndo_vflag && !fragmented) {
uint16_t sum, udp_sum;
if (ND_TTEST2(bp[0], length)) {
udp_sum = EXTRACT_16BITS(&dp->icmp6_cksum);
sum = icmp6_cksum(ndo, ip, dp, length);
if (sum != 0)
ND_PRINT((ndo,"[bad icmp6 cksum 0x%04x -> 0x%04x!] ",
udp_sum,
in_cksum_shouldbe(udp_sum, sum)));
else
ND_PRINT((ndo,"[icmp6 sum ok] "));
}
}
ND_PRINT((ndo,"ICMP6, %s", tok2str(icmp6_type_values,"unknown icmp6 type (%u)",dp->icmp6_type)));
/* display cosmetics: print the packet length for printer that use the vflag now */
if (ndo->ndo_vflag && (dp->icmp6_type == ND_ROUTER_SOLICIT ||
dp->icmp6_type == ND_ROUTER_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_ADVERT ||
dp->icmp6_type == ND_NEIGHBOR_SOLICIT ||
dp->icmp6_type == ND_REDIRECT ||
dp->icmp6_type == ICMP6_HADISCOV_REPLY ||
dp->icmp6_type == ICMP6_MOBILEPREFIX_ADVERT ))
ND_PRINT((ndo,", length %u", length));
switch (dp->icmp6_type) {
case ICMP6_DST_UNREACH:
ND_TCHECK(oip->ip6_dst);
ND_PRINT((ndo,", %s", tok2str(icmp6_dst_unreach_code_values,"unknown unreach code (%u)",dp->icmp6_code)));
switch (dp->icmp6_code) {
case ICMP6_DST_UNREACH_NOROUTE: /* fall through */
case ICMP6_DST_UNREACH_ADMIN:
case ICMP6_DST_UNREACH_ADDR:
ND_PRINT((ndo," %s",ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_DST_UNREACH_BEYONDSCOPE:
ND_PRINT((ndo," %s, source address %s",
ip6addr_string(ndo, &oip->ip6_dst),
ip6addr_string(ndo, &oip->ip6_src)));
break;
case ICMP6_DST_UNREACH_NOPORT:
if ((ouh = get_upperlayer(ndo, (const u_char *)oip, &prot))
== NULL)
goto trunc;
dport = EXTRACT_16BITS(&ouh->uh_dport);
switch (prot) {
case IPPROTO_TCP:
ND_PRINT((ndo,", %s tcp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
tcpport_string(ndo, dport)));
break;
case IPPROTO_UDP:
ND_PRINT((ndo,", %s udp port %s",
ip6addr_string(ndo, &oip->ip6_dst),
udpport_string(ndo, dport)));
break;
default:
ND_PRINT((ndo,", %s protocol %d port %d unreachable",
ip6addr_string(ndo, &oip->ip6_dst),
oip->ip6_nxt, dport));
break;
}
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, bp,"\n\t",length);
return;
}
break;
}
break;
case ICMP6_PACKET_TOO_BIG:
ND_TCHECK(dp->icmp6_mtu);
ND_PRINT((ndo,", mtu %u", EXTRACT_32BITS(&dp->icmp6_mtu)));
break;
case ICMP6_TIME_EXCEEDED:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_TIME_EXCEED_TRANSIT:
ND_PRINT((ndo," for %s",
ip6addr_string(ndo, &oip->ip6_dst)));
break;
case ICMP6_TIME_EXCEED_REASSEMBLY:
ND_PRINT((ndo," (reassembly)"));
break;
default:
ND_PRINT((ndo,", unknown code (%u)", dp->icmp6_code));
break;
}
break;
case ICMP6_PARAM_PROB:
ND_TCHECK(oip->ip6_dst);
switch (dp->icmp6_code) {
case ICMP6_PARAMPROB_HEADER:
ND_PRINT((ndo,", erroneous - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_NEXTHEADER:
ND_PRINT((ndo,", next header - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
case ICMP6_PARAMPROB_OPTION:
ND_PRINT((ndo,", option - octet %u", EXTRACT_32BITS(&dp->icmp6_pptr)));
break;
default:
ND_PRINT((ndo,", code-#%d",
dp->icmp6_code));
break;
}
break;
case ICMP6_ECHO_REQUEST:
case ICMP6_ECHO_REPLY:
ND_TCHECK(dp->icmp6_seq);
ND_PRINT((ndo,", seq %u", EXTRACT_16BITS(&dp->icmp6_seq)));
break;
case ICMP6_MEMBERSHIP_QUERY:
if (length == MLD_MINLEN) {
mld6_print(ndo, (const u_char *)dp);
} else if (length >= MLDV2_MINLEN) {
ND_PRINT((ndo," v2"));
mldv2_query_print(ndo, (const u_char *)dp, length);
} else {
ND_PRINT((ndo," unknown-version (len %u) ", length));
}
break;
case ICMP6_MEMBERSHIP_REPORT:
mld6_print(ndo, (const u_char *)dp);
break;
case ICMP6_MEMBERSHIP_REDUCTION:
mld6_print(ndo, (const u_char *)dp);
break;
case ND_ROUTER_SOLICIT:
#define RTSOLLEN 8
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + RTSOLLEN,
length - RTSOLLEN);
}
break;
case ND_ROUTER_ADVERT:
#define RTADVLEN 16
if (ndo->ndo_vflag) {
const struct nd_router_advert *p;
p = (const struct nd_router_advert *)dp;
ND_TCHECK(p->nd_ra_retransmit);
ND_PRINT((ndo,"\n\thop limit %u, Flags [%s]" \
", pref %s, router lifetime %us, reachable time %us, retrans time %us",
(u_int)p->nd_ra_curhoplimit,
bittok2str(icmp6_opt_ra_flag_values,"none",(p->nd_ra_flags_reserved)),
get_rtpref(p->nd_ra_flags_reserved),
EXTRACT_16BITS(&p->nd_ra_router_lifetime),
EXTRACT_32BITS(&p->nd_ra_reachable),
EXTRACT_32BITS(&p->nd_ra_retransmit)));
icmp6_opt_print(ndo, (const u_char *)dp + RTADVLEN,
length - RTADVLEN);
}
break;
case ND_NEIGHBOR_SOLICIT:
{
const struct nd_neighbor_solicit *p;
p = (const struct nd_neighbor_solicit *)dp;
ND_TCHECK(p->nd_ns_target);
ND_PRINT((ndo,", who has %s", ip6addr_string(ndo, &p->nd_ns_target)));
if (ndo->ndo_vflag) {
#define NDSOLLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDSOLLEN,
length - NDSOLLEN);
}
}
break;
case ND_NEIGHBOR_ADVERT:
{
const struct nd_neighbor_advert *p;
p = (const struct nd_neighbor_advert *)dp;
ND_TCHECK(p->nd_na_target);
ND_PRINT((ndo,", tgt is %s",
ip6addr_string(ndo, &p->nd_na_target)));
if (ndo->ndo_vflag) {
ND_PRINT((ndo,", Flags [%s]",
bittok2str(icmp6_nd_na_flag_values,
"none",
EXTRACT_32BITS(&p->nd_na_flags_reserved))));
#define NDADVLEN 24
icmp6_opt_print(ndo, (const u_char *)dp + NDADVLEN,
length - NDADVLEN);
#undef NDADVLEN
}
}
break;
case ND_REDIRECT:
#define RDR(i) ((const struct nd_redirect *)(i))
ND_TCHECK(RDR(dp)->nd_rd_dst);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, &RDR(dp)->nd_rd_dst)));
ND_TCHECK(RDR(dp)->nd_rd_target);
ND_PRINT((ndo," to %s",
ip6addr_string(ndo, &RDR(dp)->nd_rd_target)));
#define REDIRECTLEN 40
if (ndo->ndo_vflag) {
icmp6_opt_print(ndo, (const u_char *)dp + REDIRECTLEN,
length - REDIRECTLEN);
}
break;
#undef REDIRECTLEN
#undef RDR
case ICMP6_ROUTER_RENUMBERING:
icmp6_rrenum_print(ndo, bp, ep);
break;
case ICMP6_NI_QUERY:
case ICMP6_NI_REPLY:
icmp6_nodeinfo_print(ndo, length, bp, ep);
break;
case IND_SOLICIT:
case IND_ADVERT:
break;
case ICMP6_V2_MEMBERSHIP_REPORT:
mldv2_report_print(ndo, (const u_char *) dp, length);
break;
case ICMP6_MOBILEPREFIX_SOLICIT: /* fall through */
case ICMP6_HADISCOV_REQUEST:
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
break;
case ICMP6_HADISCOV_REPLY:
if (ndo->ndo_vflag) {
const struct in6_addr *in6;
const u_char *cp;
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
cp = (const u_char *)dp + length;
in6 = (const struct in6_addr *)(dp + 1);
for (; (const u_char *)in6 < cp; in6++) {
ND_TCHECK(*in6);
ND_PRINT((ndo,", %s", ip6addr_string(ndo, in6)));
}
}
break;
case ICMP6_MOBILEPREFIX_ADVERT:
if (ndo->ndo_vflag) {
ND_TCHECK(dp->icmp6_data16[0]);
ND_PRINT((ndo,", id 0x%04x", EXTRACT_16BITS(&dp->icmp6_data16[0])));
if (dp->icmp6_data16[1] & 0xc0)
ND_PRINT((ndo," "));
if (dp->icmp6_data16[1] & 0x80)
ND_PRINT((ndo,"M"));
if (dp->icmp6_data16[1] & 0x40)
ND_PRINT((ndo,"O"));
#define MPADVLEN 8
icmp6_opt_print(ndo, (const u_char *)dp + MPADVLEN,
length - MPADVLEN);
}
break;
case ND_RPL_MESSAGE:
/* plus 4, because struct icmp6_hdr contains 4 bytes of icmp payload */
rpl_print(ndo, dp, &dp->icmp6_data8[0], length-sizeof(struct icmp6_hdr)+4);
break;
default:
ND_PRINT((ndo,", length %u", length));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp,"\n\t", length);
return;
}
if (!ndo->ndo_vflag)
ND_PRINT((ndo,", length %u", length));
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static const struct udphdr *
get_upperlayer(netdissect_options *ndo, const u_char *bp, u_int *prot)
{
const u_char *ep;
const struct ip6_hdr *ip6 = (const struct ip6_hdr *)bp;
const struct udphdr *uh;
const struct ip6_hbh *hbh;
const struct ip6_frag *fragh;
const struct ah *ah;
u_int nh;
int hlen;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if (!ND_TTEST(ip6->ip6_nxt))
return NULL;
nh = ip6->ip6_nxt;
hlen = sizeof(struct ip6_hdr);
while (bp < ep) {
bp += hlen;
switch(nh) {
case IPPROTO_UDP:
case IPPROTO_TCP:
uh = (const struct udphdr *)bp;
if (ND_TTEST(uh->uh_dport)) {
*prot = nh;
return(uh);
}
else
return(NULL);
/* NOTREACHED */
case IPPROTO_HOPOPTS:
case IPPROTO_DSTOPTS:
case IPPROTO_ROUTING:
hbh = (const struct ip6_hbh *)bp;
if (!ND_TTEST(hbh->ip6h_len))
return(NULL);
nh = hbh->ip6h_nxt;
hlen = (hbh->ip6h_len + 1) << 3;
break;
case IPPROTO_FRAGMENT: /* this should be odd, but try anyway */
fragh = (const struct ip6_frag *)bp;
if (!ND_TTEST(fragh->ip6f_offlg))
return(NULL);
/* fragments with non-zero offset are meaningless */
if ((EXTRACT_16BITS(&fragh->ip6f_offlg) & IP6F_OFF_MASK) != 0)
return(NULL);
nh = fragh->ip6f_nxt;
hlen = sizeof(struct ip6_frag);
break;
case IPPROTO_AH:
ah = (const struct ah *)bp;
if (!ND_TTEST(ah->ah_len))
return(NULL);
nh = ah->ah_nxt;
hlen = (ah->ah_len + 2) << 2;
break;
default: /* unknown or undecodable header */
*prot = nh; /* meaningless, but set here anyway */
return(NULL);
}
}
return(NULL); /* should be notreached, though */
}
static void
icmp6_opt_print(netdissect_options *ndo, const u_char *bp, int resid)
{
const struct nd_opt_hdr *op;
const struct nd_opt_prefix_info *opp;
const struct nd_opt_mtu *opm;
const struct nd_opt_rdnss *oprd;
const struct nd_opt_dnssl *opds;
const struct nd_opt_advinterval *opa;
const struct nd_opt_homeagent_info *oph;
const struct nd_opt_route_info *opri;
const u_char *cp, *ep, *domp;
struct in6_addr in6;
const struct in6_addr *in6p;
size_t l;
u_int i;
#define ECHECK(var) if ((const u_char *)&(var) > ep - sizeof(var)) return
cp = bp;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
while (cp < ep) {
op = (const struct nd_opt_hdr *)cp;
ECHECK(op->nd_opt_len);
if (resid <= 0)
return;
if (op->nd_opt_len == 0)
goto trunc;
if (cp + (op->nd_opt_len << 3) > ep)
goto trunc;
ND_PRINT((ndo,"\n\t %s option (%u), length %u (%u): ",
tok2str(icmp6_opt_values, "unknown", op->nd_opt_type),
op->nd_opt_type,
op->nd_opt_len << 3,
op->nd_opt_len));
switch (op->nd_opt_type) {
case ND_OPT_SOURCE_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_TARGET_LINKADDR:
l = (op->nd_opt_len << 3) - 2;
print_lladdr(ndo, cp + 2, l);
break;
case ND_OPT_PREFIX_INFORMATION:
opp = (const struct nd_opt_prefix_info *)op;
ND_TCHECK(opp->nd_opt_pi_prefix);
ND_PRINT((ndo,"%s/%u%s, Flags [%s], valid time %s",
ip6addr_string(ndo, &opp->nd_opt_pi_prefix),
opp->nd_opt_pi_prefix_len,
(op->nd_opt_len != 4) ? "badlen" : "",
bittok2str(icmp6_opt_pi_flag_values, "none", opp->nd_opt_pi_flags_reserved),
get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_valid_time))));
ND_PRINT((ndo,", pref. time %s", get_lifetime(EXTRACT_32BITS(&opp->nd_opt_pi_preferred_time))));
break;
case ND_OPT_REDIRECTED_HEADER:
print_unknown_data(ndo, bp,"\n\t ",op->nd_opt_len<<3);
/* xxx */
break;
case ND_OPT_MTU:
opm = (const struct nd_opt_mtu *)op;
ND_TCHECK(opm->nd_opt_mtu_mtu);
ND_PRINT((ndo," %u%s",
EXTRACT_32BITS(&opm->nd_opt_mtu_mtu),
(op->nd_opt_len != 1) ? "bad option length" : "" ));
break;
case ND_OPT_RDNSS:
oprd = (const struct nd_opt_rdnss *)op;
l = (op->nd_opt_len - 1) / 2;
ND_PRINT((ndo," lifetime %us,",
EXTRACT_32BITS(&oprd->nd_opt_rdnss_lifetime)));
for (i = 0; i < l; i++) {
ND_TCHECK(oprd->nd_opt_rdnss_addr[i]);
ND_PRINT((ndo," addr: %s",
ip6addr_string(ndo, &oprd->nd_opt_rdnss_addr[i])));
}
break;
case ND_OPT_DNSSL:
opds = (const struct nd_opt_dnssl *)op;
ND_PRINT((ndo," lifetime %us, domain(s):",
EXTRACT_32BITS(&opds->nd_opt_dnssl_lifetime)));
domp = cp + 8; /* domain names, variable-sized, RFC1035-encoded */
while (domp < cp + (op->nd_opt_len << 3) && *domp != '\0')
{
ND_PRINT((ndo, " "));
if ((domp = ns_nprint (ndo, domp, bp)) == NULL)
goto trunc;
}
break;
case ND_OPT_ADVINTERVAL:
opa = (const struct nd_opt_advinterval *)op;
ND_TCHECK(opa->nd_opt_adv_interval);
ND_PRINT((ndo," %ums", EXTRACT_32BITS(&opa->nd_opt_adv_interval)));
break;
case ND_OPT_HOMEAGENT_INFO:
oph = (const struct nd_opt_homeagent_info *)op;
ND_TCHECK(oph->nd_opt_hai_lifetime);
ND_PRINT((ndo," preference %u, lifetime %u",
EXTRACT_16BITS(&oph->nd_opt_hai_preference),
EXTRACT_16BITS(&oph->nd_opt_hai_lifetime)));
break;
case ND_OPT_ROUTE_INFO:
opri = (const struct nd_opt_route_info *)op;
ND_TCHECK(opri->nd_opt_rti_lifetime);
memset(&in6, 0, sizeof(in6));
in6p = (const struct in6_addr *)(opri + 1);
switch (op->nd_opt_len) {
case 1:
break;
case 2:
ND_TCHECK2(*in6p, 8);
memcpy(&in6, opri + 1, 8);
break;
case 3:
ND_TCHECK(*in6p);
memcpy(&in6, opri + 1, sizeof(in6));
break;
default:
goto trunc;
}
ND_PRINT((ndo," %s/%u", ip6addr_string(ndo, &in6),
opri->nd_opt_rti_prefixlen));
ND_PRINT((ndo,", pref=%s", get_rtpref(opri->nd_opt_rti_flags)));
ND_PRINT((ndo,", lifetime=%s",
get_lifetime(EXTRACT_32BITS(&opri->nd_opt_rti_lifetime))));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo,cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
return;
}
break;
}
/* do we want to see an additional hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, cp+2,"\n\t ", (op->nd_opt_len << 3) - 2); /* skip option header */
cp += op->nd_opt_len << 3;
resid -= op->nd_opt_len << 3;
}
return;
trunc:
ND_PRINT((ndo, "[ndp opt]"));
return;
#undef ECHECK
}
static void
mld6_print(netdissect_options *ndo, const u_char *bp)
{
const struct mld6_hdr *mp = (const struct mld6_hdr *)bp;
const u_char *ep;
/* 'ep' points to the end of available data. */
ep = ndo->ndo_snapend;
if ((const u_char *)mp + sizeof(*mp) > ep)
return;
ND_PRINT((ndo,"max resp delay: %d ", EXTRACT_16BITS(&mp->mld6_maxdelay)));
ND_PRINT((ndo,"addr: %s", ip6addr_string(ndo, &mp->mld6_addr)));
}
static void
mldv2_report_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int group, nsrcs, ngroups;
u_int i, j;
/* Minimum len is 8 */
if (len < 8) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[1]);
ngroups = EXTRACT_16BITS(&icp->icmp6_data16[1]);
ND_PRINT((ndo,", %d group record(s)", ngroups));
if (ndo->ndo_vflag > 0) {
/* Print the group records */
group = 8;
for (i = 0; i < ngroups; i++) {
/* type(1) + auxlen(1) + numsrc(2) + grp(16) */
if (len < group + 20) {
ND_PRINT((ndo," [invalid number of groups]"));
return;
}
ND_TCHECK2(bp[group + 4], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[group + 4])));
ND_PRINT((ndo," %s", tok2str(mldv2report2str, " [v2-report-#%d]",
bp[group])));
nsrcs = (bp[group + 2] << 8) + bp[group + 3];
/* Check the number of sources and print them */
if (len < group + 20 + (nsrcs * sizeof(struct in6_addr))) {
ND_PRINT((ndo," [invalid number of sources %d]", nsrcs));
return;
}
if (ndo->ndo_vflag == 1)
ND_PRINT((ndo,", %d source(s)", nsrcs));
else {
/* Print the sources */
ND_PRINT((ndo," {"));
for (j = 0; j < nsrcs; j++) {
ND_TCHECK2(bp[group + 20 + j * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[group + 20 + j * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
}
/* Next group record */
group += 20 + nsrcs * sizeof(struct in6_addr);
ND_PRINT((ndo,"]"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
mldv2_query_print(netdissect_options *ndo, const u_char *bp, u_int len)
{
const struct icmp6_hdr *icp = (const struct icmp6_hdr *) bp;
u_int mrc;
int mrt, qqi;
u_int nsrcs;
register u_int i;
/* Minimum len is 28 */
if (len < 28) {
ND_PRINT((ndo," [invalid len %d]", len));
return;
}
ND_TCHECK(icp->icmp6_data16[0]);
mrc = EXTRACT_16BITS(&icp->icmp6_data16[0]);
if (mrc < 32768) {
mrt = mrc;
} else {
mrt = ((mrc & 0x0fff) | 0x1000) << (((mrc & 0x7000) >> 12) + 3);
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo," [max resp delay=%d]", mrt));
}
ND_TCHECK2(bp[8], sizeof(struct in6_addr));
ND_PRINT((ndo," [gaddr %s", ip6addr_string(ndo, &bp[8])));
if (ndo->ndo_vflag) {
ND_TCHECK(bp[25]);
if (bp[24] & 0x08) {
ND_PRINT((ndo," sflag"));
}
if (bp[24] & 0x07) {
ND_PRINT((ndo," robustness=%d", bp[24] & 0x07));
}
if (bp[25] < 128) {
qqi = bp[25];
} else {
qqi = ((bp[25] & 0x0f) | 0x10) << (((bp[25] & 0x70) >> 4) + 3);
}
ND_PRINT((ndo," qqi=%d", qqi));
}
ND_TCHECK2(bp[26], 2);
nsrcs = EXTRACT_16BITS(&bp[26]);
if (nsrcs > 0) {
if (len < 28 + nsrcs * sizeof(struct in6_addr))
ND_PRINT((ndo," [invalid number of sources]"));
else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo," {"));
for (i = 0; i < nsrcs; i++) {
ND_TCHECK2(bp[28 + i * sizeof(struct in6_addr)],
sizeof(struct in6_addr));
ND_PRINT((ndo," %s", ip6addr_string(ndo, &bp[28 + i * sizeof(struct in6_addr)])));
}
ND_PRINT((ndo," }"));
} else
ND_PRINT((ndo,", %d source(s)", nsrcs));
}
ND_PRINT((ndo,"]"));
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
return;
}
static void
dnsname_print(netdissect_options *ndo, const u_char *cp, const u_char *ep)
{
int i;
/* DNS name decoding - no decompression */
ND_PRINT((ndo,", \""));
while (cp < ep) {
i = *cp++;
if (i) {
if (i > ep - cp) {
ND_PRINT((ndo,"???"));
break;
}
while (i-- && cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
if (cp + 1 < ep && *cp)
ND_PRINT((ndo,"."));
} else {
if (cp == ep) {
/* FQDN */
ND_PRINT((ndo,"."));
} else if (cp + 1 == ep && *cp == '\0') {
/* truncated */
} else {
/* invalid */
ND_PRINT((ndo,"???"));
}
break;
}
}
ND_PRINT((ndo,"\""));
}
static void
icmp6_nodeinfo_print(netdissect_options *ndo, u_int icmp6len, const u_char *bp, const u_char *ep)
{
const struct icmp6_nodeinfo *ni6;
const struct icmp6_hdr *dp;
const u_char *cp;
size_t siz, i;
int needcomma;
if (ep < bp)
return;
dp = (const struct icmp6_hdr *)bp;
ni6 = (const struct icmp6_nodeinfo *)bp;
siz = ep - bp;
switch (ni6->ni_type) {
case ICMP6_NI_QUERY:
if (siz == sizeof(*dp) + 4) {
/* KAME who-are-you */
ND_PRINT((ndo," who-are-you request"));
break;
}
ND_PRINT((ndo," node information query"));
ND_TCHECK2(*dp, sizeof(*ni6));
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," (")); /*)*/
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
ND_PRINT((ndo,"noop"));
break;
case NI_QTYPE_SUPTYPES:
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
ND_PRINT((ndo,"DNS name"));
break;
case NI_QTYPE_NODEADDR:
ND_PRINT((ndo,"node addresses"));
i = ni6->ni_flags;
if (!i)
break;
/* NI_NODEADDR_FLAG_TRUNCATE undefined for query */
ND_PRINT((ndo," [%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : ""));
break;
default:
ND_PRINT((ndo,"unknown"));
break;
}
if (ni6->ni_qtype == NI_QTYPE_NOOP ||
ni6->ni_qtype == NI_QTYPE_SUPTYPES) {
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid len"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
/* XXX backward compat, icmp-name-lookup-03 */
if (siz == sizeof(*ni6)) {
ND_PRINT((ndo,", 03 draft"));
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (ni6->ni_code) {
case ICMP6_NI_SUBJ_IPV6:
if (!ND_TTEST2(*dp,
sizeof(*ni6) + sizeof(struct in6_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in6_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ip6addr_string(ndo, ni6 + 1)));
break;
case ICMP6_NI_SUBJ_FQDN:
ND_PRINT((ndo,", subject=DNS name"));
cp = (const u_char *)(ni6 + 1);
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
break;
case ICMP6_NI_SUBJ_IPV4:
if (!ND_TTEST2(*dp, sizeof(*ni6) + sizeof(struct in_addr)))
break;
if (siz != sizeof(*ni6) + sizeof(struct in_addr)) {
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid subject len"));
break;
}
ND_PRINT((ndo,", subject=%s",
ipaddr_string(ndo, ni6 + 1)));
break;
default:
ND_PRINT((ndo,", unknown subject"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
case ICMP6_NI_REPLY:
if (icmp6len > siz) {
ND_PRINT((ndo,"[|icmp6: node information reply]"));
break;
}
needcomma = 0;
ni6 = (const struct icmp6_nodeinfo *)dp;
ND_PRINT((ndo," node information reply"));
ND_PRINT((ndo," (")); /*)*/
switch (ni6->ni_code) {
case ICMP6_NI_SUCCESS:
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"success"));
needcomma++;
}
break;
case ICMP6_NI_REFUSED:
ND_PRINT((ndo,"refused"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case ICMP6_NI_UNKNOWN:
ND_PRINT((ndo,"unknown"));
needcomma++;
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
}
if (ni6->ni_code != ICMP6_NI_SUCCESS) {
/*(*/
ND_PRINT((ndo,")"));
break;
}
switch (EXTRACT_16BITS(&ni6->ni_qtype)) {
case NI_QTYPE_NOOP:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"noop"));
if (siz != sizeof(*ni6))
if (ndo->ndo_vflag)
ND_PRINT((ndo,", invalid length"));
break;
case NI_QTYPE_SUPTYPES:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"supported qtypes"));
i = EXTRACT_16BITS(&ni6->ni_flags);
if (i)
ND_PRINT((ndo," [%s]", (i & 0x01) ? "C" : ""));
break;
case NI_QTYPE_FQDN:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"DNS name"));
cp = (const u_char *)(ni6 + 1) + 4;
if (cp[0] == ep - cp - 1) {
/* icmp-name-lookup-03, pascal string */
if (ndo->ndo_vflag)
ND_PRINT((ndo,", 03 draft"));
cp++;
ND_PRINT((ndo,", \""));
while (cp < ep) {
safeputchar(ndo, *cp);
cp++;
}
ND_PRINT((ndo,"\""));
} else
dnsname_print(ndo, cp, ep);
if ((EXTRACT_16BITS(&ni6->ni_flags) & 0x01) != 0)
ND_PRINT((ndo," [TTL=%u]", EXTRACT_32BITS(ni6 + 1)));
break;
case NI_QTYPE_NODEADDR:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"node addresses"));
i = sizeof(*ni6);
while (i < siz) {
if (i + sizeof(struct in6_addr) + sizeof(int32_t) > siz)
break;
ND_PRINT((ndo," %s", ip6addr_string(ndo, bp + i)));
i += sizeof(struct in6_addr);
ND_PRINT((ndo,"(%d)", (int32_t)EXTRACT_32BITS(bp + i)));
i += sizeof(int32_t);
}
i = ni6->ni_flags;
if (!i)
break;
ND_PRINT((ndo," [%s%s%s%s%s%s%s]",
(i & NI_NODEADDR_FLAG_ANYCAST) ? "a" : "",
(i & NI_NODEADDR_FLAG_GLOBAL) ? "G" : "",
(i & NI_NODEADDR_FLAG_SITELOCAL) ? "S" : "",
(i & NI_NODEADDR_FLAG_LINKLOCAL) ? "L" : "",
(i & NI_NODEADDR_FLAG_COMPAT) ? "C" : "",
(i & NI_NODEADDR_FLAG_ALL) ? "A" : "",
(i & NI_NODEADDR_FLAG_TRUNCATE) ? "T" : ""));
break;
default:
if (needcomma)
ND_PRINT((ndo,", "));
ND_PRINT((ndo,"unknown"));
break;
}
/*(*/
ND_PRINT((ndo,")"));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|icmp6]"));
}
static void
icmp6_rrenum_print(netdissect_options *ndo, const u_char *bp, const u_char *ep)
{
const struct icmp6_router_renum *rr6;
const char *cp;
const struct rr_pco_match *match;
const struct rr_pco_use *use;
char hbuf[NI_MAXHOST];
int n;
if (ep < bp)
return;
rr6 = (const struct icmp6_router_renum *)bp;
cp = (const char *)(rr6 + 1);
ND_TCHECK(rr6->rr_reserved);
switch (rr6->rr_code) {
case ICMP6_ROUTER_RENUMBERING_COMMAND:
ND_PRINT((ndo,"router renum: command"));
break;
case ICMP6_ROUTER_RENUMBERING_RESULT:
ND_PRINT((ndo,"router renum: result"));
break;
case ICMP6_ROUTER_RENUMBERING_SEQNUM_RESET:
ND_PRINT((ndo,"router renum: sequence number reset"));
break;
default:
ND_PRINT((ndo,"router renum: code-#%d", rr6->rr_code));
break;
}
ND_PRINT((ndo,", seq=%u", EXTRACT_32BITS(&rr6->rr_seqnum)));
if (ndo->ndo_vflag) {
#define F(x, y) ((rr6->rr_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"[")); /*]*/
if (rr6->rr_flags) {
ND_PRINT((ndo,"%s%s%s%s%s,", F(ICMP6_RR_FLAGS_TEST, "T"),
F(ICMP6_RR_FLAGS_REQRESULT, "R"),
F(ICMP6_RR_FLAGS_FORCEAPPLY, "A"),
F(ICMP6_RR_FLAGS_SPECSITE, "S"),
F(ICMP6_RR_FLAGS_PREVDONE, "P")));
}
ND_PRINT((ndo,"seg=%u,", rr6->rr_segnum));
ND_PRINT((ndo,"maxdelay=%u", EXTRACT_16BITS(&rr6->rr_maxdelay)));
if (rr6->rr_reserved)
ND_PRINT((ndo,"rsvd=0x%x", EXTRACT_32BITS(&rr6->rr_reserved)));
/*[*/
ND_PRINT((ndo,"]"));
#undef F
}
if (rr6->rr_code == ICMP6_ROUTER_RENUMBERING_COMMAND) {
match = (const struct rr_pco_match *)cp;
cp = (const char *)(match + 1);
ND_TCHECK(match->rpm_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"match(")); /*)*/
switch (match->rpm_code) {
case RPM_PCO_ADD: ND_PRINT((ndo,"add")); break;
case RPM_PCO_CHANGE: ND_PRINT((ndo,"change")); break;
case RPM_PCO_SETGLOBAL: ND_PRINT((ndo,"setglobal")); break;
default: ND_PRINT((ndo,"#%u", match->rpm_code)); break;
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,",ord=%u", match->rpm_ordinal));
ND_PRINT((ndo,",min=%u", match->rpm_minlen));
ND_PRINT((ndo,",max=%u", match->rpm_maxlen));
}
if (addrtostr6(&match->rpm_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,",%s/%u", hbuf, match->rpm_matchlen));
else
ND_PRINT((ndo,",?/%u", match->rpm_matchlen));
/*(*/
ND_PRINT((ndo,")"));
n = match->rpm_len - 3;
if (n % 4)
goto trunc;
n /= 4;
while (n-- > 0) {
use = (const struct rr_pco_use *)cp;
cp = (const char *)(use + 1);
ND_TCHECK(use->rpu_prefix);
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo,"\n\t"));
else
ND_PRINT((ndo," "));
ND_PRINT((ndo,"use(")); /*)*/
if (use->rpu_flags) {
#define F(x, y) ((use->rpu_flags) & (x) ? (y) : "")
ND_PRINT((ndo,"%s%s,",
F(ICMP6_RR_PCOUSE_FLAGS_DECRVLTIME, "V"),
F(ICMP6_RR_PCOUSE_FLAGS_DECRPLTIME, "P")));
#undef F
}
if (ndo->ndo_vflag) {
ND_PRINT((ndo,"mask=0x%x,", use->rpu_ramask));
ND_PRINT((ndo,"raflags=0x%x,", use->rpu_raflags));
if (~use->rpu_vltime == 0)
ND_PRINT((ndo,"vltime=infty,"));
else
ND_PRINT((ndo,"vltime=%u,",
EXTRACT_32BITS(&use->rpu_vltime)));
if (~use->rpu_pltime == 0)
ND_PRINT((ndo,"pltime=infty,"));
else
ND_PRINT((ndo,"pltime=%u,",
EXTRACT_32BITS(&use->rpu_pltime)));
}
if (addrtostr6(&use->rpu_prefix, hbuf, sizeof(hbuf)))
ND_PRINT((ndo,"%s/%u/%u", hbuf, use->rpu_uselen,
use->rpu_keeplen));
else
ND_PRINT((ndo,"?/%u/%u", use->rpu_uselen,
use->rpu_keeplen));
/*(*/
ND_PRINT((ndo,")"));
}
}
return;
trunc:
ND_PRINT((ndo,"[|icmp6]"));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_2696_0 |
crossvul-cpp_data_good_2648_2 | /*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that: (1) source code
* distributions retain the above copyright notice and this paragraph
* in its entirety, and (2) distributions including binary code include
* the above copyright notice and this paragraph in its entirety in
* the documentation or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND
* WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT
* LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* Original code by Hannes Gredler (hannes@gredler.at)
*/
/* \summary: MPLS LSP PING printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include "netdissect.h"
#include "extract.h"
#include "addrtoname.h"
#include "l2vpn.h"
#include "oui.h"
/* RFC 4349 */
/*
* LSPPING common header
*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Version Number | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Message Type | Reply mode | Return Code | Return Subcode|
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's Handle |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sequence Number |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Sent (seconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Sent (microseconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Received (seconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TimeStamp Received (microseconds) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | TLVs ... |
* . .
* . .
* . .
*/
struct lspping_common_header {
uint8_t version[2];
uint8_t global_flags[2];
uint8_t msg_type;
uint8_t reply_mode;
uint8_t return_code;
uint8_t return_subcode;
uint8_t sender_handle[4];
uint8_t seq_number[4];
uint8_t ts_sent_sec[4];
uint8_t ts_sent_usec[4];
uint8_t ts_rcvd_sec[4];
uint8_t ts_rcvd_usec[4];
};
#define LSPPING_VERSION 1
static const struct tok lspping_msg_type_values[] = {
{ 1, "MPLS Echo Request"},
{ 2, "MPLS Echo Reply"},
{ 0, NULL}
};
static const struct tok lspping_reply_mode_values[] = {
{ 1, "Do not reply"},
{ 2, "Reply via an IPv4/IPv6 UDP packet"},
{ 3, "Reply via an IPv4/IPv6 UDP packet with Router Alert"},
{ 4, "Reply via application level control channel"},
{ 0, NULL}
};
static const struct tok lspping_return_code_values[] = {
{ 0, "No return code or return code contained in the Error Code TLV"},
{ 1, "Malformed echo request received"},
{ 2, "One or more of the TLVs was not understood"},
{ 3, "Replying router is an egress for the FEC at stack depth"},
{ 4, "Replying router has no mapping for the FEC at stack depth"},
{ 5, "Reserved"},
{ 6, "Reserved"},
{ 7, "Reserved"},
{ 8, "Label switched at stack-depth"},
{ 9, "Label switched but no MPLS forwarding at stack-depth"},
{ 10, "Mapping for this FEC is not the given label at stack depth"},
{ 11, "No label entry at stack-depth"},
{ 12, "Protocol not associated with interface at FEC stack depth"},
{ 13, "Premature termination of ping due to label stack shrinking to a single label"},
{ 0, NULL},
};
/*
* LSPPING TLV header
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Type | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Value |
* . .
* . .
* . .
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_header {
uint8_t type[2];
uint8_t length[2];
};
#define LSPPING_TLV_TARGET_FEC_STACK 1
#define LSPPING_TLV_DOWNSTREAM_MAPPING 2
#define LSPPING_TLV_PAD 3
/* not assigned 4 */
#define LSPPING_TLV_VENDOR_ENTERPRISE 5
#define LSPPING_TLV_VENDOR_ENTERPRISE_LEN 4
/* not assigned 6 */
#define LSPPING_TLV_INTERFACE_LABEL_STACK 7
/* not assigned 8 */
#define LSPPING_TLV_ERROR_CODE 9
#define LSPPING_TLV_REPLY_TOS_BYTE 10
#define LSPPING_TLV_BFD_DISCRIMINATOR 15 /* draft-ietf-bfd-mpls-02 */
#define LSPPING_TLV_BFD_DISCRIMINATOR_LEN 4
#define LSPPING_TLV_VENDOR_PRIVATE 0xfc00
static const struct tok lspping_tlv_values[] = {
{ LSPPING_TLV_TARGET_FEC_STACK, "Target FEC Stack" },
{ LSPPING_TLV_DOWNSTREAM_MAPPING, "Downstream Mapping" },
{ LSPPING_TLV_PAD, "Pad" },
{ LSPPING_TLV_ERROR_CODE, "Error Code" },
{ LSPPING_TLV_VENDOR_ENTERPRISE, "Vendor Enterprise Code" },
{ LSPPING_TLV_INTERFACE_LABEL_STACK, "Interface Label Stack" },
{ LSPPING_TLV_REPLY_TOS_BYTE, "Reply TOS Byte" },
{ LSPPING_TLV_BFD_DISCRIMINATOR, "BFD Discriminator" },
{ LSPPING_TLV_VENDOR_PRIVATE, "Vendor Private Code" },
{ 0, NULL}
};
#define LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4 1
#define LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6 2
#define LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4 3
#define LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6 4
/* not assigned 5 */
#define LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4 6
#define LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6 7
#define LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT 8
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD 9
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW 10
#define LSPPING_TLV_TARGETFEC_SUBTLV_FEC_129_PW 11
#define LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4 12
#define LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6 13
#define LSPPING_TLV_TARGETFEC_SUBTLV_GENERIC_IPV4 14
#define LSPPING_TLV_TARGETFEC_SUBTLV_GENERIC_IPV6 15
#define LSPPING_TLV_TARGETFEC_SUBTLV_NIL_FEC 16
static const struct tok lspping_tlvtargetfec_subtlv_values[] = {
{ LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4, "LDP IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6, "LDP IPv6 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4, "RSVP IPv4 Session Query"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6, "RSVP IPv6 Session Query"},
{ 5, "Reserved"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4, "VPN IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6, "VPN IPv6 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT, "L2 VPN endpoint"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD, "FEC 128 pseudowire (old)"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW, "FEC 128 pseudowire"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4, "BGP labeled IPv4 prefix"},
{ LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6, "BGP labeled IPv6 prefix"},
{ 0, NULL}
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t {
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t {
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 tunnel end point address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Extended Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 tunnel sender address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | LSP ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t {
uint8_t tunnel_endpoint [4];
uint8_t res[2];
uint8_t tunnel_id[2];
uint8_t extended_tunnel_id[4];
uint8_t tunnel_sender [4];
uint8_t res2[2];
uint8_t lsp_id [2];
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 tunnel end point address |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | Tunnel ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Extended Tunnel ID |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 tunnel sender address |
* | |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Must Be Zero | LSP ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t {
uint8_t tunnel_endpoint [16];
uint8_t res[2];
uint8_t tunnel_id[2];
uint8_t extended_tunnel_id[16];
uint8_t tunnel_sender [16];
uint8_t res2[2];
uint8_t lsp_id [2];
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t {
uint8_t rd [8];
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t {
uint8_t rd [8];
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Route Distinguisher |
* | (8 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's VE ID | Receiver's VE ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encapsulation Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* 0 1 2 3
*/
struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t {
uint8_t rd [8];
uint8_t sender_ve_id [2];
uint8_t receiver_ve_id [2];
uint8_t encapsulation[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Remote PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_fec_128_pw_old {
uint8_t remote_pe_address [4];
uint8_t pw_id [4];
uint8_t pw_type[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Sender's PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Remote PE Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | PW Type | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_fec_128_pw {
uint8_t sender_pe_address [4];
uint8_t remote_pe_address [4];
uint8_t pw_id [4];
uint8_t pw_type[2];
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv4 prefix |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t {
uint8_t prefix [4];
uint8_t prefix_len;
};
/*
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | IPv6 prefix |
* | (16 octets) |
* | |
* | |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Prefix Length | Must Be Zero |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t {
uint8_t prefix [16];
uint8_t prefix_len;
};
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | MTU | Address Type | Resvd (SBZ) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream IP Address (4 or 16 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Interface Address (4 or 16 octets) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Multipath Type| Depth Limit | Multipath Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . (Multipath Information) .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Label | Protocol |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* . .
* . .
* . .
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Downstream Label | Protocol |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
/* Enough to get the address type */
struct lspping_tlv_downstream_map_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
};
struct lspping_tlv_downstream_map_ipv4_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[4];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_ipv4_unmb_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[4];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_ipv6_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[16];
uint8_t downstream_interface[16];
};
struct lspping_tlv_downstream_map_ipv6_unmb_t {
uint8_t mtu [2];
uint8_t address_type;
uint8_t ds_flags;
uint8_t downstream_ip[16];
uint8_t downstream_interface[4];
};
struct lspping_tlv_downstream_map_info_t {
uint8_t multipath_type;
uint8_t depth_limit;
uint8_t multipath_length [2];
};
#define LSPPING_AFI_IPV4 1
#define LSPPING_AFI_IPV4_UNMB 2
#define LSPPING_AFI_IPV6 3
#define LSPPING_AFI_IPV6_UNMB 4
static const struct tok lspping_tlv_downstream_addr_values[] = {
{ LSPPING_AFI_IPV4, "IPv4"},
{ LSPPING_AFI_IPV4_UNMB, "Unnumbered IPv4"},
{ LSPPING_AFI_IPV6, "IPv6"},
{ LSPPING_AFI_IPV6_UNMB, "IPv6"},
{ 0, NULL}
};
void
lspping_print(netdissect_options *ndo,
register const u_char *pptr, register u_int len)
{
const struct lspping_common_header *lspping_com_header;
const struct lspping_tlv_header *lspping_tlv_header;
const struct lspping_tlv_header *lspping_subtlv_header;
const u_char *tptr,*tlv_tptr,*subtlv_tptr;
u_int tlen,lspping_tlv_len,lspping_tlv_type,tlv_tlen;
int tlv_hexdump,subtlv_hexdump;
u_int lspping_subtlv_len,lspping_subtlv_type;
struct timeval timestamp;
union {
const struct lspping_tlv_downstream_map_t *lspping_tlv_downstream_map;
const struct lspping_tlv_downstream_map_ipv4_t *lspping_tlv_downstream_map_ipv4;
const struct lspping_tlv_downstream_map_ipv4_unmb_t *lspping_tlv_downstream_map_ipv4_unmb;
const struct lspping_tlv_downstream_map_ipv6_t *lspping_tlv_downstream_map_ipv6;
const struct lspping_tlv_downstream_map_ipv6_unmb_t *lspping_tlv_downstream_map_ipv6_unmb;
const struct lspping_tlv_downstream_map_info_t *lspping_tlv_downstream_map_info;
} tlv_ptr;
union {
const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *lspping_tlv_targetfec_subtlv_ldp_ipv4;
const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *lspping_tlv_targetfec_subtlv_ldp_ipv6;
const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *lspping_tlv_targetfec_subtlv_rsvp_ipv4;
const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *lspping_tlv_targetfec_subtlv_rsvp_ipv6;
const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv4;
const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *lspping_tlv_targetfec_subtlv_l3vpn_ipv6;
const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *lspping_tlv_targetfec_subtlv_l2vpn_endpt;
const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *lspping_tlv_targetfec_subtlv_l2vpn_vcid_old;
const struct lspping_tlv_targetfec_subtlv_fec_128_pw *lspping_tlv_targetfec_subtlv_l2vpn_vcid;
const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *lspping_tlv_targetfec_subtlv_bgp_ipv4;
const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *lspping_tlv_targetfec_subtlv_bgp_ipv6;
} subtlv_ptr;
tptr=pptr;
lspping_com_header = (const struct lspping_common_header *)pptr;
if (len < sizeof(const struct lspping_common_header))
goto tooshort;
ND_TCHECK(*lspping_com_header);
/*
* Sanity checking of the header.
*/
if (EXTRACT_16BITS(&lspping_com_header->version[0]) != LSPPING_VERSION) {
ND_PRINT((ndo, "LSP-PING version %u packet not supported",
EXTRACT_16BITS(&lspping_com_header->version[0])));
return;
}
/* in non-verbose mode just lets print the basic Message Type*/
if (ndo->ndo_vflag < 1) {
ND_PRINT((ndo, "LSP-PINGv%u, %s, seq %u, length: %u",
EXTRACT_16BITS(&lspping_com_header->version[0]),
tok2str(lspping_msg_type_values, "unknown (%u)",lspping_com_header->msg_type),
EXTRACT_32BITS(lspping_com_header->seq_number),
len));
return;
}
/* ok they seem to want to know everything - lets fully decode it */
tlen=len;
ND_PRINT((ndo, "\n\tLSP-PINGv%u, msg-type: %s (%u), length: %u\n\t reply-mode: %s (%u)",
EXTRACT_16BITS(&lspping_com_header->version[0]),
tok2str(lspping_msg_type_values, "unknown",lspping_com_header->msg_type),
lspping_com_header->msg_type,
len,
tok2str(lspping_reply_mode_values, "unknown",lspping_com_header->reply_mode),
lspping_com_header->reply_mode));
/*
* the following return codes require that the subcode is attached
* at the end of the translated token output
*/
if (lspping_com_header->return_code == 3 ||
lspping_com_header->return_code == 4 ||
lspping_com_header->return_code == 8 ||
lspping_com_header->return_code == 10 ||
lspping_com_header->return_code == 11 ||
lspping_com_header->return_code == 12 )
ND_PRINT((ndo, "\n\t Return Code: %s %u (%u)\n\t Return Subcode: (%u)",
tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code),
lspping_com_header->return_subcode,
lspping_com_header->return_code,
lspping_com_header->return_subcode));
else
ND_PRINT((ndo, "\n\t Return Code: %s (%u)\n\t Return Subcode: (%u)",
tok2str(lspping_return_code_values, "unknown",lspping_com_header->return_code),
lspping_com_header->return_code,
lspping_com_header->return_subcode));
ND_PRINT((ndo, "\n\t Sender Handle: 0x%08x, Sequence: %u",
EXTRACT_32BITS(lspping_com_header->sender_handle),
EXTRACT_32BITS(lspping_com_header->seq_number)));
timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_sent_sec);
timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_sent_usec);
ND_PRINT((ndo, "\n\t Sender Timestamp: "));
ts_print(ndo, ×tamp);
timestamp.tv_sec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_sec);
timestamp.tv_usec=EXTRACT_32BITS(lspping_com_header->ts_rcvd_usec);
ND_PRINT((ndo, "Receiver Timestamp: "));
if ((timestamp.tv_sec != 0) && (timestamp.tv_usec != 0))
ts_print(ndo, ×tamp);
else
ND_PRINT((ndo, "no timestamp"));
tptr+=sizeof(const struct lspping_common_header);
tlen-=sizeof(const struct lspping_common_header);
while (tlen != 0) {
/* Does the TLV go past the end of the packet? */
if (tlen < sizeof(struct lspping_tlv_header))
goto tooshort;
/* did we capture enough for fully decoding the tlv header ? */
ND_TCHECK2(*tptr, sizeof(struct lspping_tlv_header));
lspping_tlv_header = (const struct lspping_tlv_header *)tptr;
lspping_tlv_type=EXTRACT_16BITS(lspping_tlv_header->type);
lspping_tlv_len=EXTRACT_16BITS(lspping_tlv_header->length);
ND_PRINT((ndo, "\n\t %s TLV (%u), length: %u",
tok2str(lspping_tlv_values,
"Unknown",
lspping_tlv_type),
lspping_tlv_type,
lspping_tlv_len));
/* some little sanity checking */
if (lspping_tlv_len == 0) {
tptr+=sizeof(struct lspping_tlv_header);
tlen-=sizeof(struct lspping_tlv_header);
continue; /* no value to dissect */
}
tlv_tptr=tptr+sizeof(struct lspping_tlv_header);
tlv_tlen=lspping_tlv_len; /* header not included -> no adjustment */
/* Does the TLV go past the end of the packet? */
if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header))
goto tooshort;
/* did we capture enough for fully decoding the tlv ? */
ND_TCHECK2(*tlv_tptr, lspping_tlv_len);
tlv_hexdump=FALSE;
switch(lspping_tlv_type) {
case LSPPING_TLV_TARGET_FEC_STACK:
while (tlv_tlen != 0) {
/* Does the subTLV header go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* did we capture enough for fully decoding the subtlv header ? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_header));
subtlv_hexdump=FALSE;
lspping_subtlv_header = (const struct lspping_tlv_header *)tlv_tptr;
lspping_subtlv_type=EXTRACT_16BITS(lspping_subtlv_header->type);
lspping_subtlv_len=EXTRACT_16BITS(lspping_subtlv_header->length);
subtlv_tptr=tlv_tptr+sizeof(struct lspping_tlv_header);
/* Does the subTLV go past the end of the TLV? */
if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for fully decoding the subTLV? */
ND_TCHECK2(*subtlv_tptr, lspping_subtlv_len);
ND_PRINT((ndo, "\n\t %s subTLV (%u), length: %u",
tok2str(lspping_tlvtargetfec_subtlv_values,
"Unknown",
lspping_subtlv_type),
lspping_subtlv_type,
lspping_subtlv_len));
switch(lspping_subtlv_type) {
case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 5) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_ldp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_LDP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 17) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_ldp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_ldp_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 5) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 5"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_bgp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_BGP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 17) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 17"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_bgp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t %s/%u",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_bgp_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 20) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 20"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_rsvp_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \
"\n\t tunnel-id 0x%04x, extended tunnel-id %s",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_endpoint),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_sender),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->lsp_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->tunnel_id),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv4->extended_tunnel_id)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_RSVP_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 56) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 56"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_rsvp_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t tunnel end-point %s, tunnel sender %s, lsp-id 0x%04x" \
"\n\t tunnel-id 0x%04x, extended tunnel-id %s",
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_endpoint),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_sender),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->lsp_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->tunnel_id),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_rsvp_ipv6->extended_tunnel_id)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV4:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 13) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 13"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4 = \
(const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv4_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, %s/%u",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->rd),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv4->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L3VPN_IPV6:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 25) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 25"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6 = \
(const struct lspping_tlv_targetfec_subtlv_l3vpn_ipv6_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, %s/%u",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->rd),
ip6addr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix),
subtlv_ptr.lspping_tlv_targetfec_subtlv_l3vpn_ipv6->prefix_len));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_L2VPN_ENDPT:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 14) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt = \
(const struct lspping_tlv_targetfec_subtlv_l2vpn_endpt_t *)subtlv_tptr;
ND_PRINT((ndo, "\n\t RD: %s, Sender VE ID: %u, Receiver VE ID: %u" \
"\n\t Encapsulation Type: %s (%u)",
bgp_vpn_rd_print(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->rd),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->sender_ve_id),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->receiver_ve_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_endpt->encapsulation)));
}
break;
/* the old L2VPN VCID subTLV does not have support for the sender field */
case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW_OLD:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 10) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 10"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old = \
(const struct lspping_tlv_targetfec_subtlv_fec_128_pw_old *)subtlv_tptr;
ND_PRINT((ndo, "\n\t Remote PE: %s" \
"\n\t PW ID: 0x%08x, PW Type: %s (%u)",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->remote_pe_address),
EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid_old->pw_type)));
}
break;
case LSPPING_TLV_TARGETFEC_SUBTLV_FEC_128_PW:
/* Is the subTLV length correct? */
if (lspping_subtlv_len != 14) {
ND_PRINT((ndo, "\n\t invalid subTLV length, should be 14"));
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
} else {
subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid = \
(const struct lspping_tlv_targetfec_subtlv_fec_128_pw *)subtlv_tptr;
ND_PRINT((ndo, "\n\t Sender PE: %s, Remote PE: %s" \
"\n\t PW ID: 0x%08x, PW Type: %s (%u)",
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->sender_pe_address),
ipaddr_string(ndo, subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->remote_pe_address),
EXTRACT_32BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_id),
tok2str(mpls_pw_types_values,
"unknown",
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type)),
EXTRACT_16BITS(subtlv_ptr.lspping_tlv_targetfec_subtlv_l2vpn_vcid->pw_type)));
}
break;
default:
subtlv_hexdump=TRUE; /* unknown subTLV just hexdump it */
break;
}
/* do we want to see an additionally subtlv hexdump ? */
if (ndo->ndo_vflag > 1 || subtlv_hexdump==TRUE)
print_unknown_data(ndo, tlv_tptr+sizeof(struct lspping_tlv_header), \
"\n\t ",
lspping_subtlv_len);
/* All subTLVs are aligned to four octet boundary */
if (lspping_subtlv_len % 4) {
lspping_subtlv_len += 4 - (lspping_subtlv_len % 4);
/* Does the subTLV, including padding, go past the end of the TLV? */
if (tlv_tlen < lspping_subtlv_len+sizeof(struct lspping_tlv_header)) {
ND_PRINT((ndo, "\n\t\t TLV is too short"));
return;
}
}
tlv_tptr+=lspping_subtlv_len;
tlv_tlen-=lspping_subtlv_len+sizeof(struct lspping_tlv_header);
}
break;
case LSPPING_TLV_DOWNSTREAM_MAPPING:
/* Does the header go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough to get the address family? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_t));
tlv_ptr.lspping_tlv_downstream_map= \
(const struct lspping_tlv_downstream_map_t *)tlv_tptr;
/* that strange thing with the downstream map TLV is that until now
* we do not know if its IPv4 or IPv6 or is unnumbered; after
* we find the address-type, we recast the tlv_tptr and move on. */
ND_PRINT((ndo, "\n\t MTU: %u, Address-Type: %s (%u)",
EXTRACT_16BITS(tlv_ptr.lspping_tlv_downstream_map->mtu),
tok2str(lspping_tlv_downstream_addr_values,
"unknown",
tlv_ptr.lspping_tlv_downstream_map->address_type),
tlv_ptr.lspping_tlv_downstream_map->address_type));
switch(tlv_ptr.lspping_tlv_downstream_map->address_type) {
case LSPPING_AFI_IPV4:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_t));
tlv_ptr.lspping_tlv_downstream_map_ipv4= \
(const struct lspping_tlv_downstream_map_ipv4_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface IP: %s",
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_ip),
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_t);
break;
case LSPPING_AFI_IPV4_UNMB:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t));
tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb= \
(const struct lspping_tlv_downstream_map_ipv4_unmb_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface Index: 0x%08x",
ipaddr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_ip),
EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv4_unmb->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv4_unmb_t);
break;
case LSPPING_AFI_IPV6:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_t));
tlv_ptr.lspping_tlv_downstream_map_ipv6= \
(const struct lspping_tlv_downstream_map_ipv6_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface IP: %s",
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_ip),
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_t);
break;
case LSPPING_AFI_IPV6_UNMB:
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t));
tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb= \
(const struct lspping_tlv_downstream_map_ipv6_unmb_t *)tlv_tptr;
ND_PRINT((ndo, "\n\t Downstream IP: %s" \
"\n\t Downstream Interface Index: 0x%08x",
ip6addr_string(ndo, tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_ip),
EXTRACT_32BITS(tlv_ptr.lspping_tlv_downstream_map_ipv6_unmb->downstream_interface)));
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_ipv6_unmb_t);
break;
default:
/* should not happen ! - no error message - tok2str() has barked already */
break;
}
/* Does the data go past the end of the TLV? */
if (tlv_tlen < sizeof(struct lspping_tlv_downstream_map_info_t)) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
}
/* Did we capture enough for this part of the TLV? */
ND_TCHECK2(*tlv_tptr, sizeof(struct lspping_tlv_downstream_map_info_t));
tlv_ptr.lspping_tlv_downstream_map_info= \
(const struct lspping_tlv_downstream_map_info_t *)tlv_tptr;
/* FIXME add hash-key type, depth limit, multipath processing */
tlv_tptr+=sizeof(struct lspping_tlv_downstream_map_info_t);
tlv_tlen-=sizeof(struct lspping_tlv_downstream_map_info_t);
/* FIXME print downstream labels */
tlv_hexdump=TRUE; /* dump the TLV until code complete */
break;
case LSPPING_TLV_BFD_DISCRIMINATOR:
if (tlv_tlen < LSPPING_TLV_BFD_DISCRIMINATOR_LEN) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
} else {
ND_TCHECK2(*tptr, LSPPING_TLV_BFD_DISCRIMINATOR_LEN);
ND_PRINT((ndo, "\n\t BFD Discriminator 0x%08x", EXTRACT_32BITS(tptr)));
}
break;
case LSPPING_TLV_VENDOR_ENTERPRISE:
{
uint32_t vendor_id;
if (tlv_tlen < LSPPING_TLV_VENDOR_ENTERPRISE_LEN) {
ND_PRINT((ndo, "\n\t TLV is too short"));
tlv_hexdump = TRUE;
goto tlv_tooshort;
} else {
ND_TCHECK2(*tptr, LSPPING_TLV_VENDOR_ENTERPRISE_LEN);
vendor_id = EXTRACT_32BITS(tlv_tptr);
ND_PRINT((ndo, "\n\t Vendor: %s (0x%04x)",
tok2str(smi_values, "Unknown", vendor_id),
vendor_id));
}
}
break;
/*
* FIXME those are the defined TLVs that lack a decoder
* you are welcome to contribute code ;-)
*/
case LSPPING_TLV_PAD:
case LSPPING_TLV_ERROR_CODE:
case LSPPING_TLV_VENDOR_PRIVATE:
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tlv_tptr, "\n\t ", tlv_tlen);
break;
}
/* do we want to see an additionally tlv hexdump ? */
tlv_tooshort:
if (ndo->ndo_vflag > 1 || tlv_hexdump==TRUE)
print_unknown_data(ndo, tptr+sizeof(struct lspping_tlv_header), "\n\t ",
lspping_tlv_len);
/* All TLVs are aligned to four octet boundary */
if (lspping_tlv_len % 4) {
lspping_tlv_len += (4 - lspping_tlv_len % 4);
/* Does the TLV, including padding, go past the end of the packet? */
if (tlen < lspping_tlv_len+sizeof(struct lspping_tlv_header))
goto tooshort;
}
tptr+=lspping_tlv_len+sizeof(struct lspping_tlv_header);
tlen-=lspping_tlv_len+sizeof(struct lspping_tlv_header);
}
return;
tooshort:
ND_PRINT((ndo, "\n\t\t packet is too short"));
return;
trunc:
ND_PRINT((ndo, "\n\t\t packet exceeded snapshot"));
return;
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 8
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-125/c/good_2648_2 |
crossvul-cpp_data_bad_4831_0 | ////////////////////////////////////////////////////////////////////////////
// **** WAVPACK **** //
// Hybrid Lossless Wavefile Compressor //
// Copyright (c) 1998 - 2016 David Bryant. //
// All Rights Reserved. //
// Distributed under the BSD Software License (see license.txt) //
////////////////////////////////////////////////////////////////////////////
// open_utils.c
// This module provides all the code required to open an existing WavPack file
// for reading by using a reader callback mechanism (NOT a filename). This
// includes the code required to find and parse WavPack blocks, process any
// included metadata, and queue up the bitstreams containing the encoded audio
// data. It does not the actual code to unpack audio data and this was done so
// that programs that just want to query WavPack files for information (like,
// for example, taggers) don't need to link in a lot of unnecessary code.
#include <stdlib.h>
#include <string.h>
#include "wavpack_local.h"
// This function is identical to WavpackOpenFileInput() except that instead
// of providing a filename to open, the caller provides a pointer to a set of
// reader callbacks and instances of up to two streams. The first of these
// streams is required and contains the regular WavPack data stream; the second
// contains the "correction" file if desired. Unlike the standard open
// function which handles the correction file transparently, in this case it
// is the responsibility of the caller to be aware of correction files.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper);
WavpackContext *WavpackOpenFileInputEx64 (WavpackStreamReader64 *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset)
{
WavpackContext *wpc = malloc (sizeof (WavpackContext));
WavpackStream *wps;
int num_blocks = 0;
unsigned char first_byte;
uint32_t bcount;
if (!wpc) {
if (error) strcpy (error, "can't allocate memory");
return NULL;
}
CLEAR (*wpc);
wpc->wv_in = wv_id;
wpc->wvc_in = wvc_id;
wpc->reader = reader;
wpc->total_samples = -1;
wpc->norm_offset = norm_offset;
wpc->max_streams = OLD_MAX_STREAMS; // use this until overwritten with actual number
wpc->open_flags = flags;
wpc->filelen = wpc->reader->get_length (wpc->wv_in);
#ifndef NO_TAGS
if ((flags & (OPEN_TAGS | OPEN_EDIT_TAGS)) && wpc->reader->can_seek (wpc->wv_in)) {
load_tag (wpc);
wpc->reader->set_pos_abs (wpc->wv_in, 0);
if ((flags & OPEN_EDIT_TAGS) && !editable_tag (&wpc->m_tag)) {
if (error) strcpy (error, "can't edit tags located at the beginning of files!");
return WavpackCloseFile (wpc);
}
}
#endif
if (wpc->reader->read_bytes (wpc->wv_in, &first_byte, 1) != 1) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->reader->push_back_byte (wpc->wv_in, first_byte);
if (first_byte == 'R') {
#ifdef ENABLE_LEGACY
return open_file3 (wpc, error);
#else
if (error) strcpy (error, "this legacy WavPack file is deprecated, use version 4.80.0 to transcode");
return WavpackCloseFile (wpc);
#endif
}
wpc->streams = malloc ((wpc->num_streams = 1) * sizeof (wpc->streams [0]));
if (!wpc->streams) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
wpc->streams [0] = wps = malloc (sizeof (WavpackStream));
if (!wps) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
CLEAR (*wps);
while (!wps->wphdr.block_samples) {
wpc->filepos = wpc->reader->get_pos (wpc->wv_in);
bcount = read_next_header (wpc->reader, wpc->wv_in, &wps->wphdr);
if (bcount == (uint32_t) -1 ||
(!wps->wphdr.block_samples && num_blocks++ > 16)) {
if (error) strcpy (error, "not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wpc->filepos += bcount;
wps->blockbuff = malloc (wps->wphdr.ckSize + 8);
if (!wps->blockbuff) {
if (error) strcpy (error, "can't allocate memory");
return WavpackCloseFile (wpc);
}
memcpy (wps->blockbuff, &wps->wphdr, 32);
if (wpc->reader->read_bytes (wpc->wv_in, wps->blockbuff + 32, wps->wphdr.ckSize - 24) != wps->wphdr.ckSize - 24) {
if (error) strcpy (error, "can't read all of WavPack file!");
return WavpackCloseFile (wpc);
}
// if block does not verify, flag error, free buffer, and continue
if (!WavpackVerifySingleBlock (wps->blockbuff, !(flags & OPEN_NO_CHECKSUM))) {
wps->wphdr.block_samples = 0;
free (wps->blockbuff);
wps->blockbuff = NULL;
wpc->crc_errors++;
continue;
}
wps->init_done = FALSE;
if (wps->wphdr.block_samples) {
if (flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wps->wphdr, 0);
else if (wpc->total_samples == -1) {
if (GET_BLOCK_INDEX (wps->wphdr) || GET_TOTAL_SAMPLES (wps->wphdr) == -1) {
wpc->initial_index = GET_BLOCK_INDEX (wps->wphdr);
SET_BLOCK_INDEX (wps->wphdr, 0);
if (wpc->reader->can_seek (wpc->wv_in)) {
int64_t final_index = -1;
seek_eof_information (wpc, &final_index, FALSE);
if (final_index != -1)
wpc->total_samples = final_index - wpc->initial_index;
}
}
else
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
}
}
else if (wpc->total_samples == -1 && !GET_BLOCK_INDEX (wps->wphdr) && GET_TOTAL_SAMPLES (wps->wphdr))
wpc->total_samples = GET_TOTAL_SAMPLES (wps->wphdr);
if (wpc->wvc_in && wps->wphdr.block_samples && (wps->wphdr.flags & HYBRID_FLAG)) {
unsigned char ch;
if (wpc->reader->read_bytes (wpc->wvc_in, &ch, 1) == 1) {
wpc->reader->push_back_byte (wpc->wvc_in, ch);
wpc->file2len = wpc->reader->get_length (wpc->wvc_in);
wpc->wvc_flag = TRUE;
}
}
if (wpc->wvc_flag && !read_wvc_block (wpc)) {
if (error) strcpy (error, "not compatible with this version of correction file!");
return WavpackCloseFile (wpc);
}
if (!wps->init_done && !unpack_init (wpc)) {
if (error) strcpy (error, wpc->error_message [0] ? wpc->error_message :
"not compatible with this version of WavPack file!");
return WavpackCloseFile (wpc);
}
wps->init_done = TRUE;
}
wpc->config.flags &= ~0xff;
wpc->config.flags |= wps->wphdr.flags & 0xff;
if (!wpc->config.num_channels) {
wpc->config.num_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
wpc->config.channel_mask = 0x5 - wpc->config.num_channels;
}
if ((flags & OPEN_2CH_MAX) && !(wps->wphdr.flags & FINAL_BLOCK))
wpc->reduced_channels = (wps->wphdr.flags & MONO_FLAG) ? 1 : 2;
if (wps->wphdr.flags & DSD_FLAG) {
#ifdef ENABLE_DSD
if (flags & OPEN_DSD_NATIVE) {
wpc->config.bytes_per_sample = 1;
wpc->config.bits_per_sample = 8;
}
else if (flags & OPEN_DSD_AS_PCM) {
wpc->decimation_context = decimate_dsd_init (wpc->reduced_channels ?
wpc->reduced_channels : wpc->config.num_channels);
wpc->config.bytes_per_sample = 3;
wpc->config.bits_per_sample = 24;
}
else {
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
}
#else
if (error) strcpy (error, "not configured to handle DSD WavPack files!");
return WavpackCloseFile (wpc);
#endif
}
else {
wpc->config.bytes_per_sample = (wps->wphdr.flags & BYTES_STORED) + 1;
wpc->config.float_norm_exp = wps->float_norm_exp;
wpc->config.bits_per_sample = (wpc->config.bytes_per_sample * 8) -
((wps->wphdr.flags & SHIFT_MASK) >> SHIFT_LSB);
}
if (!wpc->config.sample_rate) {
if (!wps->wphdr.block_samples || (wps->wphdr.flags & SRATE_MASK) == SRATE_MASK)
wpc->config.sample_rate = 44100;
else
wpc->config.sample_rate = sample_rates [(wps->wphdr.flags & SRATE_MASK) >> SRATE_LSB];
}
return wpc;
}
// This function returns the major version number of the WavPack program
// (or library) that created the open file. Currently, this can be 1 to 5.
// Minor versions are not recorded in WavPack files.
int WavpackGetVersion (WavpackContext *wpc)
{
if (wpc) {
#ifdef ENABLE_LEGACY
if (wpc->stream3)
return get_version3 (wpc);
#endif
return wpc->version_five ? 5 : 4;
}
return 0;
}
// Return the file format specified in the call to WavpackSetFileInformation()
// when the file was created. For all files created prior to WavPack 5.0 this
// will 0 (WP_FORMAT_WAV).
unsigned char WavpackGetFileFormat (WavpackContext *wpc)
{
return wpc->file_format;
}
// Return a string representing the recommended file extension for the open
// WavPack file. For all files created prior to WavPack 5.0 this will be "wav",
// even for raw files with no RIFF into. This string is specified in the
// call to WavpackSetFileInformation() when the file was created.
char *WavpackGetFileExtension (WavpackContext *wpc)
{
if (wpc && wpc->file_extension [0])
return wpc->file_extension;
else
return "wav";
}
// This function initializes everything required to unpack a WavPack block
// and must be called before unpack_samples() is called to obtain audio data.
// It is assumed that the WavpackHeader has been read into the wps->wphdr
// (in the current WavpackStream) and that the entire block has been read at
// wps->blockbuff. If a correction file is available (wpc->wvc_flag = TRUE)
// then the corresponding correction block must be read into wps->block2buff
// and its WavpackHeader has overwritten the header at wps->wphdr. This is
// where all the metadata blocks are scanned including those that contain
// bitstream data.
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr);
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end);
int unpack_init (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
unsigned char *blockptr, *block2ptr;
WavpackMetadata wpmd;
wps->num_terms = 0;
wps->mute_error = FALSE;
wps->crc = wps->crc_x = 0xffffffff;
wps->dsd.ready = 0;
CLEAR (wps->wvbits);
CLEAR (wps->wvcbits);
CLEAR (wps->wvxbits);
CLEAR (wps->decorr_passes);
CLEAR (wps->dc);
CLEAR (wps->w);
if (!(wps->wphdr.flags & MONO_FLAG) && wpc->config.num_channels && wps->wphdr.block_samples &&
(wpc->reduced_channels == 1 || wpc->config.num_channels == 1)) {
wps->mute_error = TRUE;
return FALSE;
}
if ((wps->wphdr.flags & UNKNOWN_FLAGS) || (wps->wphdr.flags & MONO_DATA) == MONO_DATA) {
wps->mute_error = TRUE;
return FALSE;
}
blockptr = wps->blockbuff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->blockbuff, &blockptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && wpc->wvc_flag && wps->block2buff) {
block2ptr = wps->block2buff + sizeof (WavpackHeader);
while (read_metadata_buff (&wpmd, wps->block2buff, &block2ptr))
if (!process_metadata (wpc, &wpmd)) {
wps->mute_error = TRUE;
return FALSE;
}
}
if (wps->wphdr.block_samples && ((wps->wphdr.flags & DSD_FLAG) ? !wps->dsd.ready : !bs_is_open (&wps->wvbits))) {
if (bs_is_open (&wps->wvcbits))
strcpy (wpc->error_message, "can't unpack correction files alone!");
wps->mute_error = TRUE;
return FALSE;
}
if (wps->wphdr.block_samples && !bs_is_open (&wps->wvxbits)) {
if ((wps->wphdr.flags & INT32_DATA) && wps->int32_sent_bits)
wpc->lossy_blocks = TRUE;
if ((wps->wphdr.flags & FLOAT_DATA) &&
wps->float_flags & (FLOAT_EXCEPTIONS | FLOAT_ZEROS_SENT | FLOAT_SHIFT_SENT | FLOAT_SHIFT_SAME))
wpc->lossy_blocks = TRUE;
}
if (wps->wphdr.block_samples)
wps->sample_index = GET_BLOCK_INDEX (wps->wphdr);
return TRUE;
}
//////////////////////////////// matadata handlers ///////////////////////////////
// These functions handle specific metadata types and are called directly
// during WavPack block parsing by process_metadata() at the bottom.
// This function initialzes the main bitstream for audio samples, which must
// be in the "wv" file.
static int init_wv_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initialzes the "correction" bitstream for audio samples,
// which currently must be in the "wvc" file.
static int init_wvc_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
if (!wpmd->byte_length || (wpmd->byte_length & 1))
return FALSE;
bs_open_read (&wps->wvcbits, wpmd->data, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// This function initialzes the "extra" bitstream for audio samples which
// contains the information required to losslessly decompress 32-bit float data
// or integer data that exceeds 24 bits. This bitstream is in the "wv" file
// for pure lossless data or the "wvc" file for hybrid lossless. This data
// would not be used for hybrid lossy mode. There is also a 32-bit CRC stored
// in the first 4 bytes of these blocks.
static int init_wvx_bitstream (WavpackStream *wps, WavpackMetadata *wpmd)
{
unsigned char *cp = wpmd->data;
if (wpmd->byte_length <= 4 || (wpmd->byte_length & 1))
return FALSE;
wps->crc_wvx = *cp++;
wps->crc_wvx |= (int32_t) *cp++ << 8;
wps->crc_wvx |= (int32_t) *cp++ << 16;
wps->crc_wvx |= (int32_t) *cp++ << 24;
bs_open_read (&wps->wvxbits, cp, (unsigned char *) wpmd->data + wpmd->byte_length);
return TRUE;
}
// Read the int32 data from the specified metadata into the specified stream.
// This data is used for integer data that has more than 24 bits of magnitude
// or, in some cases, used to eliminate redundant bits from any audio stream.
static int read_int32_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->int32_sent_bits = *byteptr++;
wps->int32_zeros = *byteptr++;
wps->int32_ones = *byteptr++;
wps->int32_dups = *byteptr;
return TRUE;
}
static int read_float_info (WavpackStream *wps, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
char *byteptr = wpmd->data;
if (bytecnt != 4)
return FALSE;
wps->float_flags = *byteptr++;
wps->float_shift = *byteptr++;
wps->float_max_exp = *byteptr++;
wps->float_norm_exp = *byteptr;
return TRUE;
}
// Read multichannel information from metadata. The first byte is the total
// number of channels and the following bytes represent the channel_mask
// as described for Microsoft WAVEFORMATEX.
static int read_channel_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length, shift = 0, mask_bits;
unsigned char *byteptr = wpmd->data;
uint32_t mask = 0;
if (!bytecnt || bytecnt > 7)
return FALSE;
if (!wpc->config.num_channels) {
// if bytecnt is 6 or 7 we are using new configuration with "unlimited" streams
if (bytecnt >= 6) {
wpc->config.num_channels = (byteptr [0] | ((byteptr [2] & 0xf) << 8)) + 1;
wpc->max_streams = (byteptr [1] | ((byteptr [2] & 0xf0) << 4)) + 1;
if (wpc->config.num_channels < wpc->max_streams)
return FALSE;
byteptr += 3;
mask = *byteptr++;
mask |= (uint32_t) *byteptr++ << 8;
mask |= (uint32_t) *byteptr++ << 16;
if (bytecnt == 7) // this was introduced in 5.0
mask |= (uint32_t) *byteptr << 24;
}
else {
wpc->config.num_channels = *byteptr++;
while (--bytecnt) {
mask |= (uint32_t) *byteptr++ << shift;
shift += 8;
}
}
if (wpc->config.num_channels > wpc->max_streams * 2)
return FALSE;
wpc->config.channel_mask = mask;
for (mask_bits = 0; mask; mask >>= 1)
if ((mask & 1) && ++mask_bits > wpc->config.num_channels)
return FALSE;
}
return TRUE;
}
// Read multichannel identity information from metadata. Data is an array of
// unsigned characters representing any channels in the file that DO NOT
// match one the 18 Microsoft standard channels (and are represented in the
// channel mask). A value of 0 is not allowed and 0xff means an unknown or
// undefined channel identity.
static int read_channel_identities (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if (!wpc->channel_identities) {
wpc->channel_identities = malloc (wpmd->byte_length + 1);
memcpy (wpc->channel_identities, wpmd->data, wpmd->byte_length);
wpc->channel_identities [wpmd->byte_length] = 0;
}
return TRUE;
}
// Read configuration information from metadata.
static int read_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
if (bytecnt >= 3) {
wpc->config.flags &= 0xff;
wpc->config.flags |= (int32_t) *byteptr++ << 8;
wpc->config.flags |= (int32_t) *byteptr++ << 16;
wpc->config.flags |= (int32_t) *byteptr++ << 24;
bytecnt -= 3;
if (bytecnt && (wpc->config.flags & CONFIG_EXTRA_MODE)) {
wpc->config.xmode = *byteptr++;
bytecnt--;
}
// we used an extra config byte here for the 5.0.0 alpha, so still
// honor it now (but this has been replaced with NEW_CONFIG)
if (bytecnt) {
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr;
wpc->version_five = 1;
}
}
return TRUE;
}
// Read "new" configuration information from metadata.
static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
wpc->version_five = 1; // just having this block signals version 5.0
wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;
if (wpc->channel_reordering) {
free (wpc->channel_reordering);
wpc->channel_reordering = NULL;
}
// if there's any data, the first two bytes are file_format and qmode flags
if (bytecnt) {
wpc->file_format = *byteptr++;
wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
bytecnt -= 2;
// another byte indicates a channel layout
if (bytecnt) {
int nchans, i;
wpc->channel_layout = (int32_t) *byteptr++ << 16;
bytecnt--;
// another byte means we have a channel count for the layout and maybe a reordering
if (bytecnt) {
wpc->channel_layout += nchans = *byteptr++;
bytecnt--;
// any more means there's a reordering string
if (bytecnt) {
if (bytecnt > nchans)
return FALSE;
wpc->channel_reordering = malloc (nchans);
// note that redundant reordering info is not stored, so we fill in the rest
if (wpc->channel_reordering) {
for (i = 0; i < nchans; ++i)
if (bytecnt) {
wpc->channel_reordering [i] = *byteptr++;
bytecnt--;
}
else
wpc->channel_reordering [i] = i;
}
}
}
else
wpc->channel_layout += wpc->config.num_channels;
}
}
return TRUE;
}
// Read non-standard sampling rate from metadata.
static int read_sample_rate (WavpackContext *wpc, WavpackMetadata *wpmd)
{
int bytecnt = wpmd->byte_length;
unsigned char *byteptr = wpmd->data;
if (bytecnt == 3 || bytecnt == 4) {
wpc->config.sample_rate = (int32_t) *byteptr++;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 8;
wpc->config.sample_rate |= (int32_t) *byteptr++ << 16;
// for sampling rates > 16777215 (non-audio probably, or ...)
if (bytecnt == 4)
wpc->config.sample_rate |= (int32_t) (*byteptr & 0x7f) << 24;
}
return TRUE;
}
// Read wrapper data from metadata. Currently, this consists of the RIFF
// header and trailer that wav files contain around the audio data but could
// be used for other formats as well. Because WavPack files contain all the
// information required for decoding and playback, this data can probably
// be ignored except when an exact wavefile restoration is needed.
static int read_wrapper_data (WavpackContext *wpc, WavpackMetadata *wpmd)
{
if ((wpc->open_flags & OPEN_WRAPPER) && wpc->wrapper_bytes < MAX_WRAPPER_BYTES && wpmd->byte_length) {
wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + wpmd->byte_length);
if (!wpc->wrapper_data)
return FALSE;
memcpy (wpc->wrapper_data + wpc->wrapper_bytes, wpmd->data, wpmd->byte_length);
wpc->wrapper_bytes += wpmd->byte_length;
}
return TRUE;
}
static int read_metadata_buff (WavpackMetadata *wpmd, unsigned char *blockbuff, unsigned char **buffptr)
{
WavpackHeader *wphdr = (WavpackHeader *) blockbuff;
unsigned char *buffend = blockbuff + wphdr->ckSize + 8;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->id = *(*buffptr)++;
wpmd->byte_length = *(*buffptr)++ << 1;
if (wpmd->id & ID_LARGE) {
wpmd->id &= ~ID_LARGE;
if (buffend - *buffptr < 2)
return FALSE;
wpmd->byte_length += *(*buffptr)++ << 9;
wpmd->byte_length += *(*buffptr)++ << 17;
}
if (wpmd->id & ID_ODD_SIZE) {
if (!wpmd->byte_length) // odd size and zero length makes no sense
return FALSE;
wpmd->id &= ~ID_ODD_SIZE;
wpmd->byte_length--;
}
if (wpmd->byte_length) {
if (buffend - *buffptr < wpmd->byte_length + (wpmd->byte_length & 1)) {
wpmd->data = NULL;
return FALSE;
}
wpmd->data = *buffptr;
(*buffptr) += wpmd->byte_length + (wpmd->byte_length & 1);
}
else
wpmd->data = NULL;
return TRUE;
}
static int process_metadata (WavpackContext *wpc, WavpackMetadata *wpmd)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
switch (wpmd->id) {
case ID_DUMMY:
return TRUE;
case ID_DECORR_TERMS:
return read_decorr_terms (wps, wpmd);
case ID_DECORR_WEIGHTS:
return read_decorr_weights (wps, wpmd);
case ID_DECORR_SAMPLES:
return read_decorr_samples (wps, wpmd);
case ID_ENTROPY_VARS:
return read_entropy_vars (wps, wpmd);
case ID_HYBRID_PROFILE:
return read_hybrid_profile (wps, wpmd);
case ID_SHAPING_WEIGHTS:
return read_shaping_info (wps, wpmd);
case ID_FLOAT_INFO:
return read_float_info (wps, wpmd);
case ID_INT32_INFO:
return read_int32_info (wps, wpmd);
case ID_CHANNEL_INFO:
return read_channel_info (wpc, wpmd);
case ID_CHANNEL_IDENTITIES:
return read_channel_identities (wpc, wpmd);
case ID_CONFIG_BLOCK:
return read_config_info (wpc, wpmd);
case ID_NEW_CONFIG_BLOCK:
return read_new_config_info (wpc, wpmd);
case ID_SAMPLE_RATE:
return read_sample_rate (wpc, wpmd);
case ID_WV_BITSTREAM:
return init_wv_bitstream (wps, wpmd);
case ID_WVC_BITSTREAM:
return init_wvc_bitstream (wps, wpmd);
case ID_WVX_BITSTREAM:
return init_wvx_bitstream (wps, wpmd);
case ID_DSD_BLOCK:
#ifdef ENABLE_DSD
return init_dsd_block (wpc, wpmd);
#else
strcpy (wpc->error_message, "not configured to handle DSD WavPack files!");
return FALSE;
#endif
case ID_ALT_HEADER: case ID_ALT_TRAILER:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_RIFF_HEADER: case ID_RIFF_TRAILER:
return read_wrapper_data (wpc, wpmd);
case ID_ALT_MD5_CHECKSUM:
if (!(wpc->open_flags & OPEN_ALT_TYPES))
return TRUE;
case ID_MD5_CHECKSUM:
if (wpmd->byte_length == 16) {
memcpy (wpc->config.md5_checksum, wpmd->data, 16);
wpc->config.flags |= CONFIG_MD5_CHECKSUM;
wpc->config.md5_read = 1;
}
return TRUE;
case ID_ALT_EXTENSION:
if (wpmd->byte_length && wpmd->byte_length < sizeof (wpc->file_extension)) {
memcpy (wpc->file_extension, wpmd->data, wpmd->byte_length);
wpc->file_extension [wpmd->byte_length] = 0;
}
return TRUE;
// we don't actually verify the checksum here (it's done right after the
// block is read), but it's a good indicator of version 5 files
case ID_BLOCK_CHECKSUM:
wpc->version_five = 1;
return TRUE;
default:
return (wpmd->id & ID_OPTIONAL_DATA) ? TRUE : FALSE;
}
}
//////////////////////////////// bitstream management ///////////////////////////////
// Open the specified BitStream and associate with the specified buffer.
static void bs_read (Bitstream *bs);
static void bs_open_read (Bitstream *bs, void *buffer_start, void *buffer_end)
{
bs->error = bs->sr = bs->bc = 0;
bs->ptr = (bs->buf = buffer_start) - 1;
bs->end = buffer_end;
bs->wrap = bs_read;
}
// This function is only called from the getbit() and getbits() macros when
// the BitStream has been exhausted and more data is required. Sinve these
// bistreams no longer access files, this function simple sets an error and
// resets the buffer.
static void bs_read (Bitstream *bs)
{
bs->ptr = bs->buf;
bs->error = 1;
}
// This function is called to close the bitstream. It returns the number of
// full bytes actually read as bits.
uint32_t bs_close_read (Bitstream *bs)
{
uint32_t bytes_read;
if (bs->bc < sizeof (*(bs->ptr)) * 8)
bs->ptr++;
bytes_read = (uint32_t)(bs->ptr - bs->buf) * sizeof (*(bs->ptr));
if (!(bytes_read & 1))
++bytes_read;
CLEAR (*bs);
return bytes_read;
}
// Normally the trailing wrapper will not be available when a WavPack file is first
// opened for reading because it is stored in the final block of the file. This
// function forces a seek to the end of the file to pick up any trailing wrapper
// stored there (then use WavPackGetWrapper**() to obtain). This can obviously only
// be used for seekable files (not pipes) and is not available for pre-4.0 WavPack
// files.
void WavpackSeekTrailingWrapper (WavpackContext *wpc)
{
if ((wpc->open_flags & OPEN_WRAPPER) &&
wpc->reader->can_seek (wpc->wv_in) && !wpc->stream3)
seek_eof_information (wpc, NULL, TRUE);
}
// Get any MD5 checksum stored in the metadata (should be called after reading
// last sample or an extra seek will occur). A return value of FALSE indicates
// that no MD5 checksum was stored.
int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16])
{
if (wpc->config.flags & CONFIG_MD5_CHECKSUM) {
if (!wpc->config.md5_read && wpc->reader->can_seek (wpc->wv_in))
seek_eof_information (wpc, NULL, FALSE);
if (wpc->config.md5_read) {
memcpy (data, wpc->config.md5_checksum, 16);
return TRUE;
}
}
return FALSE;
}
// Read from current file position until a valid 32-byte WavPack 4.0 header is
// found and read into the specified pointer. The number of bytes skipped is
// returned. If no WavPack header is found within 1 meg, then a -1 is returned
// to indicate the error. No additional bytes are read past the header and it
// is returned in the processor's native endian mode. Seeking is not required.
uint32_t read_next_header (WavpackStreamReader64 *reader, void *id, WavpackHeader *wphdr)
{
unsigned char buffer [sizeof (*wphdr)], *sp = buffer + sizeof (*wphdr), *ep = sp;
uint32_t bytes_skipped = 0;
int bleft;
while (1) {
if (sp < ep) {
bleft = (int)(ep - sp);
memmove (buffer, sp, bleft);
}
else
bleft = 0;
if (reader->read_bytes (id, buffer + bleft, sizeof (*wphdr) - bleft) != sizeof (*wphdr) - bleft)
return -1;
sp = buffer;
if (*sp++ == 'w' && *sp == 'v' && *++sp == 'p' && *++sp == 'k' &&
!(*++sp & 1) && sp [2] < 16 && !sp [3] && (sp [2] || sp [1] || *sp >= 24) && sp [5] == 4 &&
sp [4] >= (MIN_STREAM_VERS & 0xff) && sp [4] <= (MAX_STREAM_VERS & 0xff) && sp [18] < 3 && !sp [19]) {
memcpy (wphdr, buffer, sizeof (*wphdr));
WavpackLittleEndianToNative (wphdr, WavpackHeaderFormat);
return bytes_skipped;
}
while (sp < ep && *sp != 'w')
sp++;
if ((bytes_skipped += (uint32_t)(sp - buffer)) > 1024 * 1024)
return -1;
}
}
// Compare the regular wv file block header to a potential matching wvc
// file block header and return action code based on analysis:
//
// 0 = use wvc block (assuming rest of block is readable)
// 1 = bad match; try to read next wvc block
// -1 = bad match; ignore wvc file for this block and backup fp (if
// possible) and try to use this block next time
static int match_wvc_header (WavpackHeader *wv_hdr, WavpackHeader *wvc_hdr)
{
if (GET_BLOCK_INDEX (*wv_hdr) == GET_BLOCK_INDEX (*wvc_hdr) &&
wv_hdr->block_samples == wvc_hdr->block_samples) {
int wvi = 0, wvci = 0;
if (wv_hdr->flags == wvc_hdr->flags)
return 0;
if (wv_hdr->flags & INITIAL_BLOCK)
wvi -= 1;
if (wv_hdr->flags & FINAL_BLOCK)
wvi += 1;
if (wvc_hdr->flags & INITIAL_BLOCK)
wvci -= 1;
if (wvc_hdr->flags & FINAL_BLOCK)
wvci += 1;
return (wvci - wvi < 0) ? 1 : -1;
}
if (((GET_BLOCK_INDEX (*wvc_hdr) - GET_BLOCK_INDEX (*wv_hdr)) << 24) < 0)
return 1;
else
return -1;
}
// Read the wvc block that matches the regular wv block that has been
// read for the current stream. If an exact match is not found then
// we either keep reading or back up and (possibly) use the block
// later. The skip_wvc flag is set if not matching wvc block is found
// so that we can still decode using only the lossy version (although
// we flag this as an error). A return of FALSE indicates a serious
// error (not just that we missed one wvc block).
int read_wvc_block (WavpackContext *wpc)
{
WavpackStream *wps = wpc->streams [wpc->current_stream];
int64_t bcount, file2pos;
WavpackHeader orig_wphdr;
WavpackHeader wphdr;
int compare_result;
while (1) {
file2pos = wpc->reader->get_pos (wpc->wvc_in);
bcount = read_next_header (wpc->reader, wpc->wvc_in, &wphdr);
if (bcount == (uint32_t) -1) {
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (&orig_wphdr, &wphdr, 32); // save original header for verify step
if (wpc->open_flags & OPEN_STREAMING)
SET_BLOCK_INDEX (wphdr, wps->sample_index = 0);
else
SET_BLOCK_INDEX (wphdr, GET_BLOCK_INDEX (wphdr) - wpc->initial_index);
if (wphdr.flags & INITIAL_BLOCK)
wpc->file2pos = file2pos + bcount;
compare_result = match_wvc_header (&wps->wphdr, &wphdr);
if (!compare_result) {
wps->block2buff = malloc (wphdr.ckSize + 8);
if (!wps->block2buff)
return FALSE;
if (wpc->reader->read_bytes (wpc->wvc_in, wps->block2buff + 32, wphdr.ckSize - 24) !=
wphdr.ckSize - 24) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return FALSE;
}
memcpy (wps->block2buff, &orig_wphdr, 32);
// don't use corrupt blocks
if (!WavpackVerifySingleBlock (wps->block2buff, !(wpc->open_flags & OPEN_NO_CHECKSUM))) {
free (wps->block2buff);
wps->block2buff = NULL;
wps->wvc_skip = TRUE;
wpc->crc_errors++;
return TRUE;
}
wps->wvc_skip = FALSE;
memcpy (wps->block2buff, &wphdr, 32);
memcpy (&wps->wphdr, &wphdr, 32);
return TRUE;
}
else if (compare_result == -1) {
wps->wvc_skip = TRUE;
wpc->reader->set_pos_rel (wpc->wvc_in, -32, SEEK_CUR);
wpc->crc_errors++;
return TRUE;
}
}
}
// This function is used to seek to end of a file to obtain certain information
// that is stored there at the file creation time because it is not known at
// the start. This includes the MD5 sum and and trailing part of the file
// wrapper, and in some rare cases may include the total number of samples in
// the file (although we usually try to back up and write that at the front of
// the file). Note this function restores the file position to its original
// location (and obviously requires a seekable file). The normal return value
// is TRUE indicating no errors, although this does not actually mean that any
// information was retrieved. An error return of FALSE usually means the file
// terminated unexpectedly. Note that this could be used to get all three
// types of information in one go, but it's not actually used that way now.
static int seek_eof_information (WavpackContext *wpc, int64_t *final_index, int get_wrapper)
{
int64_t restore_pos, last_pos = -1;
WavpackStreamReader64 *reader = wpc->reader;
int alt_types = wpc->open_flags & OPEN_ALT_TYPES;
uint32_t blocks = 0, audio_blocks = 0;
void *id = wpc->wv_in;
WavpackHeader wphdr;
restore_pos = reader->get_pos (id); // we restore file position when done
// start 1MB from the end-of-file, or from the start if the file is not that big
if (reader->get_length (id) > 1048576LL)
reader->set_pos_rel (id, -1048576, SEEK_END);
else
reader->set_pos_abs (id, 0);
// Note that we go backward (without parsing inside blocks) until we find a block
// with audio (careful to not get stuck in a loop). Only then do we go forward
// parsing all blocks in their entirety.
while (1) {
uint32_t bcount = read_next_header (reader, id, &wphdr);
int64_t current_pos = reader->get_pos (id);
// if we just got to the same place as last time, we're stuck and need to give up
if (current_pos == last_pos) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
last_pos = current_pos;
// We enter here if we just read 1 MB without seeing any WavPack block headers.
// Since WavPack blocks are < 1 MB, that means we're in a big APE tag, or we got
// to the end-of-file.
if (bcount == (uint32_t) -1) {
// if we have not seen any blocks at all yet, back up almost 2 MB (or to the
// beginning of the file) and try again
if (!blocks) {
if (current_pos > 2000000LL)
reader->set_pos_rel (id, -2000000, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// if we have seen WavPack blocks, then this means we've done all we can do here
reader->set_pos_abs (id, restore_pos);
return TRUE;
}
blocks++;
// If the block has audio samples, calculate a final index, although this is not
// final since this may not be the last block with audio. On the other hand, if
// this block does not have audio, and we haven't seen one with audio, we have
// to go back some more.
if (wphdr.block_samples) {
if (final_index)
*final_index = GET_BLOCK_INDEX (wphdr) + wphdr.block_samples;
audio_blocks++;
}
else if (!audio_blocks) {
if (current_pos > 1048576LL)
reader->set_pos_rel (id, -1048576, SEEK_CUR);
else
reader->set_pos_abs (id, 0);
continue;
}
// at this point we have seen at least one block with audio, so we parse the
// entire block looking for MD5 metadata or (conditionally) trailing wrappers
bcount = wphdr.ckSize - sizeof (WavpackHeader) + 8;
while (bcount >= 2) {
unsigned char meta_id, c1, c2;
uint32_t meta_bc, meta_size;
if (reader->read_bytes (id, &meta_id, 1) != 1 ||
reader->read_bytes (id, &c1, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2 || reader->read_bytes (id, &c1, 1) != 1 ||
reader->read_bytes (id, &c2, 1) != 1) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
meta_size = (meta_id & ID_ODD_SIZE) ? meta_bc - 1 : meta_bc;
meta_id &= ID_UNIQUE;
if (get_wrapper && (meta_id == ID_RIFF_TRAILER || (alt_types && meta_id == ID_ALT_TRAILER)) && meta_bc) {
wpc->wrapper_data = realloc (wpc->wrapper_data, wpc->wrapper_bytes + meta_bc);
if (!wpc->wrapper_data) {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
if (reader->read_bytes (id, wpc->wrapper_data + wpc->wrapper_bytes, meta_bc) == meta_bc)
wpc->wrapper_bytes += meta_size;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else if (meta_id == ID_MD5_CHECKSUM || (alt_types && meta_id == ID_ALT_MD5_CHECKSUM)) {
if (meta_bc == 16 && bcount >= 16) {
if (reader->read_bytes (id, wpc->config.md5_checksum, 16) == 16)
wpc->config.md5_read = TRUE;
else {
reader->set_pos_abs (id, restore_pos);
return FALSE;
}
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
}
else
reader->set_pos_rel (id, meta_bc, SEEK_CUR);
bcount -= meta_bc;
}
}
}
// Quickly verify the referenced block. It is assumed that the WavPack header has been converted
// to native endian format. If a block checksum is performed, that is done in little-endian
// (file) format. It is also assumed that the caller has made sure that the block length
// indicated in the header is correct (we won't overflow the buffer). If a checksum is present,
// then it is checked, otherwise we just check that all the metadata blocks are formatted
// correctly (without looking at their contents). Returns FALSE for bad block.
int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum)
{
WavpackHeader *wphdr = (WavpackHeader *) buffer;
uint32_t checksum_passed = 0, bcount, meta_bc;
unsigned char *dp, meta_id, c1, c2;
if (strncmp (wphdr->ckID, "wvpk", 4) || wphdr->ckSize + 8 < sizeof (WavpackHeader))
return FALSE;
bcount = wphdr->ckSize - sizeof (WavpackHeader) + 8;
dp = (unsigned char *)(wphdr + 1);
while (bcount >= 2) {
meta_id = *dp++;
c1 = *dp++;
meta_bc = c1 << 1;
bcount -= 2;
if (meta_id & ID_LARGE) {
if (bcount < 2)
return FALSE;
c1 = *dp++;
c2 = *dp++;
meta_bc += ((uint32_t) c1 << 9) + ((uint32_t) c2 << 17);
bcount -= 2;
}
if (bcount < meta_bc)
return FALSE;
if (verify_checksum && (meta_id & ID_UNIQUE) == ID_BLOCK_CHECKSUM) {
#ifdef BITSTREAM_SHORTS
uint16_t *csptr = (uint16_t*) buffer;
#else
unsigned char *csptr = buffer;
#endif
int wcount = (int)(dp - 2 - buffer) >> 1;
uint32_t csum = (uint32_t) -1;
if ((meta_id & ID_ODD_SIZE) || meta_bc < 2 || meta_bc > 4)
return FALSE;
#ifdef BITSTREAM_SHORTS
while (wcount--)
csum = (csum * 3) + *csptr++;
#else
WavpackNativeToLittleEndian ((WavpackHeader *) buffer, WavpackHeaderFormat);
while (wcount--) {
csum = (csum * 3) + csptr [0] + (csptr [1] << 8);
csptr += 2;
}
WavpackLittleEndianToNative ((WavpackHeader *) buffer, WavpackHeaderFormat);
#endif
if (meta_bc == 4) {
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff) || *dp++ != ((csum >> 16) & 0xff) || *dp++ != ((csum >> 24) & 0xff))
return FALSE;
}
else {
csum ^= csum >> 16;
if (*dp++ != (csum & 0xff) || *dp++ != ((csum >> 8) & 0xff))
return FALSE;
}
checksum_passed++;
}
bcount -= meta_bc;
dp += meta_bc;
}
return (bcount == 0) && (!verify_checksum || !(wphdr->flags & HAS_CHECKSUM) || checksum_passed);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4831_0 |
crossvul-cpp_data_bad_451_0 | /*
** The Sleuth Kit
**
** This software is subject to the IBM Public License ver. 1.0,
** which was displayed prior to download and is included in the readme.txt
** file accompanying the Sleuth Kit files. It may also be requested from:
** Crucial Security Inc.
** 14900 Conference Center Drive
** Chantilly, VA 20151
**
** Copyright (c) 2009 Brian Carrier. All rights reserved.
**
** Judson Powers [jpowers@atc-nycorp.com]
** Matt Stillerman [matt@atc-nycorp.com]
** Rob Joyce [rob@atc-nycorp.com]
** Copyright (c) 2008, 2012 ATC-NY. All rights reserved.
** This file contains data developed with support from the National
** Institute of Justice, Office of Justice Programs, U.S. Department of Justice.
**
** Wyatt Banks [wbanks@crucialsecurity.com]
** Copyright (c) 2005 Crucial Security Inc. All rights reserved.
**
** Brian Carrier [carrier@sleuthkit.org]
** Copyright (c) 2003-2005 Brian Carrier. All rights reserved
**
** Copyright (c) 1997,1998,1999, International Business Machines
** Corporation and others. All Rights Reserved.
*/
/* 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
--*/
/*
** You may distribute the Sleuth Kit, or other software that incorporates
** part of all of the Sleuth Kit, in object code form under a license agreement,
** provided that:
** a) you comply with the terms and conditions of the IBM Public License
** ver 1.0; and
** b) the license agreement
** i) effectively disclaims on behalf of all Contributors all warranties
** and conditions, express and implied, including warranties or
** conditions of title and non-infringement, and implied warranties
** or conditions of merchantability and fitness for a particular
** purpose.
** ii) effectively excludes on behalf of all Contributors liability for
** damages, including direct, indirect, special, incidental and
** consequential damages such as lost profits.
** iii) states that any provisions which differ from IBM Public License
** ver. 1.0 are offered by that Contributor alone and not by any
** other party; and
** iv) states that the source code for the program is available from you,
** and informs licensees how to obtain it in a reasonable manner on or
** through a medium customarily used for software exchange.
**
** When the Sleuth Kit or other software that incorporates part or all of
** the Sleuth Kit is made available in source code form:
** a) it must be made available under IBM Public License ver. 1.0; and
** b) a copy of the IBM Public License ver. 1.0 must be included with
** each copy of the program.
*/
/** \file hfs.c
* Contains the general internal TSK HFS metadata and data unit code
*/
#include "tsk_fs_i.h"
#include "tsk_hfs.h"
#include <stdarg.h>
#ifdef TSK_WIN32
#include <string.h>
#else
#include <strings.h>
#endif
#define XSWAP(a,b) { a ^= b; b ^= a; a ^= b; }
// Compression Stuff
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "lzvn.h"
// Forward declarations:
static uint8_t hfs_load_attrs(TSK_FS_FILE * fs_file);
static uint8_t hfs_load_extended_attrs(TSK_FS_FILE * file,
unsigned char *isCompressed, unsigned char *cmpType,
uint64_t * uncSize);
void error_detected(uint32_t errnum, char *errstr, ...);
void error_returned(char *errstr, ...);
#ifdef HAVE_LIBZ
/***************** ZLIB stuff *******************************/
// Adapted from zpipe.c (part of zlib) at http://zlib.net/zpipe.c
#define CHUNK 16384
/*
* Invokes the zlib library to inflate (uncompress) data.
*
* Returns and error code. Places the uncompressed data in a buffer supplied by the caller. Also
* returns the uncompressed length, and the number of compressed bytes consumed.
*
* Will stop short of the end of compressed data, if a natural end of a compression unit is reached. Using
* bytesConsumed, the caller can then advance the source pointer, and re-invoke the function. This will then
* inflate the next following compression unit in the data stream.
*
* @param source - buffer of compressed data
* @param sourceLen - length of the compressed data.
* @param dest -- buffer to hold the uncompressed results
* @param destLen -- length of the dest buffer
* @param uncompressedLength -- return of the length of the uncompressed data found.
* @param bytesConsumed -- return of the number of input bytes of compressed data used.
* @return 0 on success, a negative number on error
*/
static int
zlib_inflate(char *source, uint64_t sourceLen, char *dest, uint64_t destLen, uint64_t * uncompressedLength, unsigned long *bytesConsumed) // this is unsigned long because that's what zlib uses.
{
int ret;
unsigned have;
z_stream strm;
unsigned char in[CHUNK];
unsigned char out[CHUNK];
// Some vars to help with copying bytes into "in"
char *srcPtr = source;
char *destPtr = dest;
uint64_t srcAvail = sourceLen; //uint64_t
uint64_t amtToCopy;
uint64_t copiedSoFar = 0;
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK) {
error_detected(TSK_ERR_FS_READ,
"zlib_inflate: failed to initialize inflation engine (%d)",
ret);
return ret;
}
/* decompress until deflate stream ends or end of file */
do {
// Copy up to CHUNK bytes into "in" from source, advancing the pointer, and
// setting strm.avail_in equal to the number of bytes copied.
if (srcAvail >= CHUNK) {
amtToCopy = CHUNK;
srcAvail -= CHUNK;
}
else {
amtToCopy = srcAvail;
srcAvail = 0;
}
// wipe out any previous value, copy in the bytes, advance the pointer, record number of bytes.
memset(in, 0, CHUNK);
if (amtToCopy > SIZE_MAX || amtToCopy > UINT_MAX) {
error_detected(TSK_ERR_FS_READ,
"zlib_inflate: amtToCopy in one chunk is too large");
return -100;
}
memcpy(in, srcPtr, (size_t) amtToCopy); // cast OK because of above test
srcPtr += amtToCopy;
strm.avail_in = (uInt) amtToCopy; // cast OK because of above test
if (strm.avail_in == 0)
break;
strm.next_in = in;
/* run inflate() on input until output buffer not full */
do {
strm.avail_out = CHUNK;
strm.next_out = out;
ret = inflate(&strm, Z_NO_FLUSH);
if (ret == Z_NEED_DICT)
ret = Z_DATA_ERROR; // we don't have a custom dict
if (ret < 0 && ret != Z_BUF_ERROR) { // Z_BUF_ERROR is not fatal
error_detected(TSK_ERR_FS_READ,
" zlib_inflate: zlib returned error %d (%s)", ret,
strm.msg);
(void) inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
// Is there enough space in dest to copy the current chunk?
if (copiedSoFar + have > destLen) {
// There is not enough space, so better return an error
error_detected(TSK_ERR_FS_READ,
" zlib_inflate: not enough space in inflation destination\n");
(void) inflateEnd(&strm);
return -200;
}
// Copy "have" bytes from out to destPtr, advance destPtr
memcpy(destPtr, out, have);
destPtr += have;
copiedSoFar += have;
} while ((strm.avail_out == 0) && (ret != Z_STREAM_END));
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
if (ret == Z_STREAM_END)
*uncompressedLength = copiedSoFar;
*bytesConsumed = strm.total_in;
/* clean up and return */
(void) inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
#endif
/* may set error up to string 1
* returns 0 on success, 1 on failure */
uint8_t
hfs_checked_read_random(TSK_FS_INFO * fs, char *buf, size_t len,
TSK_OFF_T offs)
{
ssize_t r;
r = tsk_fs_read(fs, offs, buf, len);
if (r != (ssize_t) len) {
if (r >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
return 1;
}
return 0;
}
/**********************************************************************
*
* MISC FUNCS
*
**********************************************************************/
/* convert the HFS Time (seconds from 1/1/1904)
* to UNIX (UTC seconds from 1/1/1970)
* The number is borrowed from linux HFS driver source
*/
uint32_t
hfs_convert_2_unix_time(uint32_t hfsdate)
{
if (hfsdate < NSEC_BTWN_1904_1970)
return 0;
return (uint32_t) (hfsdate - NSEC_BTWN_1904_1970);
}
/**
* Convert a cnid (metadata address) to big endian array.
* This is used to create the key for tree lookups.
* @param cnid Metadata address to convert
* @param array [out] Array to write data into.
*/
static void
cnid_to_array(uint32_t cnid, uint8_t array[4])
{
array[3] = (cnid >> 0) & 0xff;
array[2] = (cnid >> 8) & 0xff;
array[1] = (cnid >> 16) & 0xff;
array[0] = (cnid >> 24) & 0xff;
}
/**********************************************************************
*
* Lookup Functions
*
**********************************************************************/
/* Compares the given HFS+ Extents B-tree key to key constructed
* for finding the beginning of the data fork extents for the given
* CNID. (That is, the search key uses the given CNID and has
* fork = 0 and start_block = 0.)
*/
static int
hfs_ext_compare_keys(HFS_INFO * hfs, uint32_t cnid,
const hfs_btree_key_ext * key)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint32_t key_cnid;
key_cnid = tsk_getu32(fs->endian, key->file_id);
if (key_cnid < cnid)
return -1;
if (key_cnid > cnid)
return 1;
/* referring to the same cnids */
/* we are always looking for the data fork */
if (key->fork_type != HFS_EXT_KEY_TYPE_DATA)
return 1;
/* we are always looking for a start_block of zero
(interested in the beginning of the extents, regardless
of what the start_block is); all files except the bad
blocks file should have a start_block greater than
zero */
if (tsk_getu32(fs->endian, key->start_block) == 0)
return 0;
return 1;
}
/** \internal
* Returns the length of an HFS+ B-tree INDEX key based on the tree header
* structure and the length claimed in the record. With some trees,
* the length given in the record is not used.
* Note that this neither detects nor correctly handles 8-bit keys
* (which should not be present in HFS+).
*
* This does not give the right answer for the Attributes File B-tree, for some
* HFS+ file systems produced by the Apple OS, while it works for others. For
* the Attributes file, INDEX keys should always be as stated in the record itself,
* never the "maxKeyLen" of the B-tree header.
*
* In this software, this function is only invoked when dealing with the Extents file. In
* that usage, it is not sufficiently well tested to know if it always gives the right
* answer or not. We can only test that with a highly fragmented disk.
* @param hfs File System
* @param keylen Length of key as given in record
* @param header Tree header
* @returns Length of key
*/
uint16_t
hfs_get_idxkeylen(HFS_INFO * hfs, uint16_t keylen,
const hfs_btree_header_record * header)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
// if the flag is set, use the length given in the record
if (tsk_getu32(fs->endian, header->attr) & HFS_BT_HEAD_ATTR_VARIDXKEYS)
return keylen;
else
return tsk_getu16(fs->endian, header->maxKeyLen);
}
/**
* Convert the extents runs to TSK_FS_ATTR_RUN runs.
*
* @param a_fs File system to analyze
* @param a_extents Raw extents to process (in an array of 8)
* @param a_start_off Starting block offset of these runs
* @returns NULL on error or if no runs are in extents (test tsk_errno)
*/
static TSK_FS_ATTR_RUN *
hfs_extents_to_attr(TSK_FS_INFO * a_fs, const hfs_ext_desc * a_extents,
TSK_OFF_T a_start_off)
{
TSK_FS_ATTR_RUN *head_run = NULL;
TSK_FS_ATTR_RUN *prev_run = NULL;
int i;
TSK_OFF_T cur_off = a_start_off;
// since tsk_errno is checked as a return value, make sure it is clean.
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_extents_to_attr: Converting extents from offset %" PRIuOFF
" to runlist\n", a_start_off);
for (i = 0; i < 8; ++i) {
TSK_FS_ATTR_RUN *cur_run;
uint32_t addr = tsk_getu32(a_fs->endian, a_extents[i].start_blk);
uint32_t len = tsk_getu32(a_fs->endian, a_extents[i].blk_cnt);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_extents_to_attr: run %i at addr %" PRIu32
" with len %" PRIu32 "\n", i, addr, len);
if ((addr == 0) && (len == 0)) {
break;
}
// make a non-resident run
if ((cur_run = tsk_fs_attr_run_alloc()) == NULL) {
error_returned(" - hfs_extents_to_attr");
return NULL;
}
cur_run->addr = addr;
cur_run->len = len;
cur_run->offset = cur_off;
if (head_run == NULL)
head_run = cur_run;
if (prev_run != NULL)
prev_run->next = cur_run;
cur_off += cur_run->len;
prev_run = cur_run;
}
return head_run;
}
/**
* Look in the extents catalog for entries for a given file. Add the runs
* to the passed attribute structure.
*
* @param hfs File system being analyzed
* @param cnid file id of file to search for
* @param a_attr Attribute to add extents runs to
* @param dataForkQ if true, then find extents for the data fork. If false, then find extents for the Resource fork.
* @returns 1 on error and 0 on success
*/
static uint8_t
hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid,
TSK_FS_ATTR * a_attr, unsigned char dataForkQ)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint16_t nodesize; /* size of nodes (all, regardless of the name) */
uint32_t cur_node; /* node id of the current node */
char *node = NULL;
uint8_t is_done;
uint8_t desiredType;
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record_attr: Looking for extents for file %"
PRIu32 " %s\n", cnid,
dataForkQ ? "data fork" : "resource fork");
if (!hfs->has_extents_file) {
// No extents file (which is optional), and so, no further extents are possible.
return 0;
}
// Are we looking for extents of the data fork or the resource fork?
desiredType =
dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC;
// Load the extents attribute, if it has not been done so yet.
if (hfs->extents_file == NULL) {
ssize_t cnt;
if ((hfs->extents_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_EXTENTS_FILE_ID)) == NULL) {
return 1;
}
/* cache the data attribute */
hfs->extents_attr =
tsk_fs_attrlist_get(hfs->extents_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->extents_attr) {
tsk_error_errstr2_concat
(" - Default Attribute not found in Extents File");
return 1;
}
// cache the extents file header
cnt = tsk_fs_attr_read(hfs->extents_attr, 14,
(char *) &(hfs->extents_header),
sizeof(hfs_btree_header_record), 0);
if (cnt != sizeof(hfs_btree_header_record)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_ext_find_extent_record_attr: Error reading header");
return 1;
}
}
// allocate a node buffer
nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize);
if ((node = (char *) tsk_malloc(nodesize)) == NULL) {
return 1;
}
/* start at root node */
cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode);
/* if the root node is zero, then the extents btree is empty */
/* if no files have overflow extents, the Extents B-tree still
exists on disk, but is an empty B-tree containing only
the header node */
if (cur_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_ext_find_extent_record: "
"empty extents btree\n");
free(node);
return 0;
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_ext_find_extent_record: starting at "
"root node %" PRIu32 "; nodesize = %"
PRIu16 "\n", cur_node, nodesize);
/* Recurse down to the needed leaf nodes and then go forward */
is_done = 0;
while (is_done == 0) {
TSK_OFF_T cur_off; /* start address of cur_node */
uint16_t num_rec; /* number of records in this node */
ssize_t cnt;
hfs_btree_node *node_desc;
// sanity check
if (cur_node > tsk_getu32(fs->endian,
hfs->extents_header.totalNodes)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: Node %d too large for file",
cur_node);
free(node);
return 1;
}
// read the current node
cur_off = (TSK_OFF_T)cur_node * nodesize;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: reading node %" PRIu32
" at offset %" PRIuOFF "\n", cur_node, cur_off);
cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off,
node, nodesize, 0);
if (cnt != nodesize) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_ext_find_extent_record_attr: Error reading node %d at offset %"
PRIuOFF, cur_node, cur_off);
free(node);
return 1;
}
// process the header / descriptor
if (nodesize < sizeof(hfs_btree_node)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: Node size %d is too small to be valid", nodesize);
free(node);
return 1;
}
node_desc = (hfs_btree_node *) node;
num_rec = tsk_getu16(fs->endian, node_desc->num_rec);
if (num_rec == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record: zero records in node %"
PRIu32, cur_node);
free(node);
return 1;
}
/* With an index node, find the record with the largest key that is smaller
* to or equal to cnid */
if (node_desc->type == HFS_BT_NODE_TYPE_IDX) {
uint32_t next_node = 0;
int rec;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: Index node %" PRIu32
" @ %" PRIu64 " has %" PRIu16 " records\n", cur_node,
cur_off, num_rec);
for (rec = 0; rec < num_rec; ++rec) {
int cmp;
size_t rec_off;
hfs_btree_key_ext *key;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_ext *) & node[rec_off];
cmp = hfs_ext_compare_keys(hfs, cnid, key);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: record %" PRIu16
" ; keylen %" PRIu16 " (FileId: %" PRIu32
", ForkType: %" PRIu8 ", StartBlk: %" PRIu32
"); compare: %d\n", rec, tsk_getu16(fs->endian,
key->key_len), tsk_getu32(fs->endian,
key->file_id), key->fork_type,
tsk_getu32(fs->endian, key->start_block), cmp);
/* save the info from this record unless it is bigger than cnid */
if ((cmp <= 0) || (next_node == 0)) {
hfs_btree_index_record *idx_rec;
int keylen =
2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian,
key->key_len), &(hfs->extents_header));
if (rec_off + keylen > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node,
(int) rec_off + keylen, nodesize);
free(node);
return 1;
}
idx_rec =
(hfs_btree_index_record *) & node[rec_off +
keylen];
next_node = tsk_getu32(fs->endian, idx_rec->childNode);
}
// we are bigger than cnid, so move on to the next node
if (cmp > 0) {
break;
}
}
// check if we found a relevant node, if not stop.
if (next_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d",
cnid, cur_node);
is_done = 1;
break;
}
cur_node = next_node;
}
/* with a leaf, we process until we are past cnid. We move right too if we can */
else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) {
int rec;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: Leaf node %" PRIu32 " @ %"
PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off,
num_rec);
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_ext *key;
uint32_t rec_cnid;
hfs_extents *extents;
TSK_OFF_T ext_off = 0;
int keylen;
TSK_FS_ATTR_RUN *attr_run;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_ext *) & node[rec_off];
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_ext_find_extent_record: record %" PRIu16
"; keylen %" PRIu16 " (%" PRIu32
", %" PRIu8 ", %" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->file_id),
key->fork_type, tsk_getu32(fs->endian,
key->start_block));
rec_cnid = tsk_getu32(fs->endian, key->file_id);
// see if this record is for our file
// OLD logic, just handles the DATA fork
// if (rec_cnid < cnid) {
// continue;
// }
// else if ((rec_cnid > cnid)
// || (key->fork_type != HFS_EXT_KEY_TYPE_DATA)) {
// is_done = 1;
// break;
// }
// NEW logic, handles both DATA and RSRC forks.
if (rec_cnid < cnid) {
continue;
}
if (rec_cnid > cnid) {
is_done = 1;
break;
}
if (key->fork_type != desiredType) {
if (dataForkQ) {
is_done = 1;
break;
}
else
continue;
}
// OK, this is one of the extents records that we are seeking, so save it.
// Make sure there is room for the hfs_extents struct
keylen = 2 + tsk_getu16(fs->endian, key->key_len);
if (rec_off + keylen + sizeof(hfs_extents) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off + keylen,
nodesize);
free(node);
return 1;
}
// get the starting offset of this extent
ext_off = tsk_getu32(fs->endian, key->start_block);
// convert the extents to the TSK format
extents = (hfs_extents *) & node[rec_off + keylen];
attr_run =
hfs_extents_to_attr(fs, extents->extents, ext_off);
if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) {
tsk_error_errstr2_concat
(" - hfs_ext_find_extent_record_attr");
free(node);
return 1;
}
if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) {
tsk_error_errstr2_concat
(" - hfs_ext_find_extent_record_attr");
free(node);
return 1;
}
}
cur_node = tsk_getu32(fs->endian, node_desc->flink);
if (cur_node == 0) {
is_done = 1;
break;
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_ext_find_extent_record: btree node %"
PRIu32 " (%" PRIuOFF ") is neither index nor leaf (%" PRIu8
")", cur_node, cur_off, node_desc->type);
free(node);
return 1;
}
}
free(node);
return 0;
}
/** \internal
* Compares two Catalog B-tree keys.
* @param hfs File System being analyzed
* @param key1 Key 1 to compare
* @param key2 Key 2 to compare
* @returns -1 if key1 is smaller, 0 if equal, and 1 if key1 is larger
*/
int
hfs_cat_compare_keys(HFS_INFO * hfs, const hfs_btree_key_cat * key1,
const hfs_btree_key_cat * key2)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint32_t cnid1, cnid2;
cnid1 = tsk_getu32(fs->endian, key1->parent_cnid);
cnid2 = tsk_getu32(fs->endian, key2->parent_cnid);
if (cnid1 < cnid2)
return -1;
if (cnid1 > cnid2)
return 1;
return hfs_unicode_compare(hfs, &key1->name, &key2->name);
}
/** \internal
*
* Traverse the HFS catalog file. Call the callback for each
* record.
*
* @param hfs File system
* @param a_cb callback
* @param ptr Pointer to pass to callback
* @returns 1 on error
*/
uint8_t
hfs_cat_traverse(HFS_INFO * hfs,
TSK_HFS_BTREE_CB a_cb, void *ptr)
{
TSK_FS_INFO *fs = &(hfs->fs_info);
uint32_t cur_node; /* node id of the current node */
char *node;
uint16_t nodesize;
uint8_t is_done = 0;
tsk_error_reset();
nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize);
if ((node = (char *) tsk_malloc(nodesize)) == NULL)
return 1;
/* start at root node */
cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode);
/* if the root node is zero, then the extents btree is empty */
/* if no files have overflow extents, the Extents B-tree still
exists on disk, but is an empty B-tree containing only
the header node */
if (cur_node == 0) {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: "
"empty extents btree\n");
free(node);
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: starting at "
"root node %" PRIu32 "; nodesize = %"
PRIu16 "\n", cur_node, nodesize);
/* Recurse down to the needed leaf nodes and then go forward */
is_done = 0;
while (is_done == 0) {
TSK_OFF_T cur_off; /* start address of cur_node */
uint16_t num_rec; /* number of records in this node */
ssize_t cnt;
hfs_btree_node *node_desc;
// sanity check
if (cur_node > tsk_getu32(fs->endian,
hfs->catalog_header.totalNodes)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node %d too large for file", cur_node);
free(node);
return 1;
}
// read the current node
cur_off = cur_node * nodesize;
cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off,
node, nodesize, 0);
if (cnt != nodesize) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_traverse: Error reading node %d at offset %"
PRIuOFF, cur_node, cur_off);
free(node);
return 1;
}
// process the header / descriptor
if (nodesize < sizeof(hfs_btree_node)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: Node size %d is too small to be valid", nodesize);
free(node);
return 1;
}
node_desc = (hfs_btree_node *) node;
num_rec = tsk_getu16(fs->endian, node_desc->num_rec);
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32
" @ %" PRIu64 " has %" PRIu16 " records\n",
cur_node, cur_off, num_rec);
if (num_rec == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: zero records in node %"
PRIu32, cur_node);
free(node);
return 1;
}
/* With an index node, find the record with the largest key that is smaller
* to or equal to cnid */
if (node_desc->type == HFS_BT_NODE_TYPE_IDX) {
uint32_t next_node = 0;
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if ((keylen) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, nodesize);
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
" ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
/* save the info from this record unless it is too big */
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
// record the closest entry
else if ((retval == HFS_BTREE_CB_IDX_LT)
|| (next_node == 0)) {
hfs_btree_index_record *idx_rec;
int keylen =
2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian,
key->key_len), &(hfs->catalog_header));
if (rec_off + keylen > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %"
PRIu16 ")", rec, cur_node,
(int) rec_off + keylen, nodesize);
free(node);
return 1;
}
idx_rec =
(hfs_btree_index_record *) & node[rec_off +
keylen];
next_node = tsk_getu32(fs->endian, idx_rec->childNode);
}
if (retval == HFS_BTREE_CB_IDX_EQGT) {
// move down to the next node
break;
}
}
// check if we found a relevant node
if (next_node == 0) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: did not find any keys in index node %d",
cur_node);
is_done = 1;
break;
}
// TODO: Handle multinode loops
if (next_node == cur_node) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: node %d references itself as next node",
cur_node);
is_done = 1;
break;
}
cur_node = next_node;
}
/* With a leaf, we look for the specific record. */
else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) {
int rec;
for (rec = 0; rec < num_rec; ++rec) {
size_t rec_off;
hfs_btree_key_cat *key;
uint8_t retval;
int keylen;
// get the record offset in the node
rec_off =
tsk_getu16(fs->endian,
&node[nodesize - (rec + 1) * 2]);
if (rec_off > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, (int) rec_off,
nodesize);
free(node);
return 1;
}
key = (hfs_btree_key_cat *) & node[rec_off];
keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len);
if ((keylen) > nodesize) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %"
PRIu16 ")", rec, cur_node, keylen, nodesize);
free(node);
return 1;
}
/*
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: record %" PRIu16
"; keylen %" PRIu16 " (%" PRIu32 ")\n", rec,
tsk_getu16(fs->endian, key->key_len),
tsk_getu32(fs->endian, key->parent_cnid));
*/
// rec_cnid = tsk_getu32(fs->endian, key->file_id);
retval =
a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key,
cur_off + rec_off, ptr);
if (retval == HFS_BTREE_CB_LEAF_STOP) {
is_done = 1;
break;
}
else if (retval == HFS_BTREE_CB_ERR) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr2
("hfs_cat_traverse: Callback returned error");
free(node);
return 1;
}
}
// move right to the next node if we got this far
if (is_done == 0) {
cur_node = tsk_getu32(fs->endian, node_desc->flink);
if (cur_node == 0) {
is_done = 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_traverse: moving forward to next leaf");
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32
" (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")",
cur_node, cur_off, node_desc->type);
free(node);
return 1;
}
}
free(node);
return 0;
}
typedef struct {
const hfs_btree_key_cat *targ_key;
TSK_OFF_T off;
} HFS_CAT_GET_RECORD_OFFSET_DATA;
static uint8_t
hfs_cat_get_record_offset_cb(HFS_INFO * hfs, int8_t level_type,
const hfs_btree_key_cat * cur_key,
TSK_OFF_T key_off, void *ptr)
{
HFS_CAT_GET_RECORD_OFFSET_DATA *offset_data = (HFS_CAT_GET_RECORD_OFFSET_DATA *)ptr;
const hfs_btree_key_cat *targ_key = offset_data->targ_key;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_get_record_offset_cb: %s node want: %" PRIu32
" vs have: %" PRIu32 "\n",
(level_type == HFS_BT_NODE_TYPE_IDX) ? "Index" : "Leaf",
tsk_getu32(hfs->fs_info.endian, targ_key->parent_cnid),
tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid));
if (level_type == HFS_BT_NODE_TYPE_IDX) {
int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key);
if (diff < 0)
return HFS_BTREE_CB_IDX_LT;
else
return HFS_BTREE_CB_IDX_EQGT;
}
else {
int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key);
// see if this record is for our file or if we passed the interesting entries
if (diff < 0) {
return HFS_BTREE_CB_LEAF_GO;
}
else if (diff == 0) {
offset_data->off =
key_off + 2 + tsk_getu16(hfs->fs_info.endian,
cur_key->key_len);
}
return HFS_BTREE_CB_LEAF_STOP;
}
}
/** \internal
* Find the byte offset (from the start of the catalog file) to a record
* in the catalog file.
* @param hfs File System being analyzed
* @param needle Key to search for
* @returns Byte offset or 0 on error. 0 is also returned if catalog
* record was not found. Check tsk_errno to determine if error occurred.
*/
static TSK_OFF_T
hfs_cat_get_record_offset(HFS_INFO * hfs, const hfs_btree_key_cat * needle)
{
HFS_CAT_GET_RECORD_OFFSET_DATA offset_data;
offset_data.off = 0;
offset_data.targ_key = needle;
if (hfs_cat_traverse(hfs, hfs_cat_get_record_offset_cb, &offset_data)) {
return 0;
}
return offset_data.off;
}
/** \internal
* Given a byte offset to a leaf record in teh catalog file, read the data as
* a thread record. This will zero the buffer and read in the size of the thread
* data.
* @param hfs File System
* @param off Byte offset of record in catalog file (not including key)
* @param thread [out] Buffer to write thread data into.
* @returns 0 on success, 1 on failure; sets up to error string 1 */
uint8_t
hfs_cat_read_thread_record(HFS_INFO * hfs, TSK_OFF_T off,
hfs_thread * thread)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
uint16_t uni_len;
ssize_t cnt;
memset(thread, 0, sizeof(hfs_thread));
cnt = tsk_fs_attr_read(hfs->catalog_attr, off, (char *) thread, 10, 0);
if (cnt != 10) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_thread_record: Error reading catalog offset %"
PRIuOFF " (header)", off);
return 1;
}
if ((tsk_getu16(fs->endian, thread->rec_type) != HFS_FOLDER_THREAD)
&& (tsk_getu16(fs->endian, thread->rec_type) != HFS_FILE_THREAD)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_read_thread_record: unexpected record type %" PRIu16,
tsk_getu16(fs->endian, thread->rec_type));
return 1;
}
uni_len = tsk_getu16(fs->endian, thread->name.length);
if (uni_len > 255) {
tsk_error_set_errno(TSK_ERR_FS_INODE_COR);
tsk_error_set_errstr
("hfs_cat_read_thread_record: invalid string length (%" PRIu16
")", uni_len);
return 1;
}
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off + 10,
(char *) thread->name.unicode, uni_len * 2, 0);
if (cnt != uni_len * 2) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_thread_record: Error reading catalog offset %"
PRIuOFF " (name)", off + 10);
return 1;
}
return 0;
}
/** \internal
* Read a catalog record into a local data structure. This reads the
* correct amount, depending on if it is a file or folder.
* @param hfs File system being analyzed
* @param off Byte offset (in catalog file) of record (not including key)
* @param record [out] Structure to read data into
* @returns 1 on error
*/
uint8_t
hfs_cat_read_file_folder_record(HFS_INFO * hfs, TSK_OFF_T off,
hfs_file_folder * record)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
ssize_t cnt;
char rec_type[2];
memset(record, 0, sizeof(hfs_file_folder));
cnt = tsk_fs_attr_read(hfs->catalog_attr, off, rec_type, 2, 0);
if (cnt != 2) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading record type from catalog offset %"
PRIuOFF " (header)", off);
return 1;
}
if (tsk_getu16(fs->endian, rec_type) == HFS_FOLDER_RECORD) {
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record,
sizeof(hfs_folder), 0);
if (cnt != sizeof(hfs_folder)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading catalog offset %"
PRIuOFF " (folder)", off);
return 1;
}
}
else if (tsk_getu16(fs->endian, rec_type) == HFS_FILE_RECORD) {
cnt =
tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record,
sizeof(hfs_file), 0);
if (cnt != sizeof(hfs_file)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
tsk_error_set_errstr2
("hfs_cat_read_file_folder_record: Error reading catalog offset %"
PRIuOFF " (file)", off);
return 1;
}
}
else {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_read_file_folder_record: unexpected record type %"
PRIu16, tsk_getu16(fs->endian, rec_type));
return 1;
}
return 0;
}
// hfs_lookup_hard_link appears to be unnecessary - it looks up the cnid
// by seeing if there's a file/dir with the standard hard link name plus
// linknum and returns the meta_addr. But this should always be the same as linknum,
// and is very slow when there are many hard links, so it shouldn't be used.
//static TSK_INUM_T
//hfs_lookup_hard_link(HFS_INFO * hfs, TSK_INUM_T linknum,
// unsigned char is_directory)
//{
// char fBuff[30];
// TSK_FS_DIR *mdir;
// size_t indx;
// TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
//
// memset(fBuff, 0, 30);
//
// if (is_directory) {
//
// tsk_take_lock(&(hfs->metadata_dir_cache_lock));
// if (hfs->dir_meta_dir == NULL) {
// hfs->dir_meta_dir =
// tsk_fs_dir_open_meta(fs, hfs->meta_dir_inum);
// }
// tsk_release_lock(&(hfs->metadata_dir_cache_lock));
//
// if (hfs->dir_meta_dir == NULL) {
// error_returned
// ("hfs_lookup_hard_link: could not open the dir metadata directory");
// return 0;
// }
// else {
// mdir = hfs->dir_meta_dir;
// }
// snprintf(fBuff, 30, "dir_%" PRIuINUM, linknum);
//
// }
// else {
//
// tsk_take_lock(&(hfs->metadata_dir_cache_lock));
// if (hfs->meta_dir == NULL) {
// hfs->meta_dir = tsk_fs_dir_open_meta(fs, hfs->meta_inum);
// }
// tsk_release_lock(&(hfs->metadata_dir_cache_lock));
//
// if (hfs->meta_dir == NULL) {
// error_returned
// ("hfs_lookup_hard_link: could not open file metadata directory");
// return 0;
// }
// else {
// mdir = hfs->meta_dir;
// }
// snprintf(fBuff, 30, "iNode%" PRIuINUM, linknum);
// }
//
// for (indx = 0; indx < tsk_fs_dir_getsize(mdir); ++indx) {
// if ((mdir->names != NULL) && mdir->names[indx].name &&
// (fs->name_cmp(fs, mdir->names[indx].name, fBuff) == 0)) {
// // OK this is the one
// return mdir->names[indx].meta_addr;
// }
// }
//
// // OK, we did not find that linknum
// return 0;
//}
/*
* Given a catalog entry, will test that entry to see if it is a hard link.
* If it is a hard link, the function returns the inum (or cnid) of the target file.
* If it is NOT a hard link, then then function returns the inum of the given entry.
* In both cases, the parameter is_error is set to zero.
*
* If an ERROR occurs, if it is a mild error, then is_error is set to 1, and the
* inum of the given entry is returned. This signals that hard link detection cannot
* be carried out.
*
* If the error is serious, then is_error is set to 2 or 3, depending on the kind of error, and
* the TSK error code is set, and the function returns zero. is_error==2 means that an error
* occurred in looking up the target file in the Catalog. is_error==3 means that the given
* entry appears to be a hard link, but the target file does not exist in the Catalog.
*
* @param hfs The file system
* @param entry The catalog entry to check
* @param is_error A Boolean that is returned indicating an error, or no error.\
* @return The inum (or cnid) of the hard link target, or of the given catalog entry, or zero.
*/
TSK_INUM_T
hfs_follow_hard_link(HFS_INFO * hfs, hfs_file * cat,
unsigned char *is_error)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_INUM_T cnid;
time_t crtime;
uint32_t file_type;
uint32_t file_creator;
*is_error = 0; // default, not an error
if (cat == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_follow_hard_link: Pointer to Catalog entry (2nd arg) is null");
return 0;
}
cnid = tsk_getu32(fs->endian, cat->std.cnid);
if (cnid < HFS_FIRST_USER_CNID) {
// Can't be a hard link. And, cannot look up in Catalog file either!
return cnid;
}
crtime =
(time_t) hfs_convert_2_unix_time(tsk_getu32(fs->endian,
cat->std.crtime));
file_type = tsk_getu32(fs->endian, cat->std.u_info.file_type);
file_creator = tsk_getu32(fs->endian, cat->std.u_info.file_cr);
// Only proceed with the rest of this if the flags etc are right
if (file_type == HFS_HARDLINK_FILE_TYPE
&& file_creator == HFS_HARDLINK_FILE_CREATOR) {
// see if we have the HFS+ Private Data dir for file links;
// if not, it can't be a hard link. (We could warn the user, but
// we also rely on this when finding the HFS+ Private Data dir in
// the first place and we don't want a warning on every hfs_open.)
if (hfs->meta_inum == 0)
return cnid;
// For this to work, we need the FS creation times. Is at least one of these set?
if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime)
&& (!hfs->has_meta_crtime)) {
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
*is_error = 1;
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: File system creation times are not set. "
"Cannot test inode for hard link. File type and creator indicate that this"
" is a hard link (file), with LINK ID = %" PRIu32 "\n",
linkNum);
return cnid;
}
if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime)) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: Either the root folder or the"
" file metadata folder is not accessible. Testing this potential hard link"
" may be impaired.\n");
}
// Now we need to check the creation time against the three FS creation times
if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) ||
(hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime))
|| (hfs->has_root_crtime && (crtime == hfs->root_crtime))) {
// OK, this is a hard link to a file.
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
// We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found
// that it was very ineffecient and always resulted in the same linkNum value.
// We now just use linkNum
return linkNum;
}
}
else if (file_type == HFS_LINKDIR_FILE_TYPE
&& file_creator == HFS_LINKDIR_FILE_CREATOR) {
// see if we have the HFS+ Private Directory Data dir for links;
// if not, it can't be a hard link. (We could warn the user, but
// we also rely on this when finding the HFS+ Private Directory Data dir in
// the first place and we don't want a warning on every hfs_open.)
if (hfs->meta_dir_inum == 0)
return cnid;
// For this to work, we need the FS creation times. Is at least one of these set?
if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime)
&& (!hfs->has_meta_crtime)) {
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
*is_error = 1;
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: File system creation times are not set. "
"Cannot test inode for hard link. File type and creator indicate that this"
" is a hard link (directory), with LINK ID = %" PRIu32
"\n", linkNum);
return cnid;
}
if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime)
|| (!hfs->has_meta_dir_crtime)) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_follow_hard_link: Either the root folder or the"
" file metadata folder or the directory metatdata folder is"
" not accessible. Testing this potential hard linked folder "
"may be impaired.\n");
}
// Now we need to check the creation time against the three FS creation times
if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) ||
(hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime))
|| (hfs->has_root_crtime && (crtime == hfs->root_crtime))) {
// OK, this is a hard link to a directory.
uint32_t linkNum =
tsk_getu32(fs->endian, cat->std.perm.special.inum);
// We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found
// that it was very ineffecient and always resulted in the same linkNum value.
// We now just use linkNum
return linkNum;
}
}
// It cannot be a hard link (file or directory)
return cnid;
}
/** \internal
* Lookup an entry in the catalog file and save it into the entry. Do not
* call this for the special files that do not have an entry in the catalog.
* data structure.
* @param hfs File system being analyzed
* @param inum Address (cnid) of file to open
* @param entry [out] Structure to read data into
* @returns 1 on error or not found, 0 on success. Check tsk_errno
* to differentiate between error and not found. If it is not found, then the
* errno will be TSK_ERR_FS_INODE_NUM. Else, it will be some other value.
*/
uint8_t
hfs_cat_file_lookup(HFS_INFO * hfs, TSK_INUM_T inum, HFS_ENTRY * entry,
unsigned char follow_hard_link)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
hfs_btree_key_cat key; /* current catalog key */
hfs_thread thread; /* thread record */
hfs_file_folder record; /* file/folder record */
TSK_OFF_T off;
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: called for inum %" PRIuINUM "\n", inum);
// Test if this is a special file that is not located in the catalog
if ((inum == HFS_EXTENTS_FILE_ID) ||
(inum == HFS_CATALOG_FILE_ID) ||
(inum == HFS_ALLOCATION_FILE_ID) ||
(inum == HFS_STARTUP_FILE_ID) ||
(inum == HFS_ATTRIBUTES_FILE_ID)) {
tsk_error_set_errno(TSK_ERR_FS_GENFS);
tsk_error_set_errstr
("hfs_cat_file_lookup: Called on special file: %" PRIuINUM,
inum);
return 1;
}
/* first look up the thread record for the item we're searching for */
/* set up the thread record key */
memset((char *) &key, 0, sizeof(hfs_btree_key_cat));
cnid_to_array((uint32_t) inum, key.parent_cnid);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: Looking up thread record (%" PRIuINUM
")\n", inum);
/* look up the thread record */
off = hfs_cat_get_record_offset(hfs, &key);
if (off == 0) {
// no parsing error, just not found
if (tsk_error_get_errno() == 0) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr
("hfs_cat_file_lookup: Error finding thread node for file (%"
PRIuINUM ")", inum);
}
else {
tsk_error_set_errstr2
(" hfs_cat_file_lookup: thread for file (%" PRIuINUM ")",
inum);
}
return 1;
}
/* read the thread record */
if (hfs_cat_read_thread_record(hfs, off, &thread)) {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")",
inum);
return 1;
}
/* now look up the actual file/folder record */
/* build key */
memset((char *) &key, 0, sizeof(hfs_btree_key_cat));
memcpy((char *) key.parent_cnid, (char *) thread.parent_cnid,
sizeof(key.parent_cnid));
memcpy((char *) &key.name, (char *) &thread.name, sizeof(key.name));
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: Looking up file record (parent: %"
PRIuINUM ")\n", (uint64_t) tsk_getu32(fs->endian,
key.parent_cnid));
/* look up the record */
off = hfs_cat_get_record_offset(hfs, &key);
if (off == 0) {
// no parsing error, just not found
if (tsk_error_get_errno() == 0) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr
("hfs_cat_file_lookup: Error finding record node %"
PRIuINUM, inum);
}
else {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM
")", inum);
}
return 1;
}
/* read the record */
if (hfs_cat_read_file_folder_record(hfs, off, &record)) {
tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")",
inum);
return 1;
}
/* these memcpy can be gotten rid of, really */
if (tsk_getu16(fs->endian,
record.file.std.rec_type) == HFS_FOLDER_RECORD) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: found folder record valence %" PRIu32
", cnid %" PRIu32 "\n", tsk_getu32(fs->endian,
record.folder.std.valence), tsk_getu32(fs->endian,
record.folder.std.cnid));
memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_folder));
}
else if (tsk_getu16(fs->endian,
record.file.std.rec_type) == HFS_FILE_RECORD) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_cat_file_lookup: found file record cnid %" PRIu32
"\n", tsk_getu32(fs->endian, record.file.std.cnid));
memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_file));
}
/* other cases already caught by hfs_cat_read_file_folder_record */
memcpy((char *) &entry->thread, (char *) &thread, sizeof(hfs_thread));
entry->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED;
entry->inum = inum;
if (follow_hard_link) {
// TEST to see if this is a hard link
unsigned char is_err;
TSK_INUM_T target_cnid =
hfs_follow_hard_link(hfs, &(entry->cat), &is_err);
if (is_err > 1) {
error_returned
("hfs_cat_file_lookup: error occurred while following a possible hard link for "
"inum (cnid) = %" PRIuINUM, inum);
return 1;
}
if (target_cnid != inum) {
// This is a hard link, and we have got the cnid of the target file, so look it up.
uint8_t res =
hfs_cat_file_lookup(hfs, target_cnid, entry, FALSE);
if (res != 0) {
error_returned
("hfs_cat_file_lookup: error occurred while looking up the Catalog entry for "
"the target of inum (cnid) = %" PRIuINUM " target",
inum);
}
return 1;
}
// Target is NOT a hard link, so fall through to the non-hard link exit.
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_cat_file_lookup exiting\n");
return 0;
}
static uint8_t
hfs_find_highest_inum_cb(HFS_INFO * hfs, int8_t level_type,
const hfs_btree_key_cat * cur_key,
TSK_OFF_T key_off, void *ptr)
{
// NOTE: This assumes that the biggest inum is the last one that we
// see. the traverse method does not currently promise that as part of
// its callback "contract".
*((TSK_INUM_T*) ptr) = tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid);
return HFS_BTREE_CB_IDX_LT;
}
/** \internal
* Returns the largest inode number in file system
* @param hfs File system being analyzed
* @returns largest metadata address
*/
static TSK_INUM_T
hfs_find_highest_inum(HFS_INFO * hfs)
{
// @@@ get actual number from Catalog file (go to far right) (we can't always trust the vol header)
TSK_INUM_T inum;
if (hfs_cat_traverse(hfs, hfs_find_highest_inum_cb, &inum)) {
/* Catalog traversal failed, fallback on legacy method :
if HFS_VH_ATTR_CNIDS_REUSED is set, then
the maximum CNID is 2^32-1; if it's not set, then nextCatalogId is
supposed to be larger than all CNIDs on disk.
*/
TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info);
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_CNIDS_REUSED)
return (TSK_INUM_T) 0xffffffff;
else
return (TSK_INUM_T) tsk_getu32(fs->endian,
hfs->fs->next_cat_id) - 1;
}
return inum;
}
static TSK_FS_META_MODE_ENUM
hfs_mode_to_tsk_mode(uint16_t a_mode)
{
TSK_FS_META_MODE_ENUM mode = 0;
if (a_mode & HFS_IN_ISUID)
mode |= TSK_FS_META_MODE_ISUID;
if (a_mode & HFS_IN_ISGID)
mode |= TSK_FS_META_MODE_ISGID;
if (a_mode & HFS_IN_ISVTX)
mode |= TSK_FS_META_MODE_ISVTX;
if (a_mode & HFS_IN_IRUSR)
mode |= TSK_FS_META_MODE_IRUSR;
if (a_mode & HFS_IN_IWUSR)
mode |= TSK_FS_META_MODE_IWUSR;
if (a_mode & HFS_IN_IXUSR)
mode |= TSK_FS_META_MODE_IXUSR;
if (a_mode & HFS_IN_IRGRP)
mode |= TSK_FS_META_MODE_IRGRP;
if (a_mode & HFS_IN_IWGRP)
mode |= TSK_FS_META_MODE_IWGRP;
if (a_mode & HFS_IN_IXGRP)
mode |= TSK_FS_META_MODE_IXGRP;
if (a_mode & HFS_IN_IROTH)
mode |= TSK_FS_META_MODE_IROTH;
if (a_mode & HFS_IN_IWOTH)
mode |= TSK_FS_META_MODE_IWOTH;
if (a_mode & HFS_IN_IXOTH)
mode |= TSK_FS_META_MODE_IXOTH;
return mode;
}
static TSK_FS_META_TYPE_ENUM
hfs_mode_to_tsk_meta_type(uint16_t a_mode)
{
switch (a_mode & HFS_IN_IFMT) {
case HFS_IN_IFIFO:
return TSK_FS_META_TYPE_FIFO;
case HFS_IN_IFCHR:
return TSK_FS_META_TYPE_CHR;
case HFS_IN_IFDIR:
return TSK_FS_META_TYPE_DIR;
case HFS_IN_IFBLK:
return TSK_FS_META_TYPE_BLK;
case HFS_IN_IFREG:
return TSK_FS_META_TYPE_REG;
case HFS_IN_IFLNK:
return TSK_FS_META_TYPE_LNK;
case HFS_IN_IFSOCK:
return TSK_FS_META_TYPE_SOCK;
case HFS_IFWHT:
return TSK_FS_META_TYPE_WHT;
case HFS_IFXATTR:
return TSK_FS_META_TYPE_UNDEF;
default:
/* error */
return TSK_FS_META_TYPE_UNDEF;
}
}
static uint8_t
hfs_make_specialbase(TSK_FS_FILE * fs_file)
{
fs_file->meta->type = TSK_FS_META_TYPE_REG;
fs_file->meta->mode = 0;
fs_file->meta->nlink = 1;
fs_file->meta->flags =
(TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC);
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) {
error_returned
(" - hfs_make_specialbase, couldn't malloc space for a name list");
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();
}
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the catalog file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_catalog(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_catalog: Making virtual catalog file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_catalog");
return 1;
}
fs_file->meta->addr = HFS_CATALOG_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_CATALOGNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz);
// convert the runs in the volume header to attribute runs
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->cat_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_catalog");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_catalog");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_catalog");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_CATALOG_FILE_ID, fs_attr,
TRUE)) {
error_returned(" - hfs_make_catalog");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Catalog file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_FILE for the extents file
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_extents(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_extents: Making virtual extents file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_extents");
return 1;
}
fs_file->meta->addr = HFS_EXTENTS_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_EXTENTSNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->ext_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_extents");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_extents");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_extents");
tsk_fs_attr_run_free(attr_run);
return 1;
}
//hfs_load_extended_attrs(fs_file);
// Extents doesn't have an entry in itself
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the blockmap / allocation file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_blockmap(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_blockmap: Making virtual blockmap file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_blockmap");
return 1;
}
fs_file->meta->addr = HFS_ALLOCATION_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_ALLOCATIONNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->alloc_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_blockmap");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_blockmap");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_blockmap");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_ALLOCATION_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_blockmap");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Allocation file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the startup / boot file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_startfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_startfile: Making virtual startup file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_startfile");
return 1;
}
fs_file->meta->addr = HFS_STARTUP_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_STARTUPNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->start_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_startfile");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_startfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_startfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_STARTUP_FILE_ID, fs_attr,
TRUE)) {
error_returned(" - hfs_make_startfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the Start file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_INODE structure for the attributes file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_attrfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_attrfile: Making virtual attributes file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_attrfile");
return 1;
}
fs_file->meta->addr = HFS_ATTRIBUTES_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_ATTRIBUTESNAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size =
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz);
if (((attr_run =
hfs_extents_to_attr(fs, hfs->fs->attr_file.extents,
0)) == NULL) && (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_make_attrfile");
return 1;
}
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_attrfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// initialize the data run
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz),
tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz), 0, 0)) {
error_returned(" - hfs_make_attrfile");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if catalog file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_ATTRIBUTES_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_attrfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
//hfs_load_extended_attrs(fs_file);
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/**
* \internal
* Create an FS_FILE structure for the BadBlocks file.
*
* @param hfs File system to analyze
* @param fs_file Structure to copy file information into.
* @return 1 on error and 0 on success
*/
static uint8_t
hfs_make_badblockfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file)
{
TSK_FS_ATTR *fs_attr;
unsigned char dummy1, dummy2;
uint64_t dummy3;
uint8_t result;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_make_badblockfile: Making virtual badblock file\n");
if (hfs_make_specialbase(fs_file)) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
fs_file->meta->addr = HFS_BAD_BLOCK_FILE_ID;
strncpy(fs_file->meta->name2->name, HFS_BAD_BLOCK_FILE_NAME,
TSK_FS_META_NAME_LIST_NSIZE);
fs_file->meta->size = 0;
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
// add the run to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, NULL,
TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA,
fs_file->meta->size, fs_file->meta->size, fs_file->meta->size,
0, 0)) {
error_returned(" - hfs_make_badblockfile");
return 1;
}
// see if file has additional runs
if (hfs_ext_find_extent_record_attr(hfs, HFS_BAD_BLOCK_FILE_ID,
fs_attr, TRUE)) {
error_returned(" - hfs_make_badblockfile");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
/* @@@ We have a chicken and egg problem here... The current design of
* fs_attr_set() requires the size to be set, but we dont' know the size
* until we look into the extents file (which adds to an attribute...).
* This does not seem to be the best design... neeed a way to test this. */
fs_file->meta->size = fs_attr->nrd.initsize;
fs_attr->size = fs_file->meta->size;
fs_attr->nrd.allocsize = fs_file->meta->size;
result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3);
if (result != 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: Extended attributes failed to load for the BadBlocks file.\n");
tsk_error_reset();
}
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/** \internal
* Copy the catalog file or folder record entry into a TSK data structure.
* @param a_hfs File system being analyzed
* @param a_hfs_entry Catalog record entry (HFS_ENTRY *)
* @param a_fs_file Structure to copy data into (TSK_FS_FILE *)
* Returns 1 on error.
*/
static uint8_t
hfs_dinode_copy(HFS_INFO * a_hfs, const HFS_ENTRY * a_hfs_entry,
TSK_FS_FILE * a_fs_file)
{
// Note, a_hfs_entry->cat is really of type hfs_file. But, hfs_file_folder is a union
// of that type with hfs_folder. Both of hfs_file and hfs_folder have the same first member.
// So, this cast is appropriate.
const hfs_file_folder *a_entry =
(hfs_file_folder *) & (a_hfs_entry->cat);
const hfs_file_fold_std *std;
TSK_FS_META *a_fs_meta = a_fs_file->meta;
TSK_FS_INFO *fs;
uint16_t hfsmode;
TSK_INUM_T iStd; // the inum (or CNID) that occurs in the standard file metadata
if (a_entry == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_dinode_copy: a_entry = a_hfs_entry->cat is NULL");
return 1;
}
fs = (TSK_FS_INFO *) & a_hfs->fs_info;
// Just a sanity check. The inum (or cnid) occurs in two places in the
// entry data structure.
iStd = tsk_getu32(fs->endian, a_entry->file.std.cnid);
if (iStd != a_hfs_entry->inum) {
if (tsk_verbose)
tsk_fprintf(stderr,
"WARNING: hfs_dinode_copy: HFS_ENTRY with conflicting values for inum (or cnid).\n");
}
if (a_fs_meta == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("hfs_dinode_copy: a_fs_meta is NULL");
return 1;
}
// both files and folders start off the same
std = &(a_entry->file.std);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy: called for file/folder %" PRIu32 "\n",
tsk_getu32(fs->endian, std->cnid));
if (a_fs_meta->content_len < HFS_FILE_CONTENT_LEN) {
if ((a_fs_meta =
tsk_fs_meta_realloc(a_fs_meta,
HFS_FILE_CONTENT_LEN)) == NULL) {
return 1;
}
}
a_fs_meta->attr_state = TSK_FS_META_ATTR_EMPTY;
if (a_fs_meta->attr) {
tsk_fs_attrlist_markunused(a_fs_meta->attr);
}
/*
* Copy the file type specific stuff first
*/
hfsmode = tsk_getu16(fs->endian, std->perm.mode);
if (tsk_getu16(fs->endian, std->rec_type) == HFS_FOLDER_RECORD) {
// set the type of mode is not set
if ((hfsmode & HFS_IN_IFMT) == 0)
a_fs_meta->type = TSK_FS_META_TYPE_DIR;
a_fs_meta->size = 0;
memset(a_fs_meta->content_ptr, 0, HFS_FILE_CONTENT_LEN);
}
else if (tsk_getu16(fs->endian, std->rec_type) == HFS_FILE_RECORD) {
hfs_fork *fork;
// set the type of mode is not set
if ((hfsmode & HFS_IN_IFMT) == 0)
a_fs_meta->type = TSK_FS_META_TYPE_REG;
a_fs_meta->size =
tsk_getu64(fs->endian, a_entry->file.data.logic_sz);
// copy the data and resource forks
fork = (hfs_fork *) a_fs_meta->content_ptr;
memcpy(fork, &(a_entry->file.data), sizeof(hfs_fork));
memcpy(&fork[1], &(a_entry->file.resource), sizeof(hfs_fork));
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy error: catalog entry is neither file nor folder\n");
return 1;
}
/*
* Copy the standard stuff.
* Use default values (as defined in spec) if mode is not defined.
*/
if ((hfsmode & HFS_IN_IFMT) == 0) {
a_fs_meta->mode = 0;
a_fs_meta->uid = 99;
a_fs_meta->gid = 99;
}
else {
a_fs_meta->mode = hfs_mode_to_tsk_mode(hfsmode);
a_fs_meta->type = hfs_mode_to_tsk_meta_type(hfsmode);
a_fs_meta->uid = tsk_getu32(fs->endian, std->perm.owner);
a_fs_meta->gid = tsk_getu32(fs->endian, std->perm.group);
}
// this field is set only for "indirect" entries
if (tsk_getu32(fs->endian, std->perm.special.nlink))
a_fs_meta->nlink = tsk_getu32(fs->endian, std->perm.special.nlink);
else
a_fs_meta->nlink = 1;
a_fs_meta->mtime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->cmtime));
a_fs_meta->atime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->atime));
a_fs_meta->crtime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->crtime));
a_fs_meta->ctime =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->amtime));
a_fs_meta->time2.hfs.bkup_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->bkup_date));
a_fs_meta->mtime_nano = a_fs_meta->atime_nano = a_fs_meta->ctime_nano =
a_fs_meta->crtime_nano = 0;
a_fs_meta->time2.hfs.bkup_time_nano = 0;
a_fs_meta->addr = tsk_getu32(fs->endian, std->cnid);
// All entries here are used.
a_fs_meta->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED;
if (std->perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
a_fs_meta->flags |= TSK_FS_META_FLAG_COMP;
// We copy this inum (or cnid) here, because this file *might* have been a hard link. In
// that case, we want to make sure that a_fs_file points consistently to the target of the
// link.
if (a_fs_file->name != NULL) {
a_fs_file->name->meta_addr = a_fs_meta->addr;
}
/* TODO @@@ could fill in name2 with this entry's name and parent inode
from Catalog entry */
/* set the link string (if the file is a link)
* The size check is a sanity check so that we don't try to allocate
* a huge amount of memory for a bad inode value
*/
if ((a_fs_meta->type == TSK_FS_META_TYPE_LNK) &&
(a_fs_meta->size >= 0) && (a_fs_meta->size < HFS_MAXPATHLEN)) {
ssize_t bytes_read;
a_fs_meta->link = tsk_malloc((size_t) a_fs_meta->size + 1);
if (a_fs_meta->link == NULL)
return 1;
bytes_read = tsk_fs_file_read(a_fs_file, (TSK_OFF_T) 0,
a_fs_meta->link, (size_t) a_fs_meta->size,
TSK_FS_FILE_READ_FLAG_NONE);
a_fs_meta->link[a_fs_meta->size] = '\0';
if (bytes_read != a_fs_meta->size) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_dinode_copy: failed to read contents of symbolic link; "
"expected %u bytes but tsk_fs_file_read() returned %u\n",
a_fs_meta->size, bytes_read);
free(a_fs_meta->link);
a_fs_meta->link = NULL;
return 1;
}
}
return 0;
}
/** \internal
* Load a catalog file entry and save it in the TSK_FS_FILE structure.
*
* @param fs File system to read from.
* @param a_fs_file Structure to read into.
* @param inum File address to load
* @returns 1 on error
*/
static uint8_t
hfs_inode_lookup(TSK_FS_INFO * fs, TSK_FS_FILE * a_fs_file,
TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
HFS_ENTRY entry;
if (a_fs_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("hfs_inode_lookup: fs_file is NULL");
return 1;
}
if (a_fs_file->meta == NULL) {
a_fs_file->meta = tsk_fs_meta_alloc(HFS_FILE_CONTENT_LEN);
}
if (a_fs_file->meta == NULL) {
return 1;
}
else {
tsk_fs_meta_reset(a_fs_file->meta);
}
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_inode_lookup: looking up %" PRIuINUM "\n",
inum);
// @@@ Will need to add orphan stuff here too
/* First see if this is a special entry
* the special ones have their metadata stored in the volume header */
if (inum == HFS_EXTENTS_FILE_ID) {
if (!hfs->has_extents_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Extents File not present");
return 1;
}
return hfs_make_extents(hfs, a_fs_file);
}
else if (inum == HFS_CATALOG_FILE_ID) {
return hfs_make_catalog(hfs, a_fs_file);
}
else if (inum == HFS_BAD_BLOCK_FILE_ID) {
// Note: the Extents file and the BadBlocks file are really the same.
if (!hfs->has_extents_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"BadBlocks File not present");
return 1;
}
return hfs_make_badblockfile(hfs, a_fs_file);
}
else if (inum == HFS_ALLOCATION_FILE_ID) {
return hfs_make_blockmap(hfs, a_fs_file);
}
else if (inum == HFS_STARTUP_FILE_ID) {
if (!hfs->has_startup_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Startup File not present");
return 1;
}
return hfs_make_startfile(hfs, a_fs_file);
}
else if (inum == HFS_ATTRIBUTES_FILE_ID) {
if (!hfs->has_attributes_file) {
error_detected(TSK_ERR_FS_INODE_NUM,
"Attributes File not present");
return 1;
}
return hfs_make_attrfile(hfs, a_fs_file);
}
/* Lookup inode and store it in the HFS structure */
if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE)) {
return 1;
}
/* Copy the structure in hfs to generic fs_inode */
if (hfs_dinode_copy(hfs, &entry, a_fs_file)) {
return 1;
}
/* If this is potentially a compressed file, its
* actual size is unknown until we examine the
* extended attributes */
if ((a_fs_file->meta->size == 0) &&
(a_fs_file->meta->type == TSK_FS_META_TYPE_REG) &&
(a_fs_file->meta->attr_state != TSK_FS_META_ATTR_ERROR) &&
((a_fs_file->meta->attr_state != TSK_FS_META_ATTR_STUDIED) ||
(a_fs_file->meta->attr == NULL))) {
hfs_load_attrs(a_fs_file);
}
return 0;
}
typedef struct {
uint32_t offset;
uint32_t length;
} CMP_OFFSET_ENTRY;
/**
* \internal
* Reads the ZLIB compression block table from the attribute.
*
* @param rAtttr the attribute to read
* @param offsetTableOut block table
* @param tableSizeOut size of block table
* @param tableOffsetOut the offset of the block table in the resource fork
* @return 1 on success, 0 on error
*/
static int
hfs_read_zlib_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) {
ssize_t attrReadResult;
hfs_resource_fork_header rfHeader;
uint32_t dataOffset;
uint32_t offsetTableOffset;
char fourBytes[4]; // Size of the offset table, little endian
uint32_t tableSize; // Size of the offset table
char *offsetTableData = NULL;
CMP_OFFSET_ENTRY *offsetTable = NULL;
size_t indx;
// Read the resource fork header
attrReadResult = tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader,
sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != sizeof(hfs_resource_fork_header)) {
error_returned
(" %s: trying to read the resource fork header", __func__);
return 0;
}
// Begin to parse the resource fork. For now, we just need the data offset.
dataOffset = tsk_getu32(TSK_BIG_ENDIAN, rfHeader.dataOffset);
// The resource's data begins with an offset table, which defines blocks
// of (optionally) zlib-compressed data (so that the OS can do file seeks
// efficiently; each uncompressed block is 64KB).
offsetTableOffset = dataOffset + 4;
// read 4 bytes, the number of table entries, little endian
attrReadResult =
tsk_fs_attr_read(rAttr, offsetTableOffset, fourBytes, 4,
TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != 4) {
error_returned
(" %s: trying to read the offset table size, "
"return value of %u should have been 4", __func__, attrReadResult);
return 0;
}
tableSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes);
// Each table entry is 8 bytes long
offsetTableData = tsk_malloc(tableSize * 8);
if (offsetTableData == NULL) {
error_returned
(" %s: space for the offset table raw data", __func__);
return 0;
}
offsetTable =
(CMP_OFFSET_ENTRY *) tsk_malloc(tableSize *
sizeof(CMP_OFFSET_ENTRY));
if (offsetTable == NULL) {
error_returned
(" %s: space for the offset table", __func__);
goto on_error;
}
attrReadResult = tsk_fs_attr_read(rAttr, offsetTableOffset + 4,
offsetTableData, tableSize * 8, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) tableSize * 8) {
error_returned
(" %s: reading in the compression offset table, "
"return value %u should have been %u", __func__, attrReadResult,
tableSize * 8);
goto on_error;
}
for (indx = 0; indx < tableSize; ++indx) {
offsetTable[indx].offset =
tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8);
offsetTable[indx].length =
tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8 + 4);
}
free(offsetTableData);
*offsetTableOut = offsetTable;
*tableSizeOut = tableSize;
*tableOffsetOut = offsetTableOffset;
return 1;
on_error:
free(offsetTable);
free(offsetTableData);
return 0;
}
/**
* \internal
* Reads the LZVN compression block table from the attribute.
*
* @param rAtttr the attribute to read
* @param offsetTableOut block table
* @param tableSizeOut size of block table
* @param tableOffsetOut the offset of the block table in the resource fork
* @return 1 on success, 0 on error
*/
static int
hfs_read_lzvn_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) {
ssize_t attrReadResult;
char fourBytes[4];
uint32_t tableDataSize;
uint32_t tableSize; // Size of the offset table
char *offsetTableData = NULL;
CMP_OFFSET_ENTRY *offsetTable = NULL;
// The offset table is a sequence of 4-byte offsets of compressed
// blocks. The first 4 bytes is thus the offset of the first block,
// but also 4 times the number of entries in the table.
attrReadResult = tsk_fs_attr_read(rAttr, 0, fourBytes, 4,
TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != 4) {
error_returned
(" %s: trying to read the offset table size, "
"return value of %u should have been 4", __func__, attrReadResult);
return 0;
}
tableDataSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes);
offsetTableData = tsk_malloc(tableDataSize);
if (offsetTableData == NULL) {
error_returned
(" %s: space for the offset table raw data", __func__);
return 0;
}
// table entries are 4 bytes, last entry is end of data
tableSize = tableDataSize / 4 - 1;
offsetTable =
(CMP_OFFSET_ENTRY *) tsk_malloc(tableSize *
sizeof(CMP_OFFSET_ENTRY));
if (offsetTable == NULL) {
error_returned
(" %s: space for the offset table", __func__);
goto on_error;
}
attrReadResult = tsk_fs_attr_read(rAttr, 0,
offsetTableData, tableDataSize, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) tableDataSize) {
error_returned
(" %s: reading in the compression offset table, "
"return value %u should have been %u", __func__, attrReadResult,
tableDataSize);
goto on_error;
}
uint32_t a = tableDataSize;
uint32_t b;
size_t i;
for (i = 0; i < tableSize; ++i) {
b = tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + 4*(i+1));
offsetTable[i].offset = a;
offsetTable[i].length = b - a;
a = b;
}
free(offsetTableData);
*offsetTableOut = offsetTable;
*tableSizeOut = tableSize;
*tableOffsetOut = 0;
return 1;
on_error:
free(offsetTable);
free(offsetTableData);
return 0;
}
/**
* \internal
* "Decompress" a block which was stored uncompressed.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_noncompressed_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) {
// actually an uncompressed block of data; just copy
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Copying an uncompressed compression unit\n", __func__);
if ((len - 1) > COMPRESSION_UNIT_SIZE) {
error_detected(TSK_ERR_FS_READ,
"%s: uncompressed block length %u is longer "
"than compression unit size %u", __func__, len - 1,
COMPRESSION_UNIT_SIZE);
return 0;
}
memcpy(uncBuf, rawBuf + 1, len - 1);
*uncLen = len - 1;
return 1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Decompress a block which was stored with ZLIB.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_zlib_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)
{
// see if this block is compressed
if (len > 0 && (rawBuf[0] & 0x0F) != 0x0F) {
// Uncompress the chunk of data
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Inflating the compression unit\n", __func__);
unsigned long bytesConsumed;
int infResult = zlib_inflate(rawBuf, (uint64_t) len,
uncBuf, (uint64_t) COMPRESSION_UNIT_SIZE,
uncLen, &bytesConsumed);
if (infResult != 0) {
error_returned
(" %s: zlib inflation (uncompression) failed",
__func__, infResult);
return 0;
}
if (bytesConsumed != len) {
error_detected(TSK_ERR_FS_READ,
" %s, decompressor did not consume the whole compressed data",
__func__);
return 0;
}
return 1;
}
else {
// actually an uncompressed block of data; just copy
return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen);
}
}
#endif
/**
* \internal
* Decompress a block which was stored with LZVN.
*
* @param rawBuf the compressed data
* @param len length of the compressed data
* @param uncBuf the decompressed data
* @param uncLen length of the decompressed data
* @return 1 on success, 0 on error
*/
static int hfs_decompress_lzvn_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)
{
// see if this block is compressed
if (len > 0 && rawBuf[0] != 0x06) {
*uncLen = lzvn_decode_buffer(uncBuf, COMPRESSION_UNIT_SIZE, rawBuf, len);
return 1; // apparently this can't fail
}
else {
// actually an uncompressed block of data; just copy
return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen);
}
}
/**
* \internal
* Decompress a block.
*
* @param rAttr the attribute to read
* @param rawBuf the compressed data
* @param uncBuf the decompressed data
* @param offsetTable table of compressed block offsets
* @param offsetTableSize size of table of compressed block offsets
* @param offsetTableOffset offset of table of compressed block offsets
* @param indx index of block to read
* @param decompress_block pointer to decompression function
* @return decompressed size on success, -1 on error
*/
static ssize_t read_and_decompress_block(
const TSK_FS_ATTR* rAttr,
char* rawBuf,
char* uncBuf,
const CMP_OFFSET_ENTRY* offsetTable,
uint32_t offsetTableSize,
uint32_t offsetTableOffset,
size_t indx,
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen)
)
{
// @@@ BC: Looks like we should have bounds checks that indx < offsetTableSize, but we should confirm
ssize_t attrReadResult;
uint32_t offset = offsetTableOffset + offsetTable[indx].offset;
uint32_t len = offsetTable[indx].length;
uint64_t uncLen;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Reading compression unit %d, length %d\n",
__func__, indx, len);
/* Github #383 referenced that if len is 0, then the below code causes
* problems. Added this check, but I don't have data to verify this on.
* it looks like it should at least not crash, but it isn't clear if it
* will also do the right thing and if should actually break here
* instead. */
if (len == 0) {
return 0;
}
if (len > COMPRESSION_UNIT_SIZE + 1) {
error_detected(TSK_ERR_FS_READ,
"%s: block size is too large: %u", __func__, len);
return -1;
}
// Read in the block of compressed data
attrReadResult = tsk_fs_attr_read(rAttr, offset,
rawBuf, len, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult != (ssize_t) len) {
char msg[] =
"%s%s: reading in the compression offset table, "
"return value %u should have been %u";
if (attrReadResult < 0 ) {
error_returned(msg, " ", __func__, attrReadResult, len);
}
else {
error_detected(TSK_ERR_FS_READ, "", __func__, attrReadResult, len);
}
return -1;
}
if (!decompress_block(rawBuf, len, uncBuf, &uncLen)) {
return -1;
}
// If size is a multiple of COMPRESSION_UNIT_SIZE,
// expected uncompressed length is COMPRESSION_UNIT_SIZE
const uint32_t expUncLen = indx == offsetTableSize - 1 ?
((rAttr->fs_file->meta->size - 1) % COMPRESSION_UNIT_SIZE) + 1 :
COMPRESSION_UNIT_SIZE;
if (uncLen != expUncLen) {
error_detected(TSK_ERR_FS_READ,
"%s: compressed block decompressed to %u bytes, "
"should have been %u bytes", __func__, uncLen, expUncLen);
return -1;
}
// There are now uncLen bytes of uncompressed data available from
// this comp unit.
return (ssize_t)uncLen;
}
/**
* \internal
* Attr walk callback function for compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @param read_block_table pointer to block table read function
* @param decompress_block pointer to decompression function
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_compressed_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr,
int (*read_block_table)(const TSK_FS_ATTR *rAttr,
CMP_OFFSET_ENTRY** offsetTableOut,
uint32_t* tableSizeOut,
uint32_t* tableOffsetOut),
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen))
{
TSK_FS_INFO *fs;
TSK_FS_FILE *fs_file;
const TSK_FS_ATTR *rAttr; // resource fork attribute
char *rawBuf = NULL; // compressed data
char *uncBuf = NULL; // uncompressed data
uint32_t offsetTableOffset;
uint32_t offsetTableSize; // The number of table entries
CMP_OFFSET_ENTRY *offsetTable = NULL;
size_t indx; // index for looping over the offset table
TSK_OFF_T off = 0; // the offset in the uncompressed data stream consumed thus far
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Entered, because this is a compressed file with compressed data in the resource fork\n", __func__);
// clean up any error messages that are lying around
tsk_error_reset();
if ((fs_attr == NULL) || (fs_attr->fs_file == NULL)
|| (fs_attr->fs_file->meta == NULL)
|| (fs_attr->fs_file->fs_info == NULL)) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("%s: Null arguments given\n", __func__);
return 1;
}
// Check that the ATTR being read is the main DATA resource, 128-0,
// because this is the only one that can be compressed in HFS+
if ((fs_attr->id != HFS_FS_ATTR_ID_DATA) ||
(fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) {
error_detected(TSK_ERR_FS_ARG,
"%s: arg specified an attribute %u-%u that is not the data fork, "
"Only the data fork can be compressed.", __func__, fs_attr->type,
fs_attr->id);
return 1;
}
/* This MUST be a compressed attribute */
if (!(fs_attr->flags & TSK_FS_ATTR_COMP)) {
error_detected(TSK_ERR_FS_FWALK,
"%s: called with non-special attribute: %x",
__func__, fs_attr->flags);
return 1;
}
fs = fs_attr->fs_file->fs_info;
fs_file = fs_attr->fs_file;
/******** Open the Resource Fork ***********/
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
(" %s: could not get the attribute for the resource fork of the file", __func__);
return 1;
}
// read the offset table from the fork header
if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) {
return 1;
}
// Allocate two buffers for the raw and uncompressed data
/* Raw data can be COMPRESSION_UNIT_SIZE+1 if the data is not
* compressed and there is a 1-byte flag that indicates that
* the data is not compressed. */
rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1);
if (rawBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE);
if (uncBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
// FOR entry in the table DO
for (indx = 0; indx < offsetTableSize; ++indx) {
ssize_t uncLen; // uncompressed length
unsigned int blockSize;
uint64_t lumpSize;
uint64_t remaining;
char *lumpStart;
switch ((uncLen = read_and_decompress_block(
rAttr, rawBuf, uncBuf,
offsetTable, offsetTableSize, offsetTableOffset, indx,
decompress_block)))
{
case -1:
goto on_error;
case 0:
continue;
default:
break;
}
// Call the a_action callback with "Lumps"
// that are at most the block size.
blockSize = fs->block_size;
remaining = uncLen;
lumpStart = uncBuf;
while (remaining > 0) {
int retval; // action return value
lumpSize = remaining <= blockSize ? remaining : blockSize;
// Apply the callback function
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Calling action on lump of size %"
PRIu64 " offset %" PRIu64 " in the compression unit\n",
__func__, lumpSize, uncLen - remaining);
if (lumpSize > SIZE_MAX) {
error_detected(TSK_ERR_FS_FWALK,
" %s: lumpSize is too large for the action", __func__);
goto on_error;
}
retval = a_action(fs_attr->fs_file, off, 0, lumpStart,
(size_t) lumpSize, // cast OK because of above test
TSK_FS_BLOCK_FLAG_COMP, ptr);
if (retval == TSK_WALK_ERROR) {
error_detected(TSK_ERR_FS | 201,
"%s: callback returned an error", __func__);
goto on_error;
}
else if (retval == TSK_WALK_STOP) {
break;
}
// Find the next lump
off += lumpSize;
remaining -= lumpSize;
lumpStart += lumpSize;
}
}
// Done, so free up the allocated resources.
free(offsetTable);
free(rawBuf);
free(uncBuf);
return 0;
on_error:
free(offsetTable);
free(rawBuf);
free(uncBuf);
return 1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Attr walk callback function for ZLIB compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_zlib_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr)
{
return hfs_attr_walk_compressed_rsrc(
fs_attr, flags, a_action, ptr,
hfs_read_zlib_block_table,
hfs_decompress_zlib_block
);
}
#endif
/**
* \internal
* Attr walk callback function for LZVN compressed resources
*
* @param fs_attr the attribute to read
* @param flags
* @param a_action action callback
* @param ptr context for the action callback
* @return 0 on success, 1 on error
*/
static uint8_t
hfs_attr_walk_lzvn_rsrc(const TSK_FS_ATTR * fs_attr,
int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr)
{
return hfs_attr_walk_compressed_rsrc(
fs_attr, flags, a_action, ptr,
hfs_read_lzvn_block_table,
hfs_decompress_lzvn_block
);
}
/**
* \internal
* Read a compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @param read_block_table pointer to block table read function
* @param decompress_block pointer to decompression function
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_compressed_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len,
int (*read_block_table)(const TSK_FS_ATTR *rAttr,
CMP_OFFSET_ENTRY** offsetTableOut,
uint32_t* tableSizeOut,
uint32_t* tableOffsetOut),
int (*decompress_block)(char* rawBuf,
uint32_t len,
char* uncBuf,
uint64_t* uncLen))
{
TSK_FS_FILE *fs_file;
const TSK_FS_ATTR *rAttr;
char *rawBuf = NULL;
char *uncBuf = NULL;
uint32_t offsetTableOffset;
uint32_t offsetTableSize; // Size of the offset table
CMP_OFFSET_ENTRY *offsetTable = NULL;
TSK_OFF_T indx; // index for looping over the offset table
TSK_OFF_T startUnit = 0;
uint32_t startUnitOffset = 0;
TSK_OFF_T endUnit = 0;
uint64_t bytesCopied;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: called because this file is compressed, with data in the resource fork\n", __func__);
// Reading zero bytes? OK at any offset, I say!
if (a_len == 0)
return 0;
if (a_offset < 0) {
error_detected(TSK_ERR_FS_ARG,
"%s: reading from file at a negative offset",
__func__);
return -1;
}
if (a_len > SIZE_MAX / 2) {
error_detected(TSK_ERR_FS_ARG,
"%s: trying to read more than SIZE_MAX/2 is not supported.",
__func__);
return -1;
}
if ((a_fs_attr == NULL) || (a_fs_attr->fs_file == NULL)
|| (a_fs_attr->fs_file->meta == NULL)
|| (a_fs_attr->fs_file->fs_info == NULL)) {
error_detected(TSK_ERR_FS_ARG,
"%s: NULL parameters passed", __func__);
return -1;
}
// This should be a compressed file. If not, that's an error!
if (!(a_fs_attr->flags & TSK_FS_ATTR_COMP)) {
error_detected(TSK_ERR_FS_ARG,
"%s: called with non-special attribute: %x",
__func__, a_fs_attr->flags);
return -1;
}
// Check that the ATTR being read is the main DATA resource, 4352-0,
// because this is the only one that can be compressed in HFS+
if ((a_fs_attr->id != HFS_FS_ATTR_ID_DATA) ||
(a_fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) {
error_detected(TSK_ERR_FS_ARG,
"%s: arg specified an attribute %u-%u that is not the data fork, "
"Only the data fork can be compressed.", __func__,
a_fs_attr->type, a_fs_attr->id);
return -1;
}
/******** Open the Resource Fork ***********/
// The file
fs_file = a_fs_attr->fs_file;
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
(" %s: could not get the attribute for the resource fork of the file", __func__);
return -1;
}
// read the offset table from the fork header
if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) {
return -1;
}
// Compute the range of compression units needed for the request
startUnit = a_offset / COMPRESSION_UNIT_SIZE;
startUnitOffset = a_offset % COMPRESSION_UNIT_SIZE;
endUnit = (a_offset + a_len - 1) / COMPRESSION_UNIT_SIZE;
if (startUnit >= offsetTableSize || endUnit >= offsetTableSize) {
error_detected(TSK_ERR_FS_ARG,
"%s: range of bytes requested %lld - %lld falls past the "
"end of the uncompressed stream %llu\n",
__func__, a_offset, a_offset + a_len,
offsetTable[offsetTableSize-1].offset +
offsetTable[offsetTableSize-1].length);
goto on_error;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: reading compression units: %" PRIuOFF
" to %" PRIuOFF "\n", __func__, startUnit, endUnit);
bytesCopied = 0;
// Allocate buffers for the raw and uncompressed data
/* Raw data can be COMPRESSION_UNIT_SIZE+1 if the zlib data is not
* compressed and there is a 1-byte flag that indicates that
* the data is not compressed. */
rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1);
if (rawBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE);
if (uncBuf == NULL) {
error_returned
(" %s: buffers for reading and uncompressing", __func__);
goto on_error;
}
// Read from the indicated comp units
for (indx = startUnit; indx <= endUnit; ++indx) {
uint64_t uncLen;
char *uncBufPtr = uncBuf;
size_t bytesToCopy;
switch ((uncLen = read_and_decompress_block(
rAttr, rawBuf, uncBuf,
offsetTable, offsetTableSize, offsetTableOffset, (size_t)indx,
decompress_block)))
{
case -1:
goto on_error;
case 0:
continue;
default:
break;
}
// If this is the first comp unit, then we must skip over the
// startUnitOffset bytes.
if (indx == startUnit) {
uncLen -= startUnitOffset;
uncBufPtr += startUnitOffset;
}
// How many bytes to copy from this compression unit?
if (bytesCopied + uncLen < (uint64_t) a_len) // cast OK because a_len > 0
bytesToCopy = (size_t) uncLen; // uncLen <= size of compression unit, which is small, so cast is OK
else
bytesToCopy = (size_t) (((uint64_t) a_len) - bytesCopied); // diff <= compression unit size, so cast is OK
// Copy into the output buffer, and update bookkeeping.
memcpy(a_buf + bytesCopied, uncBufPtr, bytesToCopy);
bytesCopied += bytesToCopy;
}
// Well, we don't know (without a lot of work) what the
// true uncompressed size of the stream is. All we know is the "upper bound" which
// assumes that all of the compression units expand to their full size. If we did
// know the true size, then we could reject requests that go beyond the end of the
// stream. Instead, we treat the stream as if it is padded out to the full size of
// the last compression unit with zeros.
// Have we read and copied all of the bytes requested?
if (bytesCopied < a_len) {
// set the remaining bytes to zero
memset(a_buf + bytesCopied, 0, a_len - (size_t) bytesCopied); // cast OK because diff must be < compression unit size
}
free(offsetTable);
free(rawBuf);
free(uncBuf);
return (ssize_t) bytesCopied; // cast OK, cannot be greater than a_len which cannot be greater than SIZE_MAX/2 (rounded down).
on_error:
free(offsetTable);
free(rawBuf);
free(uncBuf);
return -1;
}
#ifdef HAVE_LIBZ
/**
* \internal
* Read a ZLIB compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_zlib_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len)
{
return hfs_file_read_compressed_rsrc(
a_fs_attr, a_offset, a_buf, a_len,
hfs_read_zlib_block_table,
hfs_decompress_zlib_block
);
}
#endif
/**
* \internal
* Read an LZVN compressed resource
*
* @param fs_attr the attribute to read
* @param a_offset the offset from which to read
* @param a_buf the buffer into which to read
* @param a_len the length of the buffer
* @return number of bytes read or -1 on error (incl if offset is past EOF)
*/
static ssize_t
hfs_file_read_lzvn_rsrc(const TSK_FS_ATTR * a_fs_attr,
TSK_OFF_T a_offset, char *a_buf, size_t a_len)
{
return hfs_file_read_compressed_rsrc(
a_fs_attr, a_offset, a_buf, a_len,
hfs_read_lzvn_block_table,
hfs_decompress_lzvn_block
);
}
/**
* \internal
* "Decompress" an uncompressed attr
*
* HFS+ compression schemes allow for some blocks to be stored uncompressed.
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1
*/
static int hfs_decompress_noncompressed_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) {
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Leading byte, 0x%02x, indicates that the data is not really compressed.\n"
"%s: Loading the default DATA attribute.", __func__, rawBuf[0], __func__);
*dstBuf = rawBuf + 1; // + 1 indicator byte
*dstSize = uncSize;
*dstBufFree = FALSE;
return 1;
}
/**
* \internal
* Decompress a ZLIB compressed attr
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1 on success, 0 on error
*/
static int hfs_decompress_zlib_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree)
{
// ZLIB blocks cannot start with 0xF as the low nibble, so that's used
// as the flag for noncompressed blocks
if ((rawBuf[0] & 0x0F) == 0x0F) {
return hfs_decompress_noncompressed_attr(
rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree);
}
else {
#ifdef HAVE_LIBZ
char* uncBuf = NULL;
uint64_t uLen;
unsigned long bytesConsumed;
int infResult;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Uncompressing (inflating) data.", __func__);
// Uncompress the remainder of the attribute, and load as 128-0
// Note: cast is OK because uncSize will be quite modest, < 4000.
uncBuf = (char *) tsk_malloc((size_t) uncSize + 100); // add some extra space
if (uncBuf == NULL) {
error_returned
(" - %s, space for the uncompressed attr", __func__);
return 0;
}
infResult = zlib_inflate(rawBuf, (uint64_t) rawSize,
uncBuf, (uint64_t) (uncSize + 100),
&uLen, &bytesConsumed);
if (infResult != 0) {
error_returned
(" %s, zlib could not uncompress attr", __func__);
free(uncBuf);
return 0;
}
if (bytesConsumed != rawSize) {
error_detected(TSK_ERR_FS_READ,
" %s, decompressor did not consume the whole compressed data",
__func__);
free(uncBuf);
return 0;
}
*dstBuf = uncBuf;
*dstSize = uncSize;
*dstBufFree = TRUE;
#else
// ZLIB compression library is not available, so we will load a
// zero-length default DATA attribute. Without this, icat may
// misbehave.
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: ZLIB not available, so loading an empty default DATA attribute.\n", __func__);
// Dummy is one byte long, so the ptr is not null, but we set the
// length to zero bytes, so it is never read.
static uint8_t dummy[1];
*dstBuf = dummy;
*dstSize = 0;
*dstBufFree = FALSE;
#endif
}
return 1;
}
/**
* \internal
* Decompress an LZVN compressed attr
*
* @param rawBuf source buffer
* @param rawSize size of source buffer
* @param uncSize expected uncompressed size
* @param dstBuf destination buffer
* @param dstSize size of destination buffer
* @param dstBufFree true iff the caller must free the destination buffer
* @return 1 on success, 0 on error
*/
static int hfs_decompress_lzvn_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree)
{
// LZVN blocks cannot start with 0x06, so that's used as the flag for
// noncompressed blocks
if (rawBuf[0] == 0x06) {
return hfs_decompress_noncompressed_attr(
rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree);
}
char* uncBuf = (char *) tsk_malloc((size_t) uncSize);
*dstSize = lzvn_decode_buffer(uncBuf, uncSize, rawBuf, rawSize);
*dstBuf = uncBuf;
*dstBufFree = TRUE;
return 1;
}
/**
* \internal
* Read a compressed attr
*
* @param fs_file the file
* @param cmpType compression type
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @param decompress_attr pointer to the decompression function
* @return 1 on success, 0 on error
*/
static int
hfs_file_read_compressed_attr(TSK_FS_FILE* fs_file,
uint8_t cmpType,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize,
int (*decompress_attr)(char* rawBuf,
uint32_t rawSize,
uint64_t uncSize,
char** dstBuf,
uint64_t* dstSize,
int* dstBufFree))
{
// Data is inline. We will load the uncompressed data as a
// resident attribute.
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Compressed data is inline in the attribute, will load this as the default DATA attribute.\n", __func__);
if (attributeLength <= 16) {
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: WARNING, Compression Record of type %u is not followed by"
" compressed data. No data will be loaded into the DATA"
" attribute.\n", __func__, cmpType);
// oddly, this is not actually considered an error
return 1;
}
TSK_FS_ATTR *fs_attr_unc;
// There is data following the compression record, as there should be.
if ((fs_attr_unc = tsk_fs_attrlist_getnew(
fs_file->meta->attr, TSK_FS_ATTR_RES)) == NULL)
{
error_returned(" - %s, FS_ATTR for uncompressed data", __func__);
return 0;
}
char* dstBuf;
uint64_t dstSize;
int dstBufFree = FALSE;
if (!decompress_attr(buffer + 16, attributeLength - 16, uncSize,
&dstBuf, &dstSize, &dstBufFree)) {
return 0;
}
if (dstSize != uncSize) {
error_detected(TSK_ERR_FS_READ,
" %s, actual uncompressed size not equal to the size in the compression record", __func__);
goto on_error;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Loading decompressed data as default DATA attribute.",
__func__);
// Load the remainder of the attribute as 128-0
// set the details in the fs_attr structure.
// Note, we are loading this as a RESIDENT attribute.
if (tsk_fs_attr_set_str(fs_file,
fs_attr_unc, "DATA",
TSK_FS_ATTR_TYPE_HFS_DATA,
HFS_FS_ATTR_ID_DATA, dstBuf,
dstSize))
{
error_returned(" - %s", __func__);
goto on_error;
}
if (dstBufFree) {
free(dstBuf);
}
return 1;
on_error:
if (dstBufFree) {
free(dstBuf);
}
return 0;
}
/**
* \internal
* Read a ZLIB compressed attr
*
* @param fs_file the file
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @return 1 on success, 0 on error
*/
static int hfs_file_read_zlib_attr(TSK_FS_FILE* fs_file,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize)
{
return hfs_file_read_compressed_attr(
fs_file, DECMPFS_TYPE_ZLIB_ATTR,
buffer, attributeLength, uncSize,
hfs_decompress_zlib_attr
);
}
/**
* \internal
* Read an LZVN compressed attr
*
* @param fs_file the file
* @param buffer destination buffer
* @param attributeLength length of the attribute
* @param uncSize uncompressed size
* @return 1 on success, 0 on error
*/
static int hfs_file_read_lzvn_attr(TSK_FS_FILE* fs_file,
char* buffer,
uint32_t attributeLength,
uint64_t uncSize)
{
return hfs_file_read_compressed_attr(
fs_file, DECMPFS_TYPE_LZVN_ATTR,
buffer, attributeLength, uncSize,
hfs_decompress_lzvn_attr
);
}
typedef struct {
TSK_FS_INFO *fs; // the HFS file system
TSK_FS_FILE *file; // the Attributes file, if open
hfs_btree_header_record *header; // the Attributes btree header record.
// For Convenience, unpacked values.
TSK_ENDIAN_ENUM endian;
uint32_t rootNode;
uint16_t nodeSize;
uint16_t maxKeyLen;
} ATTR_FILE_T;
/** \internal
* Open the Attributes file, and read the btree header record. Fill in the fields of the ATTR_FILE_T struct.
*
* @param fs -- the HFS file system
* @param header -- the header record struct
*
* @return 1 on error, 0 on success
*/
static uint8_t
open_attr_file(TSK_FS_INFO * fs, ATTR_FILE_T * attr_file)
{
ssize_t cnt; // will hold bytes read
hfs_btree_header_record *hrec;
// clean up any error messages that are lying around
tsk_error_reset();
if (fs == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("open_attr_file: fs is NULL");
return 1;
}
if (attr_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("open_attr_file: attr_file is NULL");
return 1;
}
// Open the Attributes File
attr_file->file =
tsk_fs_file_open_meta(fs, NULL, HFS_ATTRIBUTES_FILE_ID);
if (attr_file->file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr
("open_attr_file: could not open the Attributes file");
return 1;
}
// Allocate some space for the Attributes btree header record (which
// is passed back to the caller)
hrec = (hfs_btree_header_record *)
malloc(sizeof(hfs_btree_header_record));
if (hrec == NULL) {
tsk_error_set_errno(TSK_ERR_FS);
tsk_error_set_errstr
("open_attr_file: could not malloc space for Attributes header record");
return 1;
}
// Read the btree header record
cnt = tsk_fs_file_read(attr_file->file,
14,
(char *) hrec,
sizeof(hfs_btree_header_record), (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)sizeof(hfs_btree_header_record)) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr
("open_attr_file: could not open the Attributes file");
tsk_fs_file_close(attr_file->file);
free(hrec);
return 1;
}
// Fill in the fields of the attr_file struct (which was passed in by the caller)
attr_file->fs = fs;
attr_file->header = hrec;
attr_file->endian = fs->endian;
attr_file->nodeSize = tsk_getu16(attr_file->endian, hrec->nodesize);
attr_file->rootNode = tsk_getu32(attr_file->endian, hrec->rootNode);
attr_file->maxKeyLen = tsk_getu16(attr_file->endian, hrec->maxKeyLen);
return 0;
}
/** \internal
* Closes and frees the data structures associated with ATTR_FILE_T
*/
static uint8_t
close_attr_file(ATTR_FILE_T * attr_file)
{
if (attr_file == NULL) {
tsk_error_set_errno(TSK_ERR_FS_READ);
tsk_error_set_errstr("close_attr_file: NULL attr_file arg");
return 1;
}
if (attr_file->file != NULL) {
tsk_fs_file_close(attr_file->file);
attr_file->file = NULL;
}
free(attr_file->header);
attr_file->header = NULL;
attr_file->rootNode = 0;
attr_file->nodeSize = 0;
// Note that we leave the fs component alone.
return 0;
}
static const char *
hfs_attrTypeName(uint32_t typeNum)
{
switch (typeNum) {
case TSK_FS_ATTR_TYPE_HFS_DEFAULT:
return "DFLT";
case TSK_FS_ATTR_TYPE_HFS_DATA:
return "DATA";
case TSK_FS_ATTR_TYPE_HFS_EXT_ATTR:
return "ExATTR";
case TSK_FS_ATTR_TYPE_HFS_COMP_REC:
return "CMPF";
case TSK_FS_ATTR_TYPE_HFS_RSRC:
return "RSRC";
default:
return "UNKN";
}
}
// TODO: Function description missing here no idea what it is supposed to return
// in which circumstances.
static uint8_t
hfs_load_extended_attrs(TSK_FS_FILE * fs_file,
unsigned char *isCompressed, unsigned char *cmpType,
uint64_t *uncompressedSize)
{
TSK_FS_INFO *fs = fs_file->fs_info;
uint64_t fileID;
ATTR_FILE_T attrFile;
uint8_t *nodeData;
TSK_ENDIAN_ENUM endian;
hfs_btree_node *nodeDescriptor; // The node descriptor
uint32_t nodeID; // The number or ID of the Attributes file node to read.
hfs_btree_key_attr *keyB; // ptr to the key of the Attr file record.
unsigned char done; // Flag to indicate that we are done looping over leaf nodes
uint16_t attribute_counter = 2; // The ID of the next attribute to be loaded.
HFS_INFO *hfs;
char *buffer = NULL; // buffer to hold the attribute
TSK_LIST *nodeIDs_processed = NULL; // Keep track of node IDs to prevent an infinite loop
ssize_t cnt; // count of chars read from file.
tsk_error_reset();
// The CNID (or inode number) of the file
// Note that in TSK such numbers are 64 bits, but in HFS+ they are only 32 bits.
fileID = fs_file->meta->addr;
if (fs == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_load_extended_attrs: NULL fs arg");
return 1;
}
hfs = (HFS_INFO *) fs;
if (!hfs->has_attributes_file) {
// No attributes file, and so, no extended attributes
return 0;
}
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Processing file %" PRIuINUM "\n",
fileID);
}
// Open the Attributes File
if (open_attr_file(fs, &attrFile)) {
error_returned
("hfs_load_extended_attrs: could not open Attributes file");
return 1;
}
// Is the Attributes file empty?
if (attrFile.rootNode == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Attributes file is empty\n");
close_attr_file(&attrFile);
*isCompressed = FALSE;
*cmpType = 0;
return 0;
}
// A place to hold one node worth of data
nodeData = (uint8_t *) malloc(attrFile.nodeSize);
if (nodeData == NULL) {
error_detected(TSK_ERR_AUX_MALLOC,
"hfs_load_extended_attrs: Could not malloc space for an Attributes file node");
goto on_error;
}
// Initialize these
*isCompressed = FALSE;
*cmpType = 0;
endian = attrFile.fs->endian;
// Start with the root node
nodeID = attrFile.rootNode;
// While loop, over nodes in path from root node to the correct LEAF node.
while (1) {
uint16_t numRec; // Number of records in the node
int recIndx; // index for looping over records
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Reading Attributes File node with ID %"
PRIu32 "\n", nodeID);
}
/* Make sure we do not get into an infinite loop */
if (tsk_list_find(nodeIDs_processed, nodeID)) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Infinite loop detected - trying to read node %" PRIu32 " which has already been processed", nodeID);
goto on_error;
}
/* Read the node */
cnt = tsk_fs_file_read(attrFile.file,
(TSK_OFF_T)nodeID * attrFile.nodeSize,
(char *) nodeData,
attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)attrFile.nodeSize) {
error_returned
("hfs_load_extended_attrs: Could not read in a node from the Attributes File");
goto on_error;
}
/* Save this node ID to the list of processed nodes */
if (tsk_list_add(&nodeIDs_processed, nodeID)) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Could not save nodeID to the list of processed nodes");
goto on_error;
}
/** Node has a:
* Descriptor
* Set of records
* Table at the end with pointers to the records
*/
// Parse the Node header
nodeDescriptor = (hfs_btree_node *) nodeData;
// If we are at a leaf node, then we have found the right node
if (nodeDescriptor->type == HFS_ATTR_NODE_LEAF) {
break;
}
// This had better be an INDEX node, if not its an error
else if (nodeDescriptor->type != HFS_ATTR_NODE_INDEX) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Reached a non-INDEX and non-LEAF node in searching the Attributes File");
goto on_error;
}
// OK, we are in an INDEX node. loop over the records to find the last one whose key is
// smaller than or equal to the desired key
numRec = tsk_getu16(endian, nodeDescriptor->num_rec);
if (numRec == 0) {
// This is wrong, there must always be at least 1 record in an INDEX node.
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs:Attributes File index node %"
PRIu32 " has zero records", nodeID);
goto on_error;
}
for (recIndx = 0; recIndx < numRec; ++recIndx) {
uint16_t keyLength;
int comp; // comparison result
char *compStr; // comparison result, as a string
uint8_t *recData; // pointer to the data part of the record
uint32_t keyFileID;
// The offset to the record is stored in table at end of node
uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is
uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry);
//uint8_t * nextRecOffsetData = &nodeData[attrFile.nodeSize - 2* (recIndx+2)];
// make sure the record and first fields are in the buffer
if (recOffset + 14 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute (offset too big)");
goto on_error;
}
// Pointer to first byte of record
uint8_t *recordBytes = &nodeData[recOffset];
// Cast that to the Attributes file key (n.b., the key is the first thing in the record)
keyB = (hfs_btree_key_attr *) recordBytes;
// Is this key less than what we are seeking?
//int comp = comp_attr_key(endian, keyB, fileID, attrName, startBlock);
keyFileID = tsk_getu32(endian, keyB->file_id);
if (keyFileID < fileID) {
comp = -1;
compStr = "less than";
}
else if (keyFileID > fileID) {
comp = 1;
compStr = "greater than";
}
else {
comp = 0;
compStr = "equal to";
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: INDEX record %d, fileID %"
PRIu32 " is %s the file ID we are seeking, %" PRIu32
".\n", recIndx, keyFileID, compStr, fileID);
if (comp > 0) {
// The key of this record is greater than what we are seeking
if (recIndx == 0) {
// This is the first record, so no records are appropriate
// Nothing in this btree will match. We can stop right here.
goto on_exit;
}
// This is not the first record, so, the previous record's child is the one we want.
break;
}
// CASE: key in this record matches the key we are seeking. The previous record's child
// is the one we want. However, if this is the first record, then we want THIS record's child.
if (comp == 0 && recIndx != 0) {
break;
}
// Extract the child node ID from the record data (stored after the key)
keyLength = tsk_getu16(endian, keyB->key_len);
// make sure the fields we care about are still in the buffer
// +2 is because key_len doesn't include its own length
// +4 is because of the amount of data we read from the data
if (recOffset + keyLength + 2 + 4 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
recData = &recordBytes[keyLength + 2];
// Data must start on an even offset from the beginning of the record.
// So, correct this if needed.
if ((recData - recordBytes) % 2) {
recData += 1;
}
// The next four bytes should be the Node ID of the child of this node.
nodeID = tsk_getu32(endian, recData);
// At this point, either comp<0 or comp=0 && recIndx=0. In the latter case we want to
// descend to the child of this node, so we break.
if (recIndx == 0 && comp == 0) {
break;
}
// CASE: key in this record is less than key we seek. comp < 0
// So, continue looping over records in this node.
} // END loop over records
} // END while loop over Nodes in path from root to LEAF node
// At this point nodeData holds the contents of a LEAF node with the right range of keys
// and nodeDescriptor points to the descriptor of that node.
// Loop over successive LEAF nodes, starting with this one
done = FALSE;
while (!done) {
uint16_t numRec; // number of records
unsigned int recIndx; // index for looping over records
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Attributes File LEAF Node %"
PRIu32 ".\n", nodeID);
numRec = tsk_getu16(endian, nodeDescriptor->num_rec);
// Note, leaf node could have one (or maybe zero) records
// Loop over the records in this node
for (recIndx = 0; recIndx < numRec; ++recIndx) {
// The offset to the record is stored in table at end of node
uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is
uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry);
int comp; // comparison result
char *compStr; // comparison result as a string
uint32_t keyFileID;
// make sure the record and first fields are in the buffer
if (recOffset + 14 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute (offset too big)");
goto on_error;
}
// Pointer to first byte of record
uint8_t *recordBytes = &nodeData[recOffset];
// Cast that to the Attributes file key
keyB = (hfs_btree_key_attr *) recordBytes;
// Compare recordBytes key to the key that we are seeking
keyFileID = tsk_getu32(endian, keyB->file_id);
//fprintf(stdout, " Key file ID = %lu\n", keyFileID);
if (keyFileID < fileID) {
comp = -1;
compStr = "less than";
}
else if (keyFileID > fileID) {
comp = 1;
compStr = "greater than";
}
else {
comp = 0;
compStr = "equal to";
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: LEAF Record key file ID %"
PRIu32 " is %s the desired file ID %" PRIu32 "\n",
keyFileID, compStr, fileID);
// Are they the same?
if (comp == 0) {
// Yes, so load this attribute
uint8_t *recData; // pointer to the data part of the recordBytes
hfs_attr_data *attrData;
uint32_t attributeLength;
uint32_t nameLength;
uint32_t recordType;
uint16_t keyLength;
int conversionResult;
char nameBuff[HFS_MAX_ATTR_NAME_LEN_UTF8_B+1];
TSK_FS_ATTR_TYPE_ENUM attrType;
TSK_FS_ATTR *fs_attr; // Points to the attribute to be loaded.
keyLength = tsk_getu16(endian, keyB->key_len);
// make sure the fields we care about are still in the buffer
// +2 because key_len doesn't include its own length
// +16 for the amount of data we'll read from data
if (recOffset + keyLength + 2 + 16 > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
recData = &recordBytes[keyLength + 2];
// Data must start on an even offset from the beginning of the record.
// So, correct this if needed.
if ((recData - recordBytes) % 2) {
recData += 1;
}
attrData = (hfs_attr_data *) recData;
// Check we can process the record type before allocating memory
recordType = tsk_getu32(endian, attrData->record_type);
if (recordType != HFS_ATTR_RECORD_INLINE_DATA) {
error_detected(TSK_ERR_FS_UNSUPTYPE,
"hfs_load_extended_attrs: Unsupported record type: (%d)",
recordType);
goto on_error;
}
// This is the length of the useful data, not including the record header
attributeLength = tsk_getu32(endian, attrData->attr_size);
// Check the attribute fits in the node
//if (recordType != HFS_ATTR_RECORD_INLINE_DATA) {
if (recOffset + keyLength + 2 + attributeLength > attrFile.nodeSize) {
error_detected(TSK_ERR_FS_READ,
"hfs_load_extended_attrs: Unable to process attribute");
goto on_error;
}
// attr_name_len is in UTF_16 chars
nameLength = tsk_getu16(endian, keyB->attr_name_len);
if (2 * nameLength > HFS_MAX_ATTR_NAME_LEN_UTF16_B) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: Name length in bytes (%d) > max name length in bytes (%d).",
2*nameLength, HFS_MAX_ATTR_NAME_LEN_UTF16_B);
goto on_error;
}
if ((int32_t)(2*nameLength) > keyLength - 12) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: Name length in bytes (%d) > remaining struct length (%d).",
2*nameLength, keyLength - 12);
goto on_error;
}
buffer = tsk_malloc(attributeLength);
if (buffer == NULL) {
error_detected(TSK_ERR_AUX_MALLOC,
"hfs_load_extended_attrs: Could not malloc space for the attribute.");
goto on_error;
}
memcpy(buffer, attrData->attr_data, attributeLength);
// Use the "attr_name" part of the key as the attribute name
// but must convert to UTF8. Unfortunately, there does not seem to
// be any easy way to determine how long the converted string will
// be because UTF8 is a variable length encoding. However, the longest
// it will be is 3 * the max number of UTF16 code units. Add one for null
// termination. (thanks Judson!)
conversionResult = hfs_UTF16toUTF8(fs, keyB->attr_name,
nameLength, nameBuff, HFS_MAX_ATTR_NAME_LEN_UTF8_B+1, 0);
if (conversionResult != 0) {
error_returned
("-- hfs_load_extended_attrs could not convert the attr_name in the btree key into a UTF8 attribute name");
goto on_error;
}
// What is the type of this attribute? If it is a compression record, then
// use TSK_FS_ATTR_TYPE_HFS_COMP_REC. Else, use TSK_FS_ATTR_TYPE_HFS_EXT_ATTR
// Only "inline data" kind of record is handled.
if (strcmp(nameBuff, "com.apple.decmpfs") == 0 &&
tsk_getu32(endian, attrData->record_type) == HFS_ATTR_RECORD_INLINE_DATA) {
// Now, look at the compression record
DECMPFS_DISK_HEADER *cmph = (DECMPFS_DISK_HEADER *) buffer;
*cmpType =
tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type);
uint64_t uncSize = tsk_getu64(TSK_LIT_ENDIAN,
cmph->uncompressed_size);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: This attribute is a compression record.\n");
attrType = TSK_FS_ATTR_TYPE_HFS_COMP_REC;
*isCompressed = TRUE; // The data is governed by a compression record (but might not be compressed)
*uncompressedSize = uncSize;
switch (*cmpType) {
// Data is inline. We will load the uncompressed
// data as a resident attribute.
case DECMPFS_TYPE_ZLIB_ATTR:
if (!hfs_file_read_zlib_attr(
fs_file, buffer, attributeLength, uncSize))
{
goto on_error;
}
break;
case DECMPFS_TYPE_LZVN_ATTR:
if (!hfs_file_read_lzvn_attr(
fs_file, buffer, attributeLength, uncSize))
{
goto on_error;
}
break;
// Data is compressed in the resource fork
case DECMPFS_TYPE_ZLIB_RSRC:
case DECMPFS_TYPE_LZVN_RSRC:
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: Compressed data is in the file Resource Fork.\n", __func__);
break;
}
}
else { // Attrbute name is NOT com.apple.decmpfs
attrType = TSK_FS_ATTR_TYPE_HFS_EXT_ATTR;
} // END if attribute name is com.apple.decmpfs ELSE clause
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_RES)) == NULL) {
error_returned(" - hfs_load_extended_attrs");
goto on_error;
}
if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_load_extended_attrs: loading attribute %s, type %u (%s)\n",
nameBuff, (uint32_t) attrType,
hfs_attrTypeName((uint32_t) attrType));
}
// set the details in the fs_attr structure
if (tsk_fs_attr_set_str(fs_file, fs_attr, nameBuff,
attrType, attribute_counter, buffer,
attributeLength)) {
error_returned(" - hfs_load_extended_attrs");
goto on_error;
}
free(buffer);
buffer = NULL;
++attribute_counter;
} // END if comp == 0
if (comp == 1) {
// since this record key is greater than our search key, all
// subsequent records will also be greater.
done = TRUE;
break;
}
} // END loop over records in one LEAF node
/*
* We get to this point if either:
*
* 1. We finish the loop over records and we are still loading attributes
* for the given file. In this case we are NOT done, and must read in
* the next leaf node, and process its records. The following code
* loads the next leaf node before we return to the top of the loop.
*
* 2. We "broke" out of the loop over records because we found a key that
* whose file ID is greater than the one we are working on. In that case
* we are done. The following code does not run, and we exit the
* while loop over successive leaf nodes.
*/
if (!done) {
// We did not finish loading the attributes when we got to the end of that node,
// so we must get the next node, and continue.
// First determine the nodeID of the next LEAF node
uint32_t newNodeID = tsk_getu32(endian, nodeDescriptor->flink);
//fprintf(stdout, "Next Node ID = %u\n", newNodeID);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Processed last record of THIS node, still gathering attributes.\n");
// If we are at the very last leaf node in the btree, then
// this "flink" will be zero. We break out of this loop over LEAF nodes.
if (newNodeID == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: But, there are no more leaf nodes, so we are done.\n");
break;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_extended_attrs: Reading the next LEAF node %"
PRIu32 ".\n", nodeID);
nodeID = newNodeID;
cnt = tsk_fs_file_read(attrFile.file,
nodeID * attrFile.nodeSize,
(char *) nodeData,
attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0);
if (cnt != (ssize_t)attrFile.nodeSize) {
error_returned
("hfs_load_extended_attrs: Could not read in the next LEAF node from the Attributes File btree");
goto on_error;
}
// Parse the Node header
nodeDescriptor = (hfs_btree_node *) nodeData;
// If we are NOT leaf node, then this is an error
if (nodeDescriptor->type != HFS_ATTR_NODE_LEAF) {
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_load_extended_attrs: found a non-LEAF node as a successor to a LEAF node");
goto on_error;
}
} // END if(! done)
} // END while(! done) loop over successive LEAF nodes
on_exit:
free(nodeData);
tsk_list_free(nodeIDs_processed);
close_attr_file(&attrFile);
return 0;
on_error:
free(buffer);
free(nodeData);
tsk_list_free(nodeIDs_processed);
close_attr_file(&attrFile);
return 1;
}
typedef struct RES_DESCRIPTOR {
char type[5]; // type is really 4 chars, but we will null-terminate
uint16_t id;
uint32_t offset;
uint32_t length;
char *name; // NULL if a name is not defined for this resource
struct RES_DESCRIPTOR *next;
} RES_DESCRIPTOR;
void
free_res_descriptor(RES_DESCRIPTOR * rd)
{
RES_DESCRIPTOR *nxt;
if (rd == NULL)
return;
nxt = rd->next;
free(rd->name);
free(rd);
free_res_descriptor(nxt); // tail recursive
}
/**
* The purpose of this function is to parse the resource fork of a file, and to return
* a data structure that is, in effect, a table of contents for the resource fork. The
* data structure is a null-terminated linked list of entries. Each one describes one
* resource. If the resource fork is empty, or if there is not a resource fork at all,
* or an error occurs, this function returns NULL.
*
* A non-NULL answer should be freed by the caller, using free_res_descriptor.
*
*/
static RES_DESCRIPTOR *
hfs_parse_resource_fork(TSK_FS_FILE * fs_file)
{
RES_DESCRIPTOR *result = NULL;
RES_DESCRIPTOR *last = NULL;
TSK_FS_INFO *fs_info;
hfs_fork *fork_info;
hfs_fork *resForkInfo;
uint64_t resSize;
const TSK_FS_ATTR *rAttr;
hfs_resource_fork_header rfHeader;
hfs_resource_fork_header *resHead;
uint32_t dataOffset;
uint32_t mapOffset;
uint32_t mapLength;
char *map;
ssize_t attrReadResult;
ssize_t attrReadResult1;
ssize_t attrReadResult2;
hfs_resource_fork_map_header *mapHdr;
uint16_t typeListOffset;
uint16_t nameListOffset;
unsigned char hasNameList;
char *nameListBegin = NULL;
hfs_resource_type_list *typeList;
uint16_t numTypes;
hfs_resource_type_list_item *tlItem;
int mindx; // index for looping over resource types
if (fs_file == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: null fs_file");
return NULL;
}
if (fs_file->meta == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: fs_file has null metadata");
return NULL;
}
if (fs_file->meta->content_ptr == NULL) {
if (tsk_verbose)
fprintf(stderr,
"hfs_parse_resource_fork: fs_file has null fork data structures, so no resources.\n");
return NULL;
}
// Extract the fs
fs_info = fs_file->fs_info;
if (fs_info == NULL) {
error_detected(TSK_ERR_FS_ARG,
"hfs_parse_resource_fork: null fs within fs_info");
return NULL;
}
// Try to look at the Resource Fork for an HFS+ file
// Should be able to cast this to hfs_fork *
fork_info = (hfs_fork *) fs_file->meta->content_ptr; // The data fork
// The resource fork is the second one.
resForkInfo = &fork_info[1];
resSize = tsk_getu64(fs_info->endian, resForkInfo->logic_sz);
//uint32_t numBlocks = tsk_getu32(fs_info->endian, resForkInfo->total_blk);
//uint32_t clmpSize = tsk_getu32(fs_info->endian, resForkInfo->clmp_sz);
// Hmm, certainly no resources here!
if (resSize == 0) {
return NULL;
}
// OK, resource size must be > 0
// find the attribute for the resource fork
rAttr =
tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC,
HFS_FS_ATTR_ID_RSRC, TRUE);
if (rAttr == NULL) {
error_returned
("hfs_parse_resource_fork: could not get the resource fork attribute");
return NULL;
}
// JUST read the resource fork header
attrReadResult1 =
tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader,
sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult1 < 0
|| attrReadResult1 != sizeof(hfs_resource_fork_header)) {
error_returned
(" hfs_parse_resource_fork: trying to read the resource fork header");
return NULL;
}
// Begin to parse the resource fork
resHead = &rfHeader;
dataOffset = tsk_getu32(fs_info->endian, resHead->dataOffset);
mapOffset = tsk_getu32(fs_info->endian, resHead->mapOffset);
//uint32_t dataLength = tsk_getu32(fs_info->endian, resHead->dataLength);
mapLength = tsk_getu32(fs_info->endian, resHead->mapLength);
// Read in the WHOLE map
map = (char *) tsk_malloc(mapLength);
if (map == NULL) {
error_returned
("- hfs_parse_resource_fork: could not allocate space for the resource fork map");
return NULL;
}
attrReadResult =
tsk_fs_attr_read(rAttr, (uint64_t) mapOffset, map,
(size_t) mapLength, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult < 0 || attrReadResult != (ssize_t) mapLength) {
error_returned
("- hfs_parse_resource_fork: could not read the map");
free(map);
return NULL;
}
mapHdr = (hfs_resource_fork_map_header *) map;
typeListOffset = tsk_getu16(fs_info->endian, mapHdr->typeListOffset);
nameListOffset = tsk_getu16(fs_info->endian, mapHdr->nameListOffset);
if (nameListOffset >= mapLength || nameListOffset == 0) {
hasNameList = FALSE;
}
else {
hasNameList = TRUE;
nameListBegin = map + nameListOffset;
}
typeList = (hfs_resource_type_list *) (map + typeListOffset);
numTypes = tsk_getu16(fs_info->endian, typeList->typeCount) + 1;
for (mindx = 0; mindx < numTypes; ++mindx) {
uint16_t numRes;
uint16_t refOff;
int pindx; // index for looping over resources
uint16_t rID;
uint32_t rOffset;
tlItem = &(typeList->type[mindx]);
numRes = tsk_getu16(fs_info->endian, tlItem->count) + 1;
refOff = tsk_getu16(fs_info->endian, tlItem->offset);
for (pindx = 0; pindx < numRes; ++pindx) {
int16_t nameOffset;
char *nameBuffer;
RES_DESCRIPTOR *rsrc;
char lenBuff[4]; // first 4 bytes of a resource encodes its length
uint32_t rLen; // Resource length
hfs_resource_refListItem *item =
((hfs_resource_refListItem *) (((uint8_t *) typeList) +
refOff)) + pindx;
nameOffset = tsk_gets16(fs_info->endian, item->resNameOffset);
nameBuffer = NULL;
if (hasNameList && nameOffset != -1) {
char *name = nameListBegin + nameOffset;
uint8_t nameLen = (uint8_t) name[0];
nameBuffer = tsk_malloc(nameLen + 1);
if (nameBuffer == NULL) {
error_returned
("hfs_parse_resource_fork: allocating space for the name of a resource");
free_res_descriptor(result);
return NULL;
}
memcpy(nameBuffer, name + 1, nameLen);
nameBuffer[nameLen] = (char) 0;
}
else {
nameBuffer = tsk_malloc(7);
if (nameBuffer == NULL) {
error_returned
("hfs_parse_resource_fork: allocating space for the (null) name of a resource");
free_res_descriptor(result);
return NULL;
}
memcpy(nameBuffer, "<none>", 6);
nameBuffer[6] = (char) 0;
}
rsrc = (RES_DESCRIPTOR *) tsk_malloc(sizeof(RES_DESCRIPTOR));
if (rsrc == NULL) {
error_returned
("hfs_parse_resource_fork: space for a resource descriptor");
free_res_descriptor(result);
return NULL;
}
// Build the linked list
if (result == NULL)
result = rsrc;
if (last != NULL)
last->next = rsrc;
last = rsrc;
rsrc->next = NULL;
rID = tsk_getu16(fs_info->endian, item->resID);
rOffset =
tsk_getu24(fs_info->endian,
item->resDataOffset) + dataOffset;
// Just read the first four bytes of the resource to get its length. It MUST
// be at least 4 bytes long
attrReadResult2 = tsk_fs_attr_read(rAttr, (uint64_t) rOffset,
lenBuff, (size_t) 4, TSK_FS_FILE_READ_FLAG_NONE);
if (attrReadResult2 != 4) {
error_returned
("- hfs_parse_resource_fork: could not read the 4-byte length at beginning of resource");
free_res_descriptor(result);
return NULL;
}
rLen = tsk_getu32(TSK_BIG_ENDIAN, lenBuff); //TODO
rsrc->id = rID;
rsrc->offset = rOffset + 4;
memcpy(rsrc->type, tlItem->type, 4);
rsrc->type[4] = (char) 0;
rsrc->length = rLen;
rsrc->name = nameBuffer;
} // END loop over resources of one type
} // END loop over resource types
return result;
}
static uint8_t
hfs_load_attrs(TSK_FS_FILE * fs_file)
{
TSK_FS_INFO *fs;
HFS_INFO *hfs;
TSK_FS_ATTR *fs_attr;
TSK_FS_ATTR_RUN *attr_run;
hfs_fork *forkx;
unsigned char resource_fork_has_contents = FALSE;
unsigned char compression_flag = FALSE;
unsigned char isCompressed = FALSE;
unsigned char compDataInRSRCFork = FALSE;
unsigned char cmpType = 0;
uint64_t uncompressedSize;
uint64_t logicalSize; // of a fork
// clean up any error messages that are lying around
tsk_error_reset();
if ((fs_file == NULL) || (fs_file->meta == NULL)
|| (fs_file->fs_info == NULL)) {
error_detected(TSK_ERR_FS_ARG,
"hfs_load_attrs: fs_file or meta is NULL");
return 1;
}
fs = (TSK_FS_INFO *) fs_file->fs_info;
hfs = (HFS_INFO *) fs;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Processing file %" PRIuINUM "\n",
fs_file->meta->addr);
// see if we have already loaded the runs
if (fs_file->meta->attr_state == TSK_FS_META_ATTR_STUDIED) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Attributes already loaded\n");
return 0;
}
else if (fs_file->meta->attr_state == TSK_FS_META_ATTR_ERROR) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Previous attempt to load attributes resulted in error\n");
return 1;
}
// Now (re)-initialize the attrlist that will hold the list of attributes
if (fs_file->meta->attr != NULL) {
tsk_fs_attrlist_markunused(fs_file->meta->attr);
}
else if (fs_file->meta->attr == NULL) {
fs_file->meta->attr = tsk_fs_attrlist_alloc();
}
/****************** EXTENDED ATTRIBUTES *******************************/
// We do these first, so that we can detect the mode of compression, if
// any. We need to know that mode in order to handle the forks.
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the HFS+ extended attributes\n");
if (hfs_load_extended_attrs(fs_file, &isCompressed,
&cmpType, &uncompressedSize)) {
error_returned(" - hfs_load_attrs A");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
// TODO: What about DECMPFS_TYPE_RAW_RSRC?
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_RSRC:
case DECMPFS_TYPE_LZVN_RSRC:
compDataInRSRCFork = TRUE;
break;
default:
compDataInRSRCFork = FALSE;
break;
}
if (isCompressed) {
fs_file->meta->size = uncompressedSize;
}
// This is the flag indicating compression, from the Catalog File record.
compression_flag = (fs_file->meta->flags & TSK_FS_META_FLAG_COMP) != 0;
if (compression_flag && !isCompressed) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, HFS marks this as a"
" compressed file, but no compression record was found.\n");
}
if (isCompressed && !compression_flag) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, this file has a compression"
" record, but the HFS compression flag is not set.\n");
}
/************* FORKS (both) ************************************/
// Process the data and resource forks. We only do this if the
// fork data structures are non-null, so test that:
if (fs_file->meta->content_ptr != NULL) {
/************** DATA FORK STUFF ***************************/
// Get the data fork data-structure
forkx = (hfs_fork *) fs_file->meta->content_ptr;
// If this is a compressed file, then either this attribute is already loaded
// because the data was in the compression record, OR
// the compressed data is in the resource fork. We will load those runs when
// we handle the resource fork.
if (!isCompressed) {
// We only load this attribute if this fork has non-zero length
// or if this is a REG or LNK file. Otherwise, we skip
logicalSize = tsk_getu64(fs->endian, forkx->logic_sz);
if (logicalSize > 0 ||
fs_file->meta->type == TSK_FS_META_TYPE_REG ||
fs_file->meta->type == TSK_FS_META_TYPE_LNK) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the data fork attribute\n");
// get an attribute structure to store the data in
if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_load_attrs");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
if (logicalSize > 0) {
// Convert runs of blocks to the TSK internal form
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_load_attrs");
return 1;
}
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run,
"", TSK_FS_ATTR_TYPE_HFS_DATA,
HFS_FS_ATTR_ID_DATA, logicalSize, logicalSize,
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size, 0,
0)) {
error_returned(" - hfs_load_attrs (DATA)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr,
TRUE)) {
error_returned(" - hfs_load_attrs B");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
}
else {
// logicalSize == 0, but this is either a REG or LNK file
// so, it should have a DATA fork attribute of zero length.
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
0, 0, 0, 0, 0)) {
error_returned(" - hfs_load_attrs (non-file)");
return 1;
}
}
} // END logicalSize>0 or REG or LNK file type
} // END if not Compressed
/************** RESOURCE FORK STUFF ************************************/
// Get the resource fork.
//Note that content_ptr points to an array of two
// hfs_fork data structures, the second of which
// describes the blocks of the resource fork.
forkx = &((hfs_fork *) fs_file->meta->content_ptr)[1];
logicalSize = tsk_getu64(fs->endian, forkx->logic_sz);
// Skip if the length of the resource fork is zero
if (logicalSize > 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: loading the resource fork\n");
resource_fork_has_contents = TRUE;
// get an attribute structure to store the resource fork data in. We will
// reuse the fs_attr variable, since we are done with the data fork.
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned(" - hfs_load_attrs (RSRC)");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
// convert the resource fork to the TSK format
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned(" - hfs_load_attrs");
return 1;
}
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "RSRC",
TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC,
tsk_getu64(fs->endian, forkx->logic_sz),
tsk_getu64(fs->endian, forkx->logic_sz),
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size, 0, 0)) {
error_returned(" - hfs_load_attrs (RSRC)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs for the resource fork.
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr, FALSE)) {
error_returned(" - hfs_load_attrs C");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
if (isCompressed && compDataInRSRCFork) {
// OK, we are going to load those same resource fork blocks as the "DATA"
// attribute, but will mark it as compressed.
// get an attribute structure to store the resource fork data in. We will
// reuse the fs_attr variable, since we are done with the data fork.
if (tsk_verbose)
tsk_fprintf(stderr,
"File is compressed with data in the resource fork. "
"Loading the default DATA attribute.\n");
if ((fs_attr =
tsk_fs_attrlist_getnew(fs_file->meta->attr,
TSK_FS_ATTR_NONRES)) == NULL) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA)");
return 1;
}
/* NOTE that fs_attr is now tied to fs_file->meta->attr.
* that means that we do not need to free it if we abort in the
* following code (and doing so will cause double free errors). */
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_RSRC:
#ifdef HAVE_LIBZ
fs_attr->w = hfs_attr_walk_zlib_rsrc;
fs_attr->r = hfs_file_read_zlib_rsrc;
#else
// We don't have zlib, so the uncompressed data is not
// available to us; however, we must have a default DATA
// attribute, or icat will misbehave.
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: No zlib compression library, so setting a zero-length default DATA attribute.\n");
if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "DATA",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, 0,
0, 0, 0, 0)) {
error_returned(" - hfs_load_attrs (non-file)");
return 1;
}
#endif
break;
case DECMPFS_TYPE_LZVN_RSRC:
fs_attr->w = hfs_attr_walk_lzvn_rsrc;
fs_attr->r = hfs_file_read_lzvn_rsrc;
break;
}
// convert the resource fork to the TSK format
if (((attr_run =
hfs_extents_to_attr(fs, forkx->extents,
0)) == NULL)
&& (tsk_error_get_errno() != 0)) {
error_returned
(" - hfs_load_attrs, RSRC fork as DATA fork");
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: Loading RSRC fork block runs as the default DATA attribute.\n");
// add the runs to the attribute and the attribute to the file.
if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "DECOMP",
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
logicalSize,
logicalSize,
(TSK_OFF_T) tsk_getu32(fs->endian,
forkx->total_blk) * fs->block_size,
TSK_FS_ATTR_COMP | TSK_FS_ATTR_NONRES, 0)) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA)");
tsk_fs_attr_run_free(attr_run);
return 1;
}
// see if extents file has additional runs for the resource fork.
if (hfs_ext_find_extent_record_attr(hfs,
(uint32_t) fs_file->meta->addr, fs_attr, FALSE)) {
error_returned
(" - hfs_load_attrs (RSRC loading as DATA");
fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR;
return 1;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: setting the \"special\" function pointers to inflate compressed data.\n");
}
} // END resource fork size > 0
} // END the fork data structures are non-NULL
if (isCompressed && compDataInRSRCFork && !resource_fork_has_contents) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_load_attrs: WARNING, compression record claims that compressed data"
" is in the Resource Fork, but that fork is empty or non-existent.\n");
}
// Finish up.
fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED;
return 0;
}
/** \internal
* Get allocation status of file system block.
* adapted from IsAllocationBlockUsed from:
* http://developer.apple.com/technotes/tn/tn1150.html
*
* @param hfs File system being analyzed
* @param b Block address
* @returns 1 if allocated, 0 if not, -1 on error
*/
static int8_t
hfs_block_is_alloc(HFS_INFO * hfs, TSK_DADDR_T a_addr)
{
TSK_FS_INFO *fs = &(hfs->fs_info);
TSK_OFF_T b;
size_t b2;
// lazy loading
if (hfs->blockmap_file == NULL) {
if ((hfs->blockmap_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_ALLOCATION_FILE_ID)) == NULL) {
tsk_error_errstr2_concat(" - Loading blockmap file");
return -1;
}
/* cache the data attribute */
hfs->blockmap_attr =
tsk_fs_attrlist_get(hfs->blockmap_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->blockmap_attr) {
tsk_error_errstr2_concat
(" - Data Attribute not found in Blockmap File");
return -1;
}
hfs->blockmap_cache_start = -1;
hfs->blockmap_cache_len = 0;
}
// get the byte offset
b = (TSK_OFF_T) a_addr / 8;
if (b > hfs->blockmap_file->meta->size) {
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("hfs_block_is_alloc: block %" PRIuDADDR
" is too large for bitmap (%" PRIuOFF ")", a_addr,
hfs->blockmap_file->meta->size);
return -1;
}
// see if it is in the cache
if ((hfs->blockmap_cache_start == -1)
|| (hfs->blockmap_cache_start > b)
|| (hfs->blockmap_cache_start + hfs->blockmap_cache_len <= (size_t) b)) {
ssize_t cnt = tsk_fs_attr_read(hfs->blockmap_attr, b,
hfs->blockmap_cache,
sizeof(hfs->blockmap_cache), 0);
if (cnt < 1) {
tsk_error_set_errstr2
("hfs_block_is_alloc: Error reading block bitmap at offset %"
PRIuOFF, b);
return -1;
}
hfs->blockmap_cache_start = b;
hfs->blockmap_cache_len = cnt;
}
b2 = (size_t) (b - hfs->blockmap_cache_start);
return (hfs->blockmap_cache[b2] & (1 << (7 - (a_addr % 8)))) != 0;
}
TSK_FS_BLOCK_FLAG_ENUM
hfs_block_getflags(TSK_FS_INFO * a_fs, TSK_DADDR_T a_addr)
{
return (hfs_block_is_alloc((HFS_INFO *) a_fs, a_addr) == 1) ?
TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC;
}
static uint8_t
hfs_block_walk(TSK_FS_INFO * fs, TSK_DADDR_T start_blk,
TSK_DADDR_T end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM flags,
TSK_FS_BLOCK_WALK_CB action, void *ptr)
{
char *myname = "hfs_block_walk";
HFS_INFO *hfs = (HFS_INFO *) fs;
TSK_FS_BLOCK *fs_block;
TSK_DADDR_T addr;
if (tsk_verbose)
tsk_fprintf(stderr,
"%s: start_blk: %" PRIuDADDR " end_blk: %"
PRIuDADDR " flags: %" PRIu32 "\n", myname, start_blk, end_blk,
flags);
// clean up any error messages that are lying around
tsk_error_reset();
/*
* Sanity checks.
*/
if (start_blk < fs->first_block || start_blk > fs->last_block) {
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("%s: invalid start block number: %" PRIuDADDR
"", myname, start_blk);
return 1;
}
if (end_blk < fs->first_block || end_blk > fs->last_block) {
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("%s: invalid last block number: %" PRIuDADDR
"", myname, end_blk);
return 1;
}
if (start_blk > end_blk)
XSWAP(start_blk, end_blk);
/* Sanity check on flags -- make sure at least one ALLOC is set */
if (((flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) &&
((flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) {
flags |=
(TSK_FS_BLOCK_WALK_FLAG_ALLOC |
TSK_FS_BLOCK_WALK_FLAG_UNALLOC);
}
if (((flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) &&
((flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) {
flags |=
(TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META);
}
if ((fs_block = tsk_fs_block_alloc(fs)) == NULL) {
return 1;
}
/*
* Iterate
*/
for (addr = start_blk; addr <= end_blk; ++addr) {
int retval;
int myflags;
/* identify if the block is allocated or not */
myflags = hfs_block_is_alloc(hfs, addr) ?
TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC;
// test if we should call the callback with this one
if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC)
&& (!(flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC)))
continue;
else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC)
&& (!(flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC)))
continue;
if (flags & TSK_FS_BLOCK_WALK_FLAG_AONLY)
myflags |= TSK_FS_BLOCK_FLAG_AONLY;
if (tsk_fs_block_get_flag(fs, fs_block, addr,
(TSK_FS_BLOCK_FLAG_ENUM) myflags) == NULL) {
tsk_fs_block_free(fs_block);
return 1;
}
retval = action(fs_block, ptr);
if (TSK_WALK_STOP == retval) {
break;
}
else if (TSK_WALK_ERROR == retval) {
tsk_fs_block_free(fs_block);
return 1;
}
}
tsk_fs_block_free(fs_block);
return 0;
}
uint8_t
hfs_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 action, void *ptr)
{
TSK_INUM_T inum;
TSK_FS_FILE *fs_file;
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_inode_walk: start_inum: %" PRIuINUM " end_inum: %"
PRIuINUM " flags: %" PRIu32 "\n", start_inum, end_inum, flags);
/*
* Sanity checks.
*/
if (start_inum < fs->first_inum || start_inum > fs->last_inum) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("inode_walk: Start inode: %" PRIuINUM "",
start_inum);
return 1;
}
else if (end_inum < fs->first_inum || end_inum > fs->last_inum
|| end_inum < start_inum) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_WALK_RNG);
tsk_error_set_errstr("inode_walk: End inode: %" PRIuINUM "",
end_inum);
return 1;
}
/* If ORPHAN is wanted, then make sure that the flags are correct */
if (flags & TSK_FS_META_FLAG_ORPHAN) {
flags |= TSK_FS_META_FLAG_UNALLOC;
flags &= ~TSK_FS_META_FLAG_ALLOC;
flags |= TSK_FS_META_FLAG_USED;
flags &= ~TSK_FS_META_FLAG_UNUSED;
}
else {
if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) &&
((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) {
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_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(HFS_FILE_CONTENT_LEN)) == NULL)
return 1;
if (start_inum > end_inum)
XSWAP(start_inum, end_inum);
for (inum = start_inum; inum <= end_inum; ++inum) {
int retval;
if (hfs_inode_lookup(fs, fs_file, inum)) {
// deleted files may not exist in the catalog
if (tsk_error_get_errno() == TSK_ERR_FS_INODE_NUM) {
tsk_error_reset();
continue;
}
else {
return 1;
}
}
if ((fs_file->meta->flags & flags) != fs_file->meta->flags)
continue;
/* call action */
retval = action(fs_file, 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;
}
}
tsk_fs_file_close(fs_file);
return 0;
}
/* return the name of a file at a given inode
* in a newly-allocated string, or NULL on error
*/
char *
hfs_get_inode_name(TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
HFS_ENTRY entry;
char *fn = NULL;
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return NULL;
fn = malloc(HFS_MAXNAMLEN + 1);
if (fn == NULL)
return NULL;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH)) {
free(fn);
return NULL;
}
return fn;
}
/* print the name of a file at a given inode
* returns 0 on success, 1 on error */
static uint8_t
print_inode_name(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
char fn[HFS_MAXNAMLEN + 1];
HFS_ENTRY entry;
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return 1;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH))
return 1;
tsk_fprintf(hFile, "%s", fn);
return 0;
}
/* tail recursive function to print a path... prints the parent path, then
* appends / and the name of the given inode. prints nothing for root
* returns 0 on success, 1 on failure
*/
static uint8_t
print_parent_path(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
char fn[HFS_MAXNAMLEN + 1];
HFS_ENTRY entry;
if (inum == HFS_ROOT_INUM)
return 0;
if (inum <= HFS_ROOT_INUM) {
tsk_error_set_errno(TSK_ERR_FS_INODE_NUM);
tsk_error_set_errstr("print_parent_path: out-of-range inode %"
PRIuINUM, inum);
return 1;
}
if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE))
return 1;
if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode,
tsk_getu16(fs->endian, entry.thread.name.length), fn,
HFS_MAXNAMLEN + 1,
HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL))
return 1;
if (print_parent_path(hFile, fs, (TSK_INUM_T) tsk_getu32(fs->endian,
entry.thread.parent_cnid)))
return 1;
tsk_fprintf(hFile, "/%s", fn);
return 0;
}
/* print the file name corresponding to an inode, in brackets after a space.
* uses Unix path conventions, and does not include the volume name.
* returns 0 on success, 1 on failure
*/
static uint8_t
print_inode_file(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum)
{
tsk_fprintf(hFile, " [");
if (inum == HFS_ROOT_INUM)
tsk_fprintf(hFile, "/");
else {
if (print_parent_path(hFile, fs, inum)) {
tsk_fprintf(hFile, "unknown]");
return 1;
}
}
tsk_fprintf(hFile, "]");
return 0;
}
static uint8_t
hfs_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 for HFS yet");
return 1;
}
static uint8_t
hfs_fsstat(TSK_FS_INFO * fs, FILE * hFile)
{
// char *myname = "hfs_fsstat";
HFS_INFO *hfs = (HFS_INFO *) fs;
hfs_plus_vh *sb = hfs->fs;
time_t mac_time;
TSK_INUM_T inode;
char timeBuf[128];
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_fstat: called\n");
tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "File System Type: ");
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSPLUS)
tsk_fprintf(hFile, "HFS+\n");
else if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX)
tsk_fprintf(hFile, "HFSX\n");
else
tsk_fprintf(hFile, "Unknown\n");
// print name and number of version
tsk_fprintf(hFile, "File System Version: ");
switch (tsk_getu16(fs->endian, hfs->fs->version)) {
case 4:
tsk_fprintf(hFile, "HFS+\n");
break;
case 5:
tsk_fprintf(hFile, "HFSX\n");
break;
default:
tsk_fprintf(hFile, "Unknown (%" PRIu16 ")\n",
tsk_getu16(fs->endian, hfs->fs->version));
break;
}
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX) {
tsk_fprintf(hFile, "Case Sensitive: %s\n",
hfs->is_case_sensitive ? "yes" : "no");
}
if (hfs->hfs_wrapper_offset > 0) {
tsk_fprintf(hFile,
"File system is embedded in an HFS wrapper at offset %" PRIuOFF
"\n", hfs->hfs_wrapper_offset);
}
tsk_fprintf(hFile, "\nVolume Name: ");
if (print_inode_name(hFile, fs, HFS_ROOT_INUM))
return 1;
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Volume Identifier: %08" PRIx32 "%08" PRIx32 "\n",
tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID1]),
tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID2]));
// print last mounted info
tsk_fprintf(hFile, "\nLast Mounted By: ");
if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSPLUS)
tsk_fprintf(hFile, "Mac OS X\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSJ)
tsk_fprintf(hFile, "Mac OS X, Journaled\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSK)
tsk_fprintf(hFile, "failed journal replay\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSCK)
tsk_fprintf(hFile, "fsck_hfs\n");
else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_OS89)
tsk_fprintf(hFile, "Mac OS 8.1 - 9.2.2\n");
else
tsk_fprintf(hFile, "Unknown (%" PRIx32 "\n",
tsk_getu32(fs->endian, sb->last_mnt_ver));
/* State of the file system */
if ((tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_UNMOUNTED)
&& (!(tsk_getu32(fs->endian,
hfs->fs->attr) & HFS_VH_ATTR_INCONSISTENT)))
tsk_fprintf(hFile, "Volume Unmounted Properly\n");
else
tsk_fprintf(hFile, "Volume Unmounted Improperly\n");
tsk_fprintf(hFile, "Mount Count: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->write_cnt));
// Dates
// (creation date is in local time zone, not UTC, according to TN 1150)
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->cr_date));
tsk_fprintf(hFile, "\nCreation Date: \t%s\n",
tsk_fs_time_to_str(mktime(gmtime(&mac_time)), timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->m_date));
tsk_fprintf(hFile, "Last Written Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian,
hfs->fs->bkup_date));
tsk_fprintf(hFile, "Last Backup Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
mac_time =
hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->chk_date));
tsk_fprintf(hFile, "Last Checked Date: \t%s\n",
tsk_fs_time_to_str(mac_time, timeBuf));
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_SOFTWARE_LOCK)
tsk_fprintf(hFile, "Software write protect enabled\n");
/* Print journal information */
if (tsk_getu32(fs->endian, sb->attr) & HFS_VH_ATTR_JOURNALED) {
tsk_fprintf(hFile, "\nJournal Info Block: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->jinfo_blk));
}
tsk_fprintf(hFile, "\nMETADATA INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "Range: %" PRIuINUM " - %" PRIuINUM "\n",
fs->first_inum, fs->last_inum);
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT]);
tsk_fprintf(hFile, "Bootable Folder ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_START]);
tsk_fprintf(hFile, "Startup App ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_OPEN]);
tsk_fprintf(hFile, "Startup Open Folder ID: %" PRIuINUM, inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT9]);
tsk_fprintf(hFile, "Mac OS 8/9 Blessed System Folder ID: %" PRIuINUM,
inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOTX]);
tsk_fprintf(hFile, "Mac OS X Blessed System Folder ID: %" PRIuINUM,
inode);
if (inode > 0)
print_inode_file(hFile, fs, inode);
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Number of files: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->file_cnt));
tsk_fprintf(hFile, "Number of folders: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->fldr_cnt));
tsk_fprintf(hFile, "\nCONTENT INFORMATION\n");
tsk_fprintf(hFile, "--------------------------------------------\n");
tsk_fprintf(hFile, "Block Range: %" PRIuDADDR " - %" PRIuDADDR "\n",
fs->first_block, fs->last_block);
if (fs->last_block != fs->last_block_act)
tsk_fprintf(hFile,
"Total Range in Image: %" PRIuDADDR " - %" PRIuDADDR "\n",
fs->first_block, fs->last_block_act);
tsk_fprintf(hFile, "Allocation Block Size: %u\n", fs->block_size);
tsk_fprintf(hFile, "Number of Free Blocks: %" PRIu32 "\n",
tsk_getu32(fs->endian, sb->free_blks));
if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_BADBLOCKS)
tsk_fprintf(hFile, "Volume has bad blocks\n");
return 0;
}
/************************* istat *******************************/
/**
* Text encoding names defined in TN1150, Table 2.
*/
static char *
text_encoding_name(uint32_t enc)
{
switch (enc) {
case 0:
return "MacRoman";
case 1:
return "MacJapanese";
case 2:
return "MacChineseTrad";
case 4:
return "MacKorean";
case 5:
return "MacArabic";
case 6:
return "MacHebrew";
case 7:
return "MacGreek";
case 8:
return "MacCyrillic";
case 9:
return "MacDevanagari";
case 10:
return "MacGurmukhi";
case 11:
return "MacGujarati";
case 12:
return "MacOriya";
case 13:
return "MacBengali";
case 14:
return "MacTamil";
case 15:
return "Telugu";
case 16:
return "MacKannada";
case 17:
return "MacMalayalam";
case 18:
return "MacSinhalese";
case 19:
return "MacBurmese";
case 20:
return "MacKhmer";
case 21:
return "MacThai";
case 22:
return "MacLaotian";
case 23:
return "MacGeorgian";
case 24:
return "MacArmenian";
case 25:
return "MacChineseSimp";
case 26:
return "MacTibetan";
case 27:
return "MacMongolian";
case 28:
return "MacEthiopic";
case 29:
return "MacCentralEurRoman";
case 30:
return "MacVietnamese";
case 31:
return "MacExtArabic";
case 33:
return "MacSymbol";
case 34:
return "MacDingbats";
case 35:
return "MacTurkish";
case 36:
return "MacCroatian";
case 37:
return "MacIcelandic";
case 38:
return "MacRomanian";
case 49:
case 140:
return "MacFarsi";
case 48:
case 152:
return "MacUkrainian";
default:
return "Unknown encoding";
}
}
#define HFS_PRINT_WIDTH 8
typedef struct {
FILE *hFile;
int idx;
TSK_DADDR_T startBlock;
uint32_t blockCount;
unsigned char accumulating;
} HFS_PRINT_ADDR;
static void
output_print_addr(HFS_PRINT_ADDR * print)
{
if (!print->accumulating)
return;
if (print->blockCount == 1) {
tsk_fprintf(print->hFile, "%" PRIuDADDR " ", print->startBlock);
print->idx += 1;
}
else if (print->blockCount > 1) {
tsk_fprintf(print->hFile, "%" PRIuDADDR "-%" PRIuDADDR " ",
print->startBlock, print->startBlock + print->blockCount - 1);
print->idx += 2;
}
if (print->idx >= HFS_PRINT_WIDTH) {
tsk_fprintf(print->hFile, "\n");
print->idx = 0;
}
}
static TSK_WALK_RET_ENUM
print_addr_act(TSK_FS_FILE * fs_file, TSK_OFF_T a_off, TSK_DADDR_T addr,
char *buf, size_t size, TSK_FS_BLOCK_FLAG_ENUM flags, void *ptr)
{
HFS_PRINT_ADDR *print = (HFS_PRINT_ADDR *) ptr;
if (print->accumulating) {
if (addr == print->startBlock + print->blockCount) {
++print->blockCount;
}
else {
output_print_addr(print);
print->startBlock = addr;
print->blockCount = 1;
}
}
else {
print->startBlock = addr;
print->blockCount = 1;
print->accumulating = TRUE;
}
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 name 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
hfs_istat(TSK_FS_INFO * fs, TSK_FS_ISTAT_FLAG_ENUM istat_flags, FILE * hFile, TSK_INUM_T inum,
TSK_DADDR_T numblock, int32_t sec_skew)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
TSK_FS_FILE *fs_file;
char hfs_mode[12];
HFS_PRINT_ADDR print;
HFS_ENTRY entry;
char timeBuf[128];
// Compression ATTR, if there is one:
const TSK_FS_ATTR *compressionAttr = NULL;
RES_DESCRIPTOR *rd; // descriptor of a resource
tsk_error_reset();
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_istat: inum: %" PRIuINUM " numblock: %" PRIu32 "\n",
inum, numblock);
if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) {
error_returned("hfs_istat: getting metadata for the file");
return 1;
}
if (inum >= HFS_FIRST_USER_CNID) {
int rslt;
tsk_fprintf(hFile, "File Path: ");
rslt = print_parent_path(hFile, fs, inum);
if (rslt != 0)
tsk_fprintf(hFile, " Error in printing path\n");
else
tsk_fprintf(hFile, "\n");
}
else {
// All of the files in this inum range have names without nulls,
// slashes or control characters. So, it is OK to print this UTF8
// string this way.
if (fs_file->meta->name2 != NULL)
tsk_fprintf(hFile, "File Name: %s\n",
fs_file->meta->name2->name);
}
tsk_fprintf(hFile, "Catalog Record: %" PRIuINUM "\n", inum);
tsk_fprintf(hFile, "%sAllocated\n",
(fs_file->meta->flags & TSK_FS_META_FLAG_UNALLOC) ? "Not " : "");
tsk_fprintf(hFile, "Type:\t");
if (fs_file->meta->type == TSK_FS_META_TYPE_REG)
tsk_fprintf(hFile, "File\n");
else if (TSK_FS_IS_DIR_META(fs_file->meta->type))
tsk_fprintf(hFile, "Folder\n");
else
tsk_fprintf(hFile, "\n");
tsk_fs_meta_make_ls(fs_file->meta, hfs_mode, sizeof(hfs_mode));
tsk_fprintf(hFile, "Mode:\t%s\n", hfs_mode);
tsk_fprintf(hFile, "Size:\t%" PRIuOFF "\n", fs_file->meta->size);
if (fs_file->meta->link)
tsk_fprintf(hFile, "Symbolic link to:\t%s\n", fs_file->meta->link);
tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n",
fs_file->meta->uid, fs_file->meta->gid);
tsk_fprintf(hFile, "Link count:\t%d\n", fs_file->meta->nlink);
if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE) == 0) {
hfs_uni_str *nm = &entry.thread.name;
char name_buf[HFS_MAXNAMLEN + 1];
TSK_INUM_T par_cnid; // parent CNID
tsk_fprintf(hFile, "\n");
hfs_UTF16toUTF8(fs, nm->unicode, (int) tsk_getu16(fs->endian,
nm->length), &name_buf[0], HFS_MAXNAMLEN + 1,
HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL);
tsk_fprintf(hFile, "File Name: %s\n", name_buf);
// Test here to see if this is a hard link.
par_cnid = tsk_getu32(fs->endian, &(entry.thread.parent_cnid));
if ((hfs->has_meta_dir_crtime && par_cnid == hfs->meta_dir_inum) ||
(hfs->has_meta_crtime && par_cnid == hfs->meta_inum)) {
int instr = strncmp(name_buf, "iNode", 5);
int drstr = strncmp(name_buf, "dir_", 4);
if (instr == 0 &&
hfs->has_meta_crtime && par_cnid == hfs->meta_inum) {
tsk_fprintf(hFile, "This is a hard link to a file\n");
}
else if (drstr == 0 &&
hfs->has_meta_dir_crtime &&
par_cnid == hfs->meta_dir_inum) {
tsk_fprintf(hFile, "This is a hard link to a folder.\n");
}
}
/* The cat.perm union contains file-type specific values.
* Print them if they are relevant. */
if ((fs_file->meta->type == TSK_FS_META_TYPE_CHR) ||
(fs_file->meta->type == TSK_FS_META_TYPE_BLK)) {
tsk_fprintf(hFile, "Device ID:\t%" PRIu32 "\n",
tsk_getu32(fs->endian, entry.cat.std.perm.special.raw));
}
else if ((tsk_getu32(fs->endian,
entry.cat.std.u_info.file_type) ==
HFS_HARDLINK_FILE_TYPE)
&& (tsk_getu32(fs->endian,
entry.cat.std.u_info.file_cr) ==
HFS_HARDLINK_FILE_CREATOR)) {
// technically, the creation date of this item should be the same as either the
// creation date of the "HFS+ Private Data" folder or the creation date of the root folder
tsk_fprintf(hFile, "Hard link inode number\t %" PRIu32 "\n",
tsk_getu32(fs->endian, entry.cat.std.perm.special.inum));
}
tsk_fprintf(hFile, "Admin flags: %" PRIu8,
entry.cat.std.perm.a_flags);
if (entry.cat.std.perm.a_flags != 0) {
tsk_fprintf(hFile, " - ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_ARCHIVED)
tsk_fprintf(hFile, "archived ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_IMMUTABLE)
tsk_fprintf(hFile, "immutable ");
if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_APPEND)
tsk_fprintf(hFile, "append-only ");
}
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile, "Owner flags: %" PRIu8,
entry.cat.std.perm.o_flags);
if (entry.cat.std.perm.o_flags != 0) {
tsk_fprintf(hFile, " - ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_NODUMP)
tsk_fprintf(hFile, "no-dump ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_IMMUTABLE)
tsk_fprintf(hFile, "immutable ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_APPEND)
tsk_fprintf(hFile, "append-only ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_OPAQUE)
tsk_fprintf(hFile, "opaque ");
if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
tsk_fprintf(hFile, "compressed ");
}
tsk_fprintf(hFile, "\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_LOCKED)
tsk_fprintf(hFile, "Locked\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_ATTR)
tsk_fprintf(hFile, "Has extended attributes\n");
if (tsk_getu16(fs->endian,
entry.cat.std.flags) & HFS_FILE_FLAG_ACL)
tsk_fprintf(hFile, "Has security data (ACLs)\n");
// File_type and file_cr are not relevant for Folders
if ( !TSK_FS_IS_DIR_META(fs_file->meta->type)){
int windx; // loop index
tsk_fprintf(hFile,
"File type:\t%04" PRIx32 " ",
tsk_getu32(fs->endian, entry.cat.std.u_info.file_type));
for (windx = 0; windx < 4; ++windx) {
uint8_t cu = entry.cat.std.u_info.file_type[windx];
if (cu >= 32 && cu <= 126)
tsk_fprintf(hFile, "%c", (char) cu);
else
tsk_fprintf(hFile, " ");
}
tsk_fprintf(hFile, "\n");
tsk_fprintf(hFile,
"File creator:\t%04" PRIx32 " ",
tsk_getu32(fs->endian, entry.cat.std.u_info.file_cr));
for (windx = 0; windx < 4; ++windx) {
uint8_t cu = entry.cat.std.u_info.file_cr[windx];
if (cu >= 32 && cu <= 126)
tsk_fprintf(hFile, "%c", (char) cu);
else
tsk_fprintf(hFile, " ");
}
tsk_fprintf(hFile, "\n");
} // END if(not folder)
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_NAME_LOCKED)
tsk_fprintf(hFile, "Name locked\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_HAS_BUNDLE)
tsk_fprintf(hFile, "Has bundle\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_INVISIBLE)
tsk_fprintf(hFile, "Is invisible\n");
if (tsk_getu16(fs->endian,
entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_ALIAS)
tsk_fprintf(hFile, "Is alias\n");
tsk_fprintf(hFile, "Text encoding:\t%" PRIx32 " = %s\n",
tsk_getu32(fs->endian, entry.cat.std.text_enc),
text_encoding_name(tsk_getu32(fs->endian,
entry.cat.std.text_enc)));
if (tsk_getu16(fs->endian,
entry.cat.std.rec_type) == HFS_FILE_RECORD) {
tsk_fprintf(hFile, "Resource fork size:\t%" PRIu64 "\n",
tsk_getu64(fs->endian, entry.cat.resource.logic_sz));
}
}
if (sec_skew != 0) {
tsk_fprintf(hFile, "\nAdjusted times:\n");
if (fs_file->meta->mtime)
fs_file->meta->mtime -= sec_skew;
if (fs_file->meta->atime)
fs_file->meta->atime -= sec_skew;
if (fs_file->meta->ctime)
fs_file->meta->ctime -= sec_skew;
if (fs_file->meta->crtime)
fs_file->meta->crtime -= sec_skew;
if (fs_file->meta->time2.hfs.bkup_time)
fs_file->meta->time2.hfs.bkup_time -= sec_skew;
tsk_fprintf(hFile, "Created:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf));
tsk_fprintf(hFile, "Content Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf));
tsk_fprintf(hFile, "Attributes Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf));
tsk_fprintf(hFile, "Accessed:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->atime, timeBuf));
tsk_fprintf(hFile, "Backed Up:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time,
timeBuf));
if (fs_file->meta->mtime)
fs_file->meta->mtime += sec_skew;
if (fs_file->meta->atime)
fs_file->meta->atime += sec_skew;
if (fs_file->meta->ctime)
fs_file->meta->ctime += sec_skew;
if (fs_file->meta->crtime)
fs_file->meta->crtime += sec_skew;
if (fs_file->meta->time2.hfs.bkup_time)
fs_file->meta->time2.hfs.bkup_time += sec_skew;
tsk_fprintf(hFile, "\nOriginal times:\n");
}
else {
tsk_fprintf(hFile, "\nTimes:\n");
}
tsk_fprintf(hFile, "Created:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf));
tsk_fprintf(hFile, "Content Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf));
tsk_fprintf(hFile, "Attributes Modified:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf));
tsk_fprintf(hFile, "Accessed:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->atime, timeBuf));
tsk_fprintf(hFile, "Backed Up:\t%s\n",
tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time, timeBuf));
// IF this is a regular file, then print out the blocks of the DATA and RSRC forks.
if (tsk_getu16(fs->endian, entry.cat.std.rec_type) == HFS_FILE_RECORD) {
// Only print DATA fork blocks if this file is NOT compressed
// N.B., a compressed file has no data fork, and tsk_fs_file_walk() will
// do the wrong thing!
if (!(entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)) {
if (!(istat_flags & TSK_FS_ISTAT_RUNLIST)) {
tsk_fprintf(hFile, "\nData Fork Blocks:\n");
print.idx = 0;
print.hFile = hFile;
print.accumulating = FALSE;
print.startBlock = 0;
print.blockCount = 0;
if (tsk_fs_file_walk_type(fs_file,
TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA,
(TSK_FS_FILE_WALK_FLAG_AONLY |
TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act,
(void *)&print)) {
tsk_fprintf(hFile, "\nError reading file data fork\n");
tsk_error_print(hFile);
tsk_error_reset();
}
else {
output_print_addr(&print);
if (print.idx != 0)
tsk_fprintf(hFile, "\n");
}
}
}
// Only print out the blocks of the Resource fork if it has nonzero size
if (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) > 0) {
if (! (istat_flags & TSK_FS_ISTAT_RUNLIST)) {
tsk_fprintf(hFile, "\nResource Fork Blocks:\n");
print.idx = 0;
print.hFile = hFile;
print.accumulating = FALSE;
print.startBlock = 0;
print.blockCount = 0;
if (tsk_fs_file_walk_type(fs_file,
TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC,
(TSK_FS_FILE_WALK_FLAG_AONLY |
TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act,
(void *)&print)) {
tsk_fprintf(hFile, "\nError reading file resource fork\n");
tsk_error_print(hFile);
tsk_error_reset();
}
else {
output_print_addr(&print);
if (print.idx != 0)
tsk_fprintf(hFile, "\n");
}
}
}
}
// Force the loading of all attributes.
(void) tsk_fs_file_attr_get(fs_file);
/* Print all of the attributes */
tsk_fprintf(hFile, "\nAttributes: \n");
if (fs_file->meta->attr) {
int cnt, i;
// cycle through the attributes
cnt = tsk_fs_file_attr_getsize(fs_file);
for (i = 0; i < cnt; ++i) {
const char *type; // type of the attribute as a string
const TSK_FS_ATTR *fs_attr =
tsk_fs_file_attr_get_idx(fs_file, i);
if (!fs_attr)
continue;
type = hfs_attrTypeName((uint32_t) fs_attr->type);
// We will need to do something better than this, in the end.
//type = "Data";
/* print the layout if it is non-resident and not "special" */
if (fs_attr->flags & TSK_FS_ATTR_NONRES) {
//NTFS_PRINT_ADDR print_addr;
tsk_fprintf(hFile,
"Type: %s (%" PRIu32 "-%" PRIu16
") Name: %s Non-Resident%s%s%s size: %"
PRIuOFF " init_size: %" PRIuOFF "\n", type,
fs_attr->type, fs_attr->id,
(fs_attr->name) ? fs_attr->name : "N/A",
(fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" :
"",
(fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" :
"",
(fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" :
"", fs_attr->size, fs_attr->nrd.initsize);
if (istat_flags & TSK_FS_ISTAT_RUNLIST) {
if (tsk_fs_attr_print(fs_attr, hFile)) {
tsk_fprintf(hFile, "\nError creating run lists\n");
tsk_error_print(hFile);
tsk_error_reset();
}
}
} // END: non-resident attribute case
else {
tsk_fprintf(hFile,
"Type: %s (%" PRIu32 "-%" PRIu16
") Name: %s Resident%s%s%s size: %"
PRIuOFF "\n",
type,
fs_attr->type,
fs_attr->id,
(fs_attr->name) ? fs_attr->name : "N/A",
(fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" :
"",
(fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" :
"",
(fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" :
"", fs_attr->size);
if (fs_attr->type == TSK_FS_ATTR_TYPE_HFS_COMP_REC) {
if (compressionAttr == NULL) {
compressionAttr = fs_attr;
}
else {
// Problem: there is more than one compression attribute
error_detected(TSK_ERR_FS_CORRUPT,
"hfs_istat: more than one compression attribute");
return 1;
}
}
} // END: else (RESIDENT attribute case)
} // END: for(;;) loop over attributes
} // END: if(fs_file->meta->attr is non-NULL)
if ((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)
&& (compressionAttr == NULL))
tsk_fprintf(hFile,
"WARNING: Compression Flag is set, but there"
" is no compression record for this file.\n");
if (((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) == 0)
&& (compressionAttr != NULL))
tsk_fprintf(hFile,
"WARNING: Compression Flag is NOT set, but there"
" is a compression record for this file.\n");
// IF this is a compressed file
if (compressionAttr != NULL) {
const TSK_FS_ATTR *fs_attr = compressionAttr;
ssize_t attrReadResult;
DECMPFS_DISK_HEADER *cmph;
uint32_t cmpType;
uint64_t uncSize;
uint64_t cmpSize = 0;
// Read the attribute. It cannot be too large because it is stored in
// a btree node
char *aBuf = (char *) tsk_malloc((size_t) fs_attr->size);
if (aBuf == NULL) {
error_returned("hfs_istat: space for a compression attribute");
return 1;
}
attrReadResult = tsk_fs_attr_read(fs_attr, (TSK_OFF_T) 0,
aBuf, (size_t) fs_attr->size,
(TSK_FS_FILE_READ_FLAG_ENUM) 0x00);
if (attrReadResult == -1) {
error_returned("hfs_istat: reading the compression attribute");
free(aBuf);
return 1;
}
else if (attrReadResult < fs_attr->size) {
error_detected(TSK_ERR_FS_READ,
"hfs_istat: could not read the whole compression attribute");
free(aBuf);
return 1;
}
// Now, cast the attr into a compression header
cmph = (DECMPFS_DISK_HEADER *) aBuf;
cmpType = tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type);
uncSize = tsk_getu64(TSK_LIT_ENDIAN, cmph->uncompressed_size);
tsk_fprintf(hFile, "\nCompressed File:\n");
tsk_fprintf(hFile, " Uncompressed size: %llu\n", uncSize);
switch (cmpType) {
case DECMPFS_TYPE_ZLIB_ATTR:
// Data is inline
{
// size of header, with indicator byte if uncompressed
uint32_t off = (cmph->attr_bytes[0] & 0x0F) == 0x0F ? 17 : 16;
cmpSize = fs_attr->size - off;
tsk_fprintf(hFile,
" Data follows compression record in the CMPF attribute\n"
" %" PRIu64 " bytes of data at offset %u, %s compressed\n",
cmpSize, off, off == 16 ? "zlib" : "not");
}
break;
case DECMPFS_TYPE_LZVN_ATTR:
// Data is inline
{
// size of header, with indicator byte if uncompressed
uint32_t off = cmph->attr_bytes[0] == 0x06 ? 17 : 16;
cmpSize = fs_attr->size - off;
tsk_fprintf(hFile,
" Data follows compression record in the CMPF attribute\n"
" %" PRIu64 " bytes of data at offset %u, %s compressed\n",
cmpSize, off, off == 16 ? "lzvn" : "not");
}
break;
case DECMPFS_TYPE_ZLIB_RSRC:
// Data is zlib compressed in the resource fork
tsk_fprintf(hFile,
" Data is zlib compressed in the resource fork\n");
break;
case DECMPFS_TYPE_LZVN_RSRC:
// Data is lzvn compressed in the resource fork
tsk_fprintf(hFile,
" Data is lzvn compressed in the resource fork\n");
break;
default:
tsk_fprintf(hFile, " Compression type is %u: UNKNOWN\n",
cmpType);
}
free(aBuf);
if ((cmpType == DECMPFS_TYPE_ZLIB_RSRC ||
cmpType == DECMPFS_TYPE_LZVN_RSRC)
&& (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) == 0))
tsk_fprintf(hFile,
"WARNING: Compression record indicates compressed data"
" in the RSRC Fork, but that fork is empty.\n");
}
// This will return NULL if there is an error, or if there are no resources
rd = hfs_parse_resource_fork(fs_file);
// TODO: Should check the errnum here to see if there was an error
if (rd != NULL) {
tsk_fprintf(hFile, "\nResources:\n");
while (rd) {
tsk_fprintf(hFile,
" Type: %s \tID: %-5u \tOffset: %-5u \tSize: %-5u \tName: %s\n",
rd->type, rd->id, rd->offset, rd->length, rd->name);
rd = rd->next;
}
}
// This is OK to call with NULL
free_res_descriptor(rd);
tsk_fs_file_close(fs_file);
return 0;
}
static TSK_FS_ATTR_TYPE_ENUM
hfs_get_default_attr_type(const TSK_FS_FILE * a_file)
{
// The HFS+ special files have a default attr type of "Default"
TSK_INUM_T inum = a_file->meta->addr;
if (inum == 3 || // Extents File
inum == 4 || // Catalog File
inum == 5 || // Bad Blocks File
inum == 6 || // Block Map (Allocation File)
inum == 7 || // Startup File
inum == 8 || // Attributes File
inum == 14 || // Not sure if these two will actually work. I don't see
inum == 15) // any code to load the attrs of these files, if they exist.
return TSK_FS_ATTR_TYPE_DEFAULT;
// The "regular" files and symbolic links have a DATA fork with type "DATA"
if (a_file->meta->type == TSK_FS_META_TYPE_REG ||
a_file->meta->type == TSK_FS_META_TYPE_LNK)
// This should be an HFS-specific type.
return TSK_FS_ATTR_TYPE_HFS_DATA;
// We've got to return *something* for every file, so we return this.
return TSK_FS_ATTR_TYPE_DEFAULT;
}
static void
hfs_close(TSK_FS_INFO * fs)
{
HFS_INFO *hfs = (HFS_INFO *) fs;
// We'll grab this lock a bit early.
tsk_take_lock(&(hfs->metadata_dir_cache_lock));
fs->tag = 0;
free(hfs->fs);
if (hfs->catalog_file) {
tsk_fs_file_close(hfs->catalog_file);
hfs->catalog_attr = NULL;
}
if (hfs->blockmap_file) {
tsk_fs_file_close(hfs->blockmap_file);
hfs->blockmap_attr = NULL;
}
if (hfs->meta_dir) {
tsk_fs_dir_close(hfs->meta_dir);
hfs->meta_dir = NULL;
}
if (hfs->dir_meta_dir) {
tsk_fs_dir_close(hfs->dir_meta_dir);
hfs->dir_meta_dir = NULL;
}
if (hfs->extents_file) {
tsk_fs_file_close(hfs->extents_file);
hfs->extents_file = NULL;
}
tsk_release_lock(&(hfs->metadata_dir_cache_lock));
tsk_deinit_lock(&(hfs->metadata_dir_cache_lock));
tsk_fs_free((TSK_FS_INFO *)hfs);
}
/* hfs_open - open an hfs file system
*
* Return NULL on error (or not an HFS or HFS+ file system)
* */
TSK_FS_INFO *
hfs_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset,
TSK_FS_TYPE_ENUM ftype, uint8_t test)
{
HFS_INFO *hfs;
unsigned int len;
TSK_FS_INFO *fs;
ssize_t cnt;
TSK_FS_FILE *file; // The root directory, or the metadata directories
TSK_INUM_T inum; // The inum (or CNID) of the metadata directories
int8_t result; // of tsk_fs_path2inum()
tsk_error_reset();
if (TSK_FS_TYPE_ISHFS(ftype) == 0) {
tsk_error_set_errno(TSK_ERR_FS_ARG);
tsk_error_set_errstr("Invalid FS Type in hfs_open");
return NULL;
}
if ((hfs = (HFS_INFO *) tsk_fs_malloc(sizeof(HFS_INFO))) == NULL)
return NULL;
fs = &(hfs->fs_info);
fs->ftype = TSK_FS_TYPE_HFS;
fs->duname = "Allocation Block";
fs->tag = TSK_FS_INFO_TAG;
fs->flags = 0;
fs->img_info = img_info;
fs->offset = offset;
/*
* Read the superblock.
*/
len = sizeof(hfs_plus_vh);
if ((hfs->fs = (hfs_plus_vh *) tsk_malloc(len)) == NULL) {
fs->tag = 0;
tsk_fs_free((TSK_FS_INFO *)hfs);
return NULL;
}
if (hfs_checked_read_random(fs, (char *) hfs->fs, len,
(TSK_OFF_T) HFS_VH_OFF)) {
tsk_error_set_errstr2("hfs_open: superblock");
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
return NULL;
}
/*
* Verify we are looking at an HFS+ image
*/
if (tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSPLUS) &&
tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSX) &&
tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFS)) {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_MAGIC);
tsk_error_set_errstr("not an HFS+ file system (magic)");
return NULL;
}
/*
* Handle an HFS-wrapped HFS+ image, which is a HFS volume that contains
* the HFS+ volume inside of it.
*/
if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFS) {
hfs_mdb *wrapper_sb = (hfs_mdb *) hfs->fs;
// Verify that we are setting a wrapper and not a normal HFS volume
if ((tsk_getu16(fs->endian,
wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSPLUS)
|| (tsk_getu16(fs->endian,
wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSX)) {
TSK_FS_INFO *fs_info2;
// offset in sectors to start of first HFS block
uint16_t drAlBlSt =
tsk_getu16(fs->endian, wrapper_sb->drAlBlSt);
// size of each HFS block
uint32_t drAlBlkSiz =
tsk_getu32(fs->endian, wrapper_sb->drAlBlkSiz);
// start of embedded FS
uint16_t startBlock = tsk_getu16(fs->endian,
wrapper_sb->drEmbedExtent_startBlock);
// calculate the offset; 512 here is intentional.
// TN1150 says "The drAlBlSt field contains the offset, in
// 512-byte blocks, of the wrapper's allocation block 0 relative
// to the start of the volume"
TSK_OFF_T hfsplus_offset =
(drAlBlSt * (TSK_OFF_T) 512) +
(drAlBlkSiz * (TSK_OFF_T) startBlock);
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: HFS+/HFSX within HFS wrapper at byte offset %"
PRIuOFF "\n", hfsplus_offset);
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
/* just re-open with the new offset, then record the offset */
if (hfsplus_offset == 0) {
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("HFS+ offset is zero");
return NULL;
}
fs_info2 =
hfs_open(img_info, offset + hfsplus_offset, ftype, test);
if (fs_info2)
((HFS_INFO *) fs_info2)->hfs_wrapper_offset =
hfsplus_offset;
return fs_info2;
}
else {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_MAGIC);
tsk_error_set_errstr
("HFS file systems (other than wrappers HFS+/HFSX file systems) are not supported");
return NULL;
}
}
fs->block_count = tsk_getu32(fs->endian, hfs->fs->blk_cnt);
fs->first_block = 0;
fs->last_block = fs->last_block_act = fs->block_count - 1;
/* this isn't really accurate; fs->block_size reports only the size
of the allocation block; the size of the device block has to be
found from the device (allocation block size should always be
larger than device block size and an even multiple of the device
block size) */
fs->dev_bsize = fs->block_size =
tsk_getu32(fs->endian, hfs->fs->blk_sz);
// determine the last block we have in this image
if (fs->block_size <= 1) {
fs->tag = 0;
free(hfs->fs);
tsk_fs_free((TSK_FS_INFO *)hfs);
tsk_error_set_errno(TSK_ERR_FS_CORRUPT);
tsk_error_set_errstr("HFS+ allocation block size too small");
return NULL;
}
if ((TSK_DADDR_T) ((img_info->size - offset) / fs->block_size) <
fs->block_count)
fs->last_block_act =
(img_info->size - offset) / fs->block_size - 1;
// Initialize the lock
tsk_init_lock(&(hfs->metadata_dir_cache_lock));
/*
* Set function pointers
*/
fs->inode_walk = hfs_inode_walk;
fs->block_walk = hfs_block_walk;
fs->block_getflags = hfs_block_getflags;
fs->load_attrs = hfs_load_attrs;
fs->get_default_attr_type = hfs_get_default_attr_type;
fs->file_add_meta = hfs_inode_lookup;
fs->dir_open_meta = hfs_dir_open_meta;
fs->fsstat = hfs_fsstat;
fs->fscheck = hfs_fscheck;
fs->istat = hfs_istat;
fs->close = hfs_close;
// lazy loading of block map
hfs->blockmap_file = NULL;
hfs->blockmap_attr = NULL;
hfs->blockmap_cache_start = -1;
hfs->blockmap_cache_len = 0;
fs->first_inum = HFS_ROOT_INUM;
fs->root_inum = HFS_ROOT_INUM;
fs->last_inum = HFS_FIRST_USER_CNID - 1; // we will later increase this
fs->inum_count = fs->last_inum - fs->first_inum + 1;
/* We will load the extents file data when we need it */
hfs->extents_file = NULL;
hfs->extents_attr = NULL;
if (tsk_getu32(fs->endian,
hfs->fs->start_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Startup File is not present.\n");
hfs->has_startup_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_open: Startup File is present.\n");
hfs->has_startup_file = TRUE;
}
if (tsk_getu32(fs->endian, hfs->fs->ext_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Extents File (and Badblocks File) is not present.\n");
hfs->has_extents_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Extents File (and BadBlocks File) is present.\n");
hfs->has_extents_file = TRUE;
}
if (tsk_getu32(fs->endian, hfs->fs->attr_file.extents[0].blk_cnt) == 0) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Optional Attributes File is not present.\n");
hfs->has_attributes_file = FALSE;
}
else {
if (tsk_verbose)
tsk_fprintf(stderr, "hfs_open: Attributes File is present.\n");
hfs->has_attributes_file = TRUE;
}
/* Load the catalog file though */
if ((hfs->catalog_file =
tsk_fs_file_open_meta(fs, NULL,
HFS_CATALOG_FILE_ID)) == NULL) {
hfs_close(fs);
return NULL;
}
/* cache the data attribute */
hfs->catalog_attr =
tsk_fs_attrlist_get(hfs->catalog_file->meta->attr,
TSK_FS_ATTR_TYPE_DEFAULT);
if (!hfs->catalog_attr) {
hfs_close(fs);
tsk_error_errstr2_concat
(" - Data Attribute not found in Catalog File");
return NULL;
}
// cache the catalog file header
cnt = tsk_fs_attr_read(hfs->catalog_attr, 14,
(char *) &(hfs->catalog_header),
sizeof(hfs_btree_header_record), 0);
if (cnt != sizeof(hfs_btree_header_record)) {
if (cnt >= 0) {
tsk_error_reset();
tsk_error_set_errno(TSK_ERR_FS_READ);
}
hfs_close(fs);
tsk_error_set_errstr2("hfs_open: Error reading catalog header");
return NULL;
}
if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSPLUS)
hfs->is_case_sensitive = 0;
else if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSX) {
if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_SENS)
hfs->is_case_sensitive = 1;
else if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_INSENS)
hfs->is_case_sensitive = 0;
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: invalid value (0x%02" PRIx8
") for key compare type; using case-insensitive\n",
hfs->catalog_header.compType);
hfs->is_case_sensitive = 0;
}
}
else {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: unknown HFS+/HFSX version (%" PRIu16 "\n",
tsk_getu16(fs->endian, hfs->fs->version));
hfs->is_case_sensitive = 0;
}
// update the numbers.
fs->last_inum = hfs_find_highest_inum(hfs);
fs->inum_count = fs->last_inum + 1;
snprintf((char *) fs->fs_id, 17, "%08" PRIx32 "%08" PRIx32,
tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID1]),
tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID2]));
fs->fs_id_used = 16;
/* journal */
fs->jblk_walk = hfs_jblk_walk;
fs->jentry_walk = hfs_jentry_walk;
fs->jopen = hfs_jopen;
fs->name_cmp = hfs_name_cmp;
fs->journ_inum = 0;
/* Creation Times */
// First, the root
file = tsk_fs_file_open_meta(fs, NULL, 2);
if (file != NULL) {
hfs->root_crtime = file->meta->crtime;
hfs->has_root_crtime = TRUE;
tsk_fs_file_close(file);
}
else {
hfs->has_root_crtime = FALSE;
}
file = NULL;
// disable hard link traversal while finding the hard
// link directories themselves (to prevent problems if
// there are hard links in the root directory)
hfs->meta_inum = 0;
hfs->meta_dir_inum = 0;
// Now the (file) metadata directory
// The metadata directory is a sub-directory of the root. Its name begins with four nulls, followed
// by "HFS+ Private Data". The file system parsing code replaces nulls in filenames with UTF8_NULL_REPLACE.
// In the released version of TSK, this replacement is the character '^'.
// NOTE: There is a standard Unicode replacement which is 0xfffd in UTF16 and 0xEF 0xBF 0xBD in UTF8.
// Systems that require the standard definition can redefine UTF8_NULL_REPLACE and UTF16_NULL_REPLACE
// in tsk_hfs.h
hfs->has_meta_crtime = FALSE;
result =
tsk_fs_path2inum(fs,
"/" UTF8_NULL_REPLACE UTF8_NULL_REPLACE UTF8_NULL_REPLACE
UTF8_NULL_REPLACE "HFS+ Private Data", &inum, NULL);
if (result == 0) {
TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum);
if (file_tmp != NULL) {
hfs->meta_crtime = file_tmp->meta->crtime;
hfs->has_meta_crtime = TRUE;
hfs->meta_inum = inum;
tsk_fs_file_close(file_tmp);
}
}
// Now, the directory metadata directory
// The "directory" metadata directory, where hardlinked directories actually live, is a subdirectory
// of the root. The beginning of the name of this directory is ".HFS+ Private Directory Data" which
// is followed by a carriage return (ASCII 13).
hfs->has_meta_dir_crtime = FALSE;
result =
tsk_fs_path2inum(fs, "/.HFS+ Private Directory Data\r", &inum,
NULL);
if (result == 0) {
TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum);
if (file_tmp != NULL) {
hfs->metadir_crtime = file_tmp->meta->crtime;
hfs->has_meta_dir_crtime = TRUE;
hfs->meta_dir_inum = inum;
tsk_fs_file_close(file_tmp);
}
}
if (hfs->has_root_crtime && hfs->has_meta_crtime
&& hfs->has_meta_dir_crtime) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Creation times for key folders have been read and cached.\n");
}
if (!hfs->has_root_crtime) {
if (tsk_verbose)
tsk_fprintf(stderr,
"hfs_open: Warning: Could not open the root directory. "
"Hard link detection and some other functions will be impaired\n");
}
else if (tsk_verbose) {
tsk_fprintf(stderr,
"hfs_open: The root directory is accessible.\n");
}
if (tsk_verbose) {
if (hfs->has_meta_crtime)
tsk_fprintf(stderr,
"hfs_open: \"/^^^^HFS+ Private Data\" metadata folder is accessible.\n");
else
tsk_fprintf(stderr,
"hfs_open: Optional \"^^^^HFS+ Private Data\" metadata folder is not accessible, or does not exist.\n");
if (hfs->has_meta_dir_crtime)
tsk_fprintf(stderr,
"hfs_open: \"/HFS+ Private Directory Data^\" metadata folder is accessible.\n");
else
tsk_fprintf(stderr,
"hfs_open: Optional \"/HFS+ Private Directory Data^\" metadata folder is not accessible, or does not exist.\n");
}
// These caches will be set, if they are needed.
hfs->meta_dir = NULL;
hfs->dir_meta_dir = NULL;
return fs;
}
/*
* Error Handling
*/
/**
* Call this when an error is first detected. It sets the error code and it also
* sets the primary error string, describing the lowest level of error. (Actually,
* it appends to the error string.)
*
* If the error code is already set, then this appends to the primary error
* string an hex representation of the new error code, plus the new error message.
*
* @param errnum The desired error code
* @param errstr The format string for the error message
*/
void
error_detected(uint32_t errnum, char *errstr, ...)
{
va_list args;
va_start(args, errstr);
{
TSK_ERROR_INFO *errInfo = tsk_error_get_info();
char *loc_errstr = errInfo->errstr;
if (errInfo->t_errno == 0)
errInfo->t_errno = errnum;
else {
//This should not happen! We don't want to wipe out the existing error
//code, so we write the new code into the error string, in hex.
size_t sl = strlen(errstr);
snprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
" Next errnum: 0x%x ", errnum);
}
if (errstr != NULL) {
size_t sl = strlen(loc_errstr);
vsnprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
errstr, args);
}
}
va_end(args);
}
/**
* Call this when a called TSK function returns an error. Presumably, that
* function will have set the error code and the primary error string. This
* *appends* to the secondary error string. It should be called to describe
* the context of the call. If no error code has been set, then this sets a
* default code so that it is not zero.
*
* @param errstr The format string for the error message
*/
void
error_returned(char *errstr, ...)
{
va_list args;
va_start(args, errstr);
{
TSK_ERROR_INFO *errInfo = tsk_error_get_info();
char *loc_errstr2 = errInfo->errstr2;
if (errInfo->t_errno == 0)
errInfo->t_errno = TSK_ERR_AUX_GENERIC;
if (errstr != NULL) {
size_t sl = strlen(loc_errstr2);
vsnprintf(loc_errstr2 + sl, TSK_ERROR_STRING_MAX_LENGTH - sl,
errstr, args);
}
}
va_end(args);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_451_0 |
crossvul-cpp_data_bad_5298_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% H H DDDD RRRR %
% H H D D R R %
% HHHHH D D RRRR %
% H H D D R R %
% H H DDDD R R %
% %
% %
% Read/Write Radiance RGBE Image Format %
% %
% Software Design %
% Cristy %
% July 1992 %
% %
% %
% 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 "MagickCore/studio.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/colorspace.h"
#include "MagickCore/colorspace-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/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/property.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteHDRImage(const ImageInfo *,Image *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s H D R %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsHDR() returns MagickTrue if the image format type, identified by the
% magick string, is Radiance RGBE image format.
%
% The format of the IsHDR method is:
%
% MagickBooleanType IsHDR(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 IsHDR(const unsigned char *magick,
const size_t length)
{
if (length < 10)
return(MagickFalse);
if (LocaleNCompare((const char *) magick,"#?RADIANCE",10) == 0)
return(MagickTrue);
if (LocaleNCompare((const char *) magick,"#?RGBE",6) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadHDRImage() reads the Radiance RGBE image format 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 ReadHDRImage method is:
%
% Image *ReadHDRImage(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 *ReadHDRImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
format[MagickPathExtent],
keyword[MagickPathExtent],
tag[MagickPathExtent],
value[MagickPathExtent];
double
gamma;
Image
*image;
int
c;
MagickBooleanType
status,
value_expected;
register Quantum
*q;
register ssize_t
i,
x;
register unsigned char
*p;
ssize_t
count,
y;
unsigned char
*end,
pixel[4],
*pixels;
/*
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);
}
/*
Decode image header.
*/
image->columns=0;
image->rows=0;
*format='\0';
c=ReadBlobByte(image);
if (c == EOF)
{
image=DestroyImage(image);
return((Image *) NULL);
}
while (isgraph(c) && (image->columns == 0) && (image->rows == 0))
{
if (c == (int) '#')
{
char
*comment;
register char
*p;
size_t
length;
/*
Read comment-- any text between # and end-of-line.
*/
length=MagickPathExtent;
comment=AcquireString((char *) NULL);
for (p=comment; comment != (char *) NULL; p++)
{
c=ReadBlobByte(image);
if ((c == EOF) || (c == (int) '\n'))
break;
if ((size_t) (p-comment+1) >= length)
{
*p='\0';
length<<=1;
comment=(char *) ResizeQuantumMemory(comment,length+
MagickPathExtent,sizeof(*comment));
if (comment == (char *) NULL)
break;
p=comment+strlen(comment);
}
*p=(char) c;
}
if (comment == (char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
*p='\0';
(void) SetImageProperty(image,"comment",comment,exception);
comment=DestroyString(comment);
c=ReadBlobByte(image);
}
else
if (isalnum(c) == MagickFalse)
c=ReadBlobByte(image);
else
{
register char
*p;
/*
Determine a keyword and its value.
*/
p=keyword;
do
{
if ((size_t) (p-keyword) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
} while (isalnum(c) || (c == '_'));
*p='\0';
value_expected=MagickFalse;
while ((isspace((int) ((unsigned char) c)) != 0) || (c == '='))
{
if (c == '=')
value_expected=MagickTrue;
c=ReadBlobByte(image);
}
if (LocaleCompare(keyword,"Y") == 0)
value_expected=MagickTrue;
if (value_expected == MagickFalse)
continue;
p=value;
while ((c != '\n') && (c != '\0') && (c != EOF))
{
if ((size_t) (p-value) < (MagickPathExtent-1))
*p++=c;
c=ReadBlobByte(image);
}
*p='\0';
/*
Assign a value to the specified keyword.
*/
switch (*keyword)
{
case 'F':
case 'f':
{
if (LocaleCompare(keyword,"format") == 0)
{
(void) CopyMagickString(format,value,MagickPathExtent);
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'G':
case 'g':
{
if (LocaleCompare(keyword,"gamma") == 0)
{
image->gamma=StringToDouble(value,(char **) NULL);
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'P':
case 'p':
{
if (LocaleCompare(keyword,"primaries") == 0)
{
float
chromaticity[6],
white_point[2];
int
count;
count=sscanf(value,"%g %g %g %g %g %g %g %g",&chromaticity[0],
&chromaticity[1],&chromaticity[2],&chromaticity[3],
&chromaticity[4],&chromaticity[5],&white_point[0],
&white_point[1]);
if (count == 8)
{
image->chromaticity.red_primary.x=chromaticity[0];
image->chromaticity.red_primary.y=chromaticity[1];
image->chromaticity.green_primary.x=chromaticity[2];
image->chromaticity.green_primary.y=chromaticity[3];
image->chromaticity.blue_primary.x=chromaticity[4];
image->chromaticity.blue_primary.y=chromaticity[5];
image->chromaticity.white_point.x=white_point[0],
image->chromaticity.white_point.y=white_point[1];
}
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
case 'Y':
case 'y':
{
char
target[] = "Y";
if (strcmp(keyword,target) == 0)
{
int
height,
width;
if (sscanf(value,"%d +X %d",&height,&width) == 2)
{
image->columns=(size_t) width;
image->rows=(size_t) height;
}
break;
}
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
default:
{
(void) FormatLocaleString(tag,MagickPathExtent,"hdr:%s",keyword);
(void) SetImageProperty(image,tag,value,exception);
break;
}
}
}
if ((image->columns == 0) && (image->rows == 0))
while (isspace((int) ((unsigned char) c)) != 0)
c=ReadBlobByte(image);
}
if ((LocaleCompare(format,"32-bit_rle_rgbe") != 0) &&
(LocaleCompare(format,"32-bit_rle_xyze") != 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if ((image->columns == 0) || (image->rows == 0))
ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize");
(void) SetImageColorspace(image,RGBColorspace,exception);
if (LocaleCompare(format,"32-bit_rle_xyze") == 0)
(void) SetImageColorspace(image,XYZColorspace,exception);
image->compression=(image->columns < 8) || (image->columns > 0x7ffff) ?
NoCompression : RLECompression;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
/*
Read RGBE (red+green+blue+exponent) pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
if (image->compression != RLECompression)
{
count=ReadBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
else
{
count=ReadBlob(image,4*sizeof(*pixel),pixel);
if (count != 4)
break;
if ((size_t) ((((size_t) pixel[2]) << 8) | pixel[3]) != image->columns)
{
(void) memcpy(pixels,pixel,4*sizeof(*pixel));
count=ReadBlob(image,4*(image->columns-1)*sizeof(*pixels),pixels+4);
image->compression=NoCompression;
}
else
{
p=pixels;
for (i=0; i < 4; i++)
{
end=&pixels[(i+1)*image->columns];
while (p < end)
{
count=ReadBlob(image,2*sizeof(*pixel),pixel);
if (count < 1)
break;
if (pixel[0] > 128)
{
count=(ssize_t) pixel[0]-128;
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
while (count-- > 0)
*p++=pixel[1];
}
else
{
count=(ssize_t) pixel[0];
if ((count == 0) || (count > (ssize_t) (end-p)))
break;
*p++=pixel[1];
if (--count > 0)
{
count=ReadBlob(image,(size_t) count*sizeof(*p),p);
if (count < 1)
break;
p+=count;
}
}
}
}
}
}
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->compression == RLECompression)
{
pixel[0]=pixels[x];
pixel[1]=pixels[x+image->columns];
pixel[2]=pixels[x+2*image->columns];
pixel[3]=pixels[x+3*image->columns];
}
else
{
pixel[0]=pixels[i++];
pixel[1]=pixels[i++];
pixel[2]=pixels[i++];
pixel[3]=pixels[i++];
}
SetPixelRed(image,0,q);
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
if (pixel[3] != 0)
{
gamma=pow(2.0,pixel[3]-(128.0+8.0));
SetPixelRed(image,ClampToQuantum(QuantumRange*gamma*pixel[0]),q);
SetPixelGreen(image,ClampToQuantum(QuantumRange*gamma*pixel[1]),q);
SetPixelBlue(image,ClampToQuantum(QuantumRange*gamma*pixel[2]),q);
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterHDRImage() adds attributes for the Radiance RGBE 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 RegisterHDRImage method is:
%
% size_t RegisterHDRImage(void)
%
*/
ModuleExport size_t RegisterHDRImage(void)
{
MagickInfo
*entry;
entry=AcquireMagickInfo("HDR","HDR","Radiance RGBE image format");
entry->decoder=(DecodeImageHandler *) ReadHDRImage;
entry->encoder=(EncodeImageHandler *) WriteHDRImage;
entry->magick=(IsImageFormatHandler *) IsHDR;
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterHDRImage() removes format registrations made by the
% HDR module from the list of supported formats.
%
% The format of the UnregisterHDRImage method is:
%
% UnregisterHDRImage(void)
%
*/
ModuleExport void UnregisterHDRImage(void)
{
(void) UnregisterMagickInfo("HDR");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e H D R I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteHDRImage() writes an image in the Radience RGBE image format.
%
% The format of the WriteHDRImage method is:
%
% MagickBooleanType WriteHDRImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static size_t HDRWriteRunlengthPixels(Image *image,unsigned char *pixels)
{
#define MinimumRunlength 4
register size_t
p,
q;
size_t
runlength;
ssize_t
count,
previous_count;
unsigned char
pixel[2];
for (p=0; p < image->columns; )
{
q=p;
runlength=0;
previous_count=0;
while ((runlength < MinimumRunlength) && (q < image->columns))
{
q+=runlength;
previous_count=(ssize_t) runlength;
runlength=1;
while ((pixels[q] == pixels[q+runlength]) &&
((q+runlength) < image->columns) && (runlength < 127))
runlength++;
}
if ((previous_count > 1) && (previous_count == (ssize_t) (q-p)))
{
pixel[0]=(unsigned char) (128+previous_count);
pixel[1]=pixels[p];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p=q;
}
while (p < q)
{
count=(ssize_t) (q-p);
if (count > 128)
count=128;
pixel[0]=(unsigned char) count;
if (WriteBlob(image,sizeof(*pixel),pixel) < 1)
break;
if (WriteBlob(image,(size_t) count*sizeof(*pixel),&pixels[p]) < 1)
break;
p+=count;
}
if (runlength >= MinimumRunlength)
{
pixel[0]=(unsigned char) (128+runlength);
pixel[1]=pixels[q];
if (WriteBlob(image,2*sizeof(*pixel),pixel) < 1)
break;
p+=runlength;
}
}
return(p);
}
static MagickBooleanType WriteHDRImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
header[MagickPathExtent];
const char
*property;
MagickBooleanType
status;
register const Quantum
*p;
register ssize_t
i,
x;
size_t
length;
ssize_t
count,
y;
unsigned char
pixel[4],
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(status);
if (IsRGBColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,RGBColorspace,exception);
/*
Write header.
*/
(void) ResetMagickMemory(header,' ',MagickPathExtent);
length=CopyMagickString(header,"#?RGBE\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
property=GetImageProperty(image,"comment",exception);
if ((property != (const char *) NULL) &&
(strchr(property,'\n') == (char *) NULL))
{
count=FormatLocaleString(header,MagickPathExtent,"#%s\n",property);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
property=GetImageProperty(image,"hdr:exposure",exception);
if (property != (const char *) NULL)
{
count=FormatLocaleString(header,MagickPathExtent,"EXPOSURE=%g\n",
strtod(property,(char **) NULL));
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
if (image->gamma != 0.0)
{
count=FormatLocaleString(header,MagickPathExtent,"GAMMA=%g\n",image->gamma);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
}
count=FormatLocaleString(header,MagickPathExtent,
"PRIMARIES=%g %g %g %g %g %g %g %g\n",
image->chromaticity.red_primary.x,image->chromaticity.red_primary.y,
image->chromaticity.green_primary.x,image->chromaticity.green_primary.y,
image->chromaticity.blue_primary.x,image->chromaticity.blue_primary.y,
image->chromaticity.white_point.x,image->chromaticity.white_point.y);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
length=CopyMagickString(header,"FORMAT=32-bit_rle_rgbe\n\n",MagickPathExtent);
(void) WriteBlob(image,length,(unsigned char *) header);
count=FormatLocaleString(header,MagickPathExtent,"-Y %.20g +X %.20g\n",
(double) image->rows,(double) image->columns);
(void) WriteBlob(image,(size_t) count,(unsigned char *) header);
/*
Write HDR pixels.
*/
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,4*
sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixel[0]=2;
pixel[1]=2;
pixel[2]=(unsigned char) (image->columns >> 8);
pixel[3]=(unsigned char) (image->columns & 0xff);
count=WriteBlob(image,4*sizeof(*pixel),pixel);
if (count != (ssize_t) (4*sizeof(*pixel)))
break;
}
i=0;
for (x=0; x < (ssize_t) image->columns; x++)
{
double
gamma;
pixel[0]=0;
pixel[1]=0;
pixel[2]=0;
pixel[3]=0;
gamma=QuantumScale*GetPixelRed(image,p);
if ((QuantumScale*GetPixelGreen(image,p)) > gamma)
gamma=QuantumScale*GetPixelGreen(image,p);
if ((QuantumScale*GetPixelBlue(image,p)) > gamma)
gamma=QuantumScale*GetPixelBlue(image,p);
if (gamma > MagickEpsilon)
{
int
exponent;
gamma=frexp(gamma,&exponent)*256.0/gamma;
pixel[0]=(unsigned char) (gamma*QuantumScale*GetPixelRed(image,p));
pixel[1]=(unsigned char) (gamma*QuantumScale*GetPixelGreen(image,p));
pixel[2]=(unsigned char) (gamma*QuantumScale*GetPixelBlue(image,p));
pixel[3]=(unsigned char) (exponent+128);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
pixels[x]=pixel[0];
pixels[x+image->columns]=pixel[1];
pixels[x+2*image->columns]=pixel[2];
pixels[x+3*image->columns]=pixel[3];
}
else
{
pixels[i++]=pixel[0];
pixels[i++]=pixel[1];
pixels[i++]=pixel[2];
pixels[i++]=pixel[3];
}
p+=GetPixelChannels(image);
}
if ((image->columns >= 8) && (image->columns <= 0x7ffff))
{
for (i=0; i < 4; i++)
length=HDRWriteRunlengthPixels(image,&pixels[i*image->columns]);
}
else
{
count=WriteBlob(image,4*image->columns*sizeof(*pixels),pixels);
if (count != (ssize_t) (4*image->columns*sizeof(*pixels)))
break;
}
status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
(void) CloseBlob(image);
return(MagickTrue);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_5298_0 |
crossvul-cpp_data_bad_157_1 | /*
* This file is part of Espruino, a JavaScript interpreter for Microcontrollers
*
* Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* ----------------------------------------------------------------------------
* This file is designed to be parsed during the build process
*
* Contains JavaScript Graphics Draw Functions
* ----------------------------------------------------------------------------
*/
#include "jswrap_graphics.h"
#include "jsutils.h"
#include "jsinteractive.h"
#include "lcd_arraybuffer.h"
#include "lcd_js.h"
#ifdef USE_LCD_SDL
#include "lcd_sdl.h"
#endif
#ifdef USE_LCD_FSMC
#include "lcd_fsmc.h"
#endif
/*JSON{
"type" : "class",
"class" : "Graphics"
}
This class provides Graphics operations that can be applied to a surface.
Use Graphics.createXXX to create a graphics object that renders in the way you want. See [the Graphics page](/Graphics) for more information.
**Note:** On boards that contain an LCD, there is a built-in 'LCD' object of type Graphics. For instance to draw a line you'd type: ```LCD.drawLine(0,0,100,100)```
*/
/*JSON{
"type" : "idle",
"generate" : "jswrap_graphics_idle"
}*/
bool jswrap_graphics_idle() {
graphicsIdle();
return false;
}
/*JSON{
"type" : "init",
"generate" : "jswrap_graphics_init"
}*/
void jswrap_graphics_init() {
#ifdef USE_LCD_FSMC
JsVar *parent = jspNewObject("LCD", "Graphics");
if (parent) {
JsVar *parentObj = jsvSkipName(parent);
JsGraphics gfx;
graphicsStructInit(&gfx);
gfx.data.type = JSGRAPHICSTYPE_FSMC;
gfx.graphicsVar = parentObj;
gfx.data.width = 320;
gfx.data.height = 240;
gfx.data.bpp = 16;
lcdInit_FSMC(&gfx);
lcdSetCallbacks_FSMC(&gfx);
graphicsSplash(&gfx);
graphicsSetVar(&gfx);
jsvUnLock2(parentObj, parent);
}
#endif
}
static bool isValidBPP(int bpp) {
return bpp==1 || bpp==2 || bpp==4 || bpp==8 || bpp==16 || bpp==24 || bpp==32; // currently one colour can't ever be spread across multiple bytes
}
/*JSON{
"type" : "staticmethod",
"class" : "Graphics",
"name" : "createArrayBuffer",
"generate" : "jswrap_graphics_createArrayBuffer",
"params" : [
["width","int32","Pixels wide"],
["height","int32","Pixels high"],
["bpp","int32","Number of bits per pixel"],
["options","JsVar",[
"An object of other options. ```{ zigzag : true/false(default), vertical_byte : true/false(default), msb : true/false(default), color_order: 'rgb'(default),'bgr',etc }```",
"zigzag = whether to alternate the direction of scanlines for rows",
"vertical_byte = whether to align bits in a byte vertically or not",
"msb = when bits<8, store pixels msb first",
"color_order = re-orders the colour values that are supplied via setColor"
]]
],
"return" : ["JsVar","The new Graphics object"],
"return_object" : "Graphics"
}
Create a Graphics object that renders to an Array Buffer. This will have a field called 'buffer' that can get used to get at the buffer itself
*/
JsVar *jswrap_graphics_createArrayBuffer(int width, int height, int bpp, JsVar *options) {
if (width<=0 || height<=0 || width>32767 || height>32767) {
jsExceptionHere(JSET_ERROR, "Invalid Size");
return 0;
}
if (!isValidBPP(bpp)) {
jsExceptionHere(JSET_ERROR, "Invalid BPP");
return 0;
}
JsVar *parent = jspNewObject(0, "Graphics");
if (!parent) return 0; // low memory
JsGraphics gfx;
graphicsStructInit(&gfx);
gfx.data.type = JSGRAPHICSTYPE_ARRAYBUFFER;
gfx.data.flags = JSGRAPHICSFLAGS_NONE;
gfx.graphicsVar = parent;
gfx.data.width = (unsigned short)width;
gfx.data.height = (unsigned short)height;
gfx.data.bpp = (unsigned char)bpp;
if (jsvIsObject(options)) {
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "zigzag", 0)))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_ZIGZAG);
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "msb", 0)))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_MSB);
if (jsvGetBoolAndUnLock(jsvObjectGetChild(options, "vertical_byte", 0))) {
if (gfx.data.bpp==1)
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_ARRAYBUFFER_VERTICAL_BYTE);
else
jsWarn("vertical_byte only works for 1bpp ArrayBuffers\n");
}
JsVar *colorv = jsvObjectGetChild(options, "color_order", 0);
if (colorv) {
if (jsvIsStringEqual(colorv, "rgb")) ; // The default
else if (!jsvIsStringEqual(colorv, "brg"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BRG);
else if (!jsvIsStringEqual(colorv, "bgr"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_BGR);
else if (!jsvIsStringEqual(colorv, "gbr"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GBR);
else if (!jsvIsStringEqual(colorv, "grb"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_GRB);
else if (!jsvIsStringEqual(colorv, "rbg"))
gfx.data.flags = (JsGraphicsFlags)(gfx.data.flags | JSGRAPHICSFLAGS_COLOR_RBG);
else
jsWarn("color_order must be 3 characters");
jsvUnLock(colorv);
}
}
lcdInit_ArrayBuffer(&gfx);
graphicsSetVar(&gfx);
return parent;
}
/*JSON{
"type" : "staticmethod",
"class" : "Graphics",
"name" : "createCallback",
"ifndef" : "SAVE_ON_FLASH",
"generate" : "jswrap_graphics_createCallback",
"params" : [
["width","int32","Pixels wide"],
["height","int32","Pixels high"],
["bpp","int32","Number of bits per pixel"],
["callback","JsVar","A function of the form ```function(x,y,col)``` that is called whenever a pixel needs to be drawn, or an object with: ```{setPixel:function(x,y,col),fillRect:function(x1,y1,x2,y2,col)}```. All arguments are already bounds checked."]
],
"return" : ["JsVar","The new Graphics object"],
"return_object" : "Graphics"
}
Create a Graphics object that renders by calling a JavaScript callback function to draw pixels
*/
JsVar *jswrap_graphics_createCallback(int width, int height, int bpp, JsVar *callback) {
if (width<=0 || height<=0 || width>32767 || height>32767) {
jsExceptionHere(JSET_ERROR, "Invalid Size");
return 0;
}
if (!isValidBPP(bpp)) {
jsExceptionHere(JSET_ERROR, "Invalid BPP");
return 0;
}
JsVar *callbackSetPixel = 0;
JsVar *callbackFillRect = 0;
if (jsvIsObject(callback)) {
jsvUnLock(callbackSetPixel);
callbackSetPixel = jsvObjectGetChild(callback, "setPixel", 0);
callbackFillRect = jsvObjectGetChild(callback, "fillRect", 0);
} else
callbackSetPixel = jsvLockAgain(callback);
if (!jsvIsFunction(callbackSetPixel)) {
jsExceptionHere(JSET_ERROR, "Expecting Callback Function or an Object but got %t", callbackSetPixel);
jsvUnLock2(callbackSetPixel, callbackFillRect);
return 0;
}
if (!jsvIsUndefined(callbackFillRect) && !jsvIsFunction(callbackFillRect)) {
jsExceptionHere(JSET_ERROR, "Expecting Callback Function or an Object but got %t", callbackFillRect);
jsvUnLock2(callbackSetPixel, callbackFillRect);
return 0;
}
JsVar *parent = jspNewObject(0, "Graphics");
if (!parent) return 0; // low memory
JsGraphics gfx;
graphicsStructInit(&gfx);
gfx.data.type = JSGRAPHICSTYPE_JS;
gfx.graphicsVar = parent;
gfx.data.width = (unsigned short)width;
gfx.data.height = (unsigned short)height;
gfx.data.bpp = (unsigned char)bpp;
lcdInit_JS(&gfx, callbackSetPixel, callbackFillRect);
graphicsSetVar(&gfx);
jsvUnLock2(callbackSetPixel, callbackFillRect);
return parent;
}
#ifdef USE_LCD_SDL
/*JSON{
"type" : "staticmethod",
"class" : "Graphics",
"name" : "createSDL",
"ifdef" : "USE_LCD_SDL",
"generate" : "jswrap_graphics_createSDL",
"params" : [
["width","int32","Pixels wide"],
["height","int32","Pixels high"]
],
"return" : ["JsVar","The new Graphics object"],
"return_object" : "Graphics"
}
Create a Graphics object that renders to SDL window (Linux-based devices only)
*/
JsVar *jswrap_graphics_createSDL(int width, int height) {
if (width<=0 || height<=0 || width>32767 || height>32767) {
jsExceptionHere(JSET_ERROR, "Invalid Size");
return 0;
}
JsVar *parent = jspNewObject(0, "Graphics");
if (!parent) return 0; // low memory
JsGraphics gfx;
graphicsStructInit(&gfx);
gfx.data.type = JSGRAPHICSTYPE_SDL;
gfx.graphicsVar = parent;
gfx.data.width = (unsigned short)width;
gfx.data.height = (unsigned short)height;
gfx.data.bpp = 32;
lcdInit_SDL(&gfx);
graphicsSetVar(&gfx);
return parent;
}
#endif
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getWidth",
"generate_full" : "jswrap_graphics_getWidthOrHeight(parent, false)",
"return" : ["int","The width of the LCD"]
}
The width of the LCD
*/
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getHeight",
"generate_full" : "jswrap_graphics_getWidthOrHeight(parent, true)",
"return" : ["int","The height of the LCD"]
}
The height of the LCD
*/
int jswrap_graphics_getWidthOrHeight(JsVar *parent, bool height) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0;
if (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY)
height=!height;
return height ? gfx.data.height : gfx.data.width;
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "clear",
"generate" : "jswrap_graphics_clear"
}
Clear the LCD with the Background Color
*/
void jswrap_graphics_clear(JsVar *parent) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsClear(&gfx);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "fillRect",
"generate" : "jswrap_graphics_fillRect",
"params" : [
["x1","int32","The left"],
["y1","int32","The top"],
["x2","int32","The right"],
["y2","int32","The bottom"]
]
}
Fill a rectangular area in the Foreground Color
*/
void jswrap_graphics_fillRect(JsVar *parent, int x1, int y1, int x2, int y2) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsFillRect(&gfx, (short)x1,(short)y1,(short)x2,(short)y2);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "drawRect",
"generate" : "jswrap_graphics_drawRect",
"params" : [
["x1","int32","The left"],
["y1","int32","The top"],
["x2","int32","The right"],
["y2","int32","The bottom"]
]
}
Draw an unfilled rectangle 1px wide in the Foreground Color
*/
void jswrap_graphics_drawRect(JsVar *parent, int x1, int y1, int x2, int y2) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsDrawRect(&gfx, (short)x1,(short)y1,(short)x2,(short)y2);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "fillCircle",
"generate" : "jswrap_graphics_fillCircle",
"params" : [
["x","int32","The X axis"],
["y","int32","The Y axis"],
["rad","int32","The circle radius"]
]
}
Draw a filled circle in the Foreground Color
*/
void jswrap_graphics_fillCircle(JsVar *parent, int x, int y, int rad) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsFillCircle(&gfx, (short)x,(short)y,(short)rad);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "drawCircle",
"generate" : "jswrap_graphics_drawCircle",
"params" : [
["x","int32","The X axis"],
["y","int32","The Y axis"],
["rad","int32","The circle radius"]
]
}
Draw an unfilled circle 1px wide in the Foreground Color
*/
void jswrap_graphics_drawCircle(JsVar *parent, int x, int y, int rad) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsDrawCircle(&gfx, (short)x,(short)y,(short)rad);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getPixel",
"generate" : "jswrap_graphics_getPixel",
"params" : [
["x","int32","The left"],
["y","int32","The top"]
],
"return" : ["int32","The color"]
}
Get a pixel's color
*/
int jswrap_graphics_getPixel(JsVar *parent, int x, int y) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0;
return (int)graphicsGetPixel(&gfx, (short)x, (short)y);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setPixel",
"generate" : "jswrap_graphics_setPixel",
"params" : [
["x","int32","The left"],
["y","int32","The top"],
["col","JsVar","The color"]
]
}
Set a pixel's color
*/
void jswrap_graphics_setPixel(JsVar *parent, int x, int y, JsVar *color) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
unsigned int col = gfx.data.fgColor;
if (!jsvIsUndefined(color))
col = (unsigned int)jsvGetInteger(color);
graphicsSetPixel(&gfx, (short)x, (short)y, col);
gfx.data.cursorX = (short)x;
gfx.data.cursorY = (short)y;
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setColor",
"generate_full" : "jswrap_graphics_setColorX(parent, r,g,b, true)",
"params" : [
["r","JsVar","Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order"],
["g","JsVar","Green (between 0 and 1)"],
["b","JsVar","Blue (between 0 and 1)"]
]
}
Set the color to use for subsequent drawing operations
*/
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setBgColor",
"generate_full" : "jswrap_graphics_setColorX(parent, r,g,b, false)",
"params" : [
["r","JsVar","Red (between 0 and 1) OR an integer representing the color in the current bit depth and color order"],
["g","JsVar","Green (between 0 and 1)"],
["b","JsVar","Blue (between 0 and 1)"]
]
}
Set the background color to use for subsequent drawing operations
*/
void jswrap_graphics_setColorX(JsVar *parent, JsVar *r, JsVar *g, JsVar *b, bool isForeground) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
unsigned int color = 0;
JsVarFloat rf, gf, bf;
rf = jsvGetFloat(r);
gf = jsvGetFloat(g);
bf = jsvGetFloat(b);
if (!jsvIsUndefined(g) && !jsvIsUndefined(b)) {
int ri = (int)(rf*256);
int gi = (int)(gf*256);
int bi = (int)(bf*256);
if (ri>255) ri=255;
if (gi>255) gi=255;
if (bi>255) bi=255;
if (ri<0) ri=0;
if (gi<0) gi=0;
if (bi<0) bi=0;
// Check if we need to twiddle colors
int colorMask = gfx.data.flags & JSGRAPHICSFLAGS_COLOR_MASK;
if (colorMask) {
int tmpr, tmpg, tmpb;
tmpr = ri;
tmpg = gi;
tmpb = bi;
switch (colorMask) {
case JSGRAPHICSFLAGS_COLOR_BRG:
ri = tmpb;
gi = tmpr;
bi = tmpg;
break;
case JSGRAPHICSFLAGS_COLOR_BGR:
ri = tmpb;
bi = tmpr;
break;
case JSGRAPHICSFLAGS_COLOR_GBR:
ri = tmpg;
gi = tmpb;
bi = tmpr;
break;
case JSGRAPHICSFLAGS_COLOR_GRB:
ri = tmpg;
gi = tmpr;
break;
case JSGRAPHICSFLAGS_COLOR_RBG:
gi = tmpb;
bi = tmpg;
break;
default: break;
}
}
if (gfx.data.bpp==16) {
color = (unsigned int)((bi>>3) | (gi>>2)<<5 | (ri>>3)<<11);
} else if (gfx.data.bpp==32) {
color = 0xFF000000 | (unsigned int)(bi | (gi<<8) | (ri<<16));
} else if (gfx.data.bpp==24) {
color = (unsigned int)(bi | (gi<<8) | (ri<<16));
} else
color = (unsigned int)(((ri+gi+bi)>=384) ? 0xFFFFFFFF : 0);
} else {
// just rgb
color = (unsigned int)jsvGetInteger(r);
}
if (isForeground)
gfx.data.fgColor = color;
else
gfx.data.bgColor = color;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getColor",
"generate_full" : "jswrap_graphics_getColorX(parent, true)",
"return" : ["int","The integer value of the colour"]
}
Get the color to use for subsequent drawing operations
*/
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getBgColor",
"generate_full" : "jswrap_graphics_getColorX(parent, false)",
"return" : ["int","The integer value of the colour"]
}
Get the background color to use for subsequent drawing operations
*/
JsVarInt jswrap_graphics_getColorX(JsVar *parent, bool isForeground) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0;
return (JsVarInt)((isForeground ? gfx.data.fgColor : gfx.data.bgColor) & ((1UL<<gfx.data.bpp)-1));
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setFontBitmap",
"generate_full" : "jswrap_graphics_setFontSizeX(parent, JSGRAPHICS_FONTSIZE_4X6, false)"
}
Make subsequent calls to `drawString` use the built-in 4x6 pixel bitmapped Font
*/
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setFontVector",
"ifndef" : "SAVE_ON_FLASH",
"generate_full" : "jswrap_graphics_setFontSizeX(parent, size, true)",
"params" : [
["size","int32","The height of the font, as an integer"]
]
}
Make subsequent calls to `drawString` use a Vector Font of the given height
*/
void jswrap_graphics_setFontSizeX(JsVar *parent, int size, bool checkValid) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
if (checkValid) {
if (size<1) size=1;
if (size>1023) size=1023;
}
if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) {
jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_BMP);
jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH);
jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT);
jsvObjectRemoveChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR);
}
gfx.data.fontSize = (short)size;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setFontCustom",
"generate" : "jswrap_graphics_setFontCustom",
"params" : [
["bitmap","JsVar","A column-first, MSB-first, 1bpp bitmap containing the font bitmap"],
["firstChar","int32","The first character in the font - usually 32 (space)"],
["width","JsVar","The width of each character in the font. Either an integer, or a string where each character represents the width"],
["height","int32","The height as an integer"]
]
}
Make subsequent calls to `drawString` use a Custom Font of the given height. See the [Fonts page](http://www.espruino.com/Fonts) for more
information about custom fonts and how to create them.
*/
void jswrap_graphics_setFontCustom(JsVar *parent, JsVar *bitmap, int firstChar, JsVar *width, int height) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
if (!jsvIsString(bitmap)) {
jsExceptionHere(JSET_ERROR, "Font bitmap must be a String");
return;
}
if (firstChar<0 || firstChar>255) {
jsExceptionHere(JSET_ERROR, "First character out of range");
return;
}
if (!jsvIsString(width) && !jsvIsInt(width)) {
jsExceptionHere(JSET_ERROR, "Font width must be a String or an integer");
return;
}
if (height<=0 || height>255) {
jsExceptionHere(JSET_ERROR, "Invalid height");
return;
}
jsvObjectSetChild(parent, JSGRAPHICS_CUSTOMFONT_BMP, bitmap);
jsvObjectSetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, width);
jsvObjectSetChildAndUnLock(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT, jsvNewFromInteger(height));
jsvObjectSetChildAndUnLock(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, jsvNewFromInteger(firstChar));
gfx.data.fontSize = JSGRAPHICS_FONTSIZE_CUSTOM;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setFontAlign",
"generate" : "jswrap_graphics_setFontAlign",
"params" : [
["x","int32","X alignment. -1=left (default), 0=center, 1=right"],
["y","int32","Y alignment. -1=top (default), 0=center, 1=bottom"],
["rotation","int32","Rotation of the text. 0=normal, 1=90 degrees clockwise, 2=180, 3=270"]
]
}
Set the alignment for subsequent calls to `drawString`
*/
void jswrap_graphics_setFontAlign(JsVar *parent, int x, int y, int r) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
if (x<-1) x=-1;
if (x>1) x=1;
if (y<-1) y=-1;
if (y>1) y=1;
if (r<0) r=0;
if (r>3) r=3;
gfx.data.fontAlignX = x;
gfx.data.fontAlignY = y;
gfx.data.fontRotate = r;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "drawString",
"generate" : "jswrap_graphics_drawString",
"params" : [
["str","JsVar","The string"],
["x","int32","The X position of the leftmost pixel"],
["y","int32","The Y position of the topmost pixel"]
]
}
Draw a string of text in the current font
*/
void jswrap_graphics_drawString(JsVar *parent, JsVar *var, int x, int y) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
JsVar *customBitmap = 0, *customWidth = 0;
int customHeight = 0, customFirstChar = 0;
if (gfx.data.fontSize>0) {
customHeight = gfx.data.fontSize;
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) {
customHeight = 6;
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) {
customBitmap = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_BMP, 0);
customWidth = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, 0);
customHeight = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_HEIGHT, 0));
customFirstChar = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, 0));
}
// Handle text rotation
JsGraphicsFlags oldFlags = gfx.data.flags;
if (gfx.data.fontRotate==1) {
gfx.data.flags ^= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X;
int t = gfx.data.width - (x+1);
x = y;
y = t;
} else if (gfx.data.fontRotate==2) {
gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y;
x = gfx.data.width - (x+1);
y = gfx.data.height - (y+1);
} else if (gfx.data.fontRotate==3) {
gfx.data.flags ^= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_Y;
int t = gfx.data.height - (y+1);
y = x;
x = t;
}
// Handle font alignment
if (gfx.data.fontAlignX>=0)
x -= jswrap_graphics_stringWidth(parent, var) * (gfx.data.fontAlignX+1)/2;
if (gfx.data.fontAlignY>=0)
y -= customHeight * (gfx.data.fontAlignX+1)/2;
int maxX = (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) ? gfx.data.height : gfx.data.width;
int maxY = (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY) ? gfx.data.width : gfx.data.height;
int startx = x;
JsVar *str = jsvAsString(var, false);
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (ch=='\n') {
x = startx;
y += customHeight;
jsvStringIteratorNext(&it);
continue;
}
if (gfx.data.fontSize>0) {
#ifndef SAVE_ON_FLASH
int w = (int)graphicsVectorCharWidth(&gfx, gfx.data.fontSize, ch);
if (x>-w && x<maxX && y>-gfx.data.fontSize && y<maxY)
graphicsFillVectorChar(&gfx, (short)x, (short)y, gfx.data.fontSize, ch);
x+=w;
#endif
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) {
if (x>-4 && x<maxX && y>-6 && y<maxY)
graphicsDrawChar4x6(&gfx, (short)x, (short)y, ch);
x+=4;
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) {
// get char width and offset in string
int width = 0, bmpOffset = 0;
if (jsvIsString(customWidth)) {
if (ch>=customFirstChar) {
JsvStringIterator wit;
jsvStringIteratorNew(&wit, customWidth, 0);
while (jsvStringIteratorHasChar(&wit) && (int)jsvStringIteratorGetIndex(&wit)<(ch-customFirstChar)) {
bmpOffset += (unsigned char)jsvStringIteratorGetChar(&wit);
jsvStringIteratorNext(&wit);
}
width = (unsigned char)jsvStringIteratorGetChar(&wit);
jsvStringIteratorFree(&wit);
}
} else {
width = (int)jsvGetInteger(customWidth);
bmpOffset = width*(ch-customFirstChar);
}
if (ch>=customFirstChar && (x>-width) && (x<maxX) && (y>-customHeight) && y<maxY) {
bmpOffset *= customHeight;
// now render character
JsvStringIterator cit;
jsvStringIteratorNew(&cit, customBitmap, (size_t)bmpOffset>>3);
bmpOffset &= 7;
int cx,cy;
for (cx=0;cx<width;cx++) {
for (cy=0;cy<customHeight;cy++) {
if ((jsvStringIteratorGetChar(&cit)<<bmpOffset)&128)
graphicsSetPixel(&gfx, (short)(cx+x), (short)(cy+y), gfx.data.fgColor);
bmpOffset++;
if (bmpOffset==8) {
bmpOffset=0;
jsvStringIteratorNext(&cit);
}
}
}
jsvStringIteratorFree(&cit);
}
x += width;
}
if (jspIsInterrupted()) break;
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
jsvUnLock3(str, customBitmap, customWidth);
gfx.data.flags = oldFlags; // restore flags because of text rotation
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "stringWidth",
"generate" : "jswrap_graphics_stringWidth",
"params" : [
["str","JsVar","The string"]
],
"return" : ["int","The length of the string in pixels"]
}
Return the size in pixels of a string of text in the current font
*/
JsVarInt jswrap_graphics_stringWidth(JsVar *parent, JsVar *var) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0;
JsVar *customWidth = 0;
int customFirstChar = 0;
if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) {
customWidth = jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_WIDTH, 0);
customFirstChar = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(parent, JSGRAPHICS_CUSTOMFONT_FIRSTCHAR, 0));
}
JsVar *str = jsvAsString(var, false);
JsvStringIterator it;
jsvStringIteratorNew(&it, str, 0);
int width = 0;
while (jsvStringIteratorHasChar(&it)) {
char ch = jsvStringIteratorGetChar(&it);
if (gfx.data.fontSize>0) {
#ifndef SAVE_ON_FLASH
width += (int)graphicsVectorCharWidth(&gfx, gfx.data.fontSize, ch);
#endif
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_4X6) {
width += 4;
} else if (gfx.data.fontSize == JSGRAPHICS_FONTSIZE_CUSTOM) {
if (jsvIsString(customWidth)) {
if (ch>=customFirstChar)
width += (unsigned char)jsvGetCharInString(customWidth, (size_t)(ch-customFirstChar));
} else
width += (int)jsvGetInteger(customWidth);
}
jsvStringIteratorNext(&it);
}
jsvStringIteratorFree(&it);
jsvUnLock2(str, customWidth);
return width;
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "drawLine",
"generate" : "jswrap_graphics_drawLine",
"params" : [
["x1","int32","The left"],
["y1","int32","The top"],
["x2","int32","The right"],
["y2","int32","The bottom"]
]
}
Draw a line between x1,y1 and x2,y2 in the current foreground color
*/
void jswrap_graphics_drawLine(JsVar *parent, int x1, int y1, int x2, int y2) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsDrawLine(&gfx, (short)x1,(short)y1,(short)x2,(short)y2);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "lineTo",
"generate" : "jswrap_graphics_lineTo",
"params" : [
["x","int32","X value"],
["y","int32","Y value"]
]
}
Draw a line from the last position of lineTo or moveTo to this position
*/
void jswrap_graphics_lineTo(JsVar *parent, int x, int y) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsDrawLine(&gfx, gfx.data.cursorX, gfx.data.cursorY, (short)x, (short)y);
gfx.data.cursorX = (short)x;
gfx.data.cursorY = (short)y;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "moveTo",
"generate" : "jswrap_graphics_moveTo",
"params" : [
["x","int32","X value"],
["y","int32","Y value"]
]
}
Move the cursor to a position - see lineTo
*/
void jswrap_graphics_moveTo(JsVar *parent, int x, int y) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
gfx.data.cursorX = (short)x;
gfx.data.cursorY = (short)y;
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "fillPoly",
"generate" : "jswrap_graphics_fillPoly",
"params" : [
["poly","JsVar","An array of vertices, of the form ```[x1,y1,x2,y2,x3,y3,etc]```"]
]
}
Draw a filled polygon in the current foreground color
*/
void jswrap_graphics_fillPoly(JsVar *parent, JsVar *poly) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
if (!jsvIsIterable(poly)) return;
const int maxVerts = 128;
short verts[maxVerts];
int idx = 0;
JsvIterator it;
jsvIteratorNew(&it, poly, JSIF_EVERY_ARRAY_ELEMENT);
while (jsvIteratorHasElement(&it) && idx<maxVerts) {
verts[idx++] = (short)jsvIteratorGetIntegerValue(&it);
jsvIteratorNext(&it);
}
jsvIteratorFree(&it);
if (idx==maxVerts) {
jsWarn("Maximum number of points (%d) exceeded for fillPoly", maxVerts/2);
}
graphicsFillPoly(&gfx, idx/2, verts);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "setRotation",
"generate" : "jswrap_graphics_setRotation",
"params" : [
["rotation","int32","The clockwise rotation. 0 for no rotation, 1 for 90 degrees, 2 for 180, 3 for 270"],
["reflect","bool","Whether to reflect the image"]
]
}
Set the current rotation of the graphics device.
*/
void jswrap_graphics_setRotation(JsVar *parent, int rotation, bool reflect) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
// clear flags
gfx.data.flags &= (JsGraphicsFlags)~(JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y);
// set flags
switch (rotation) {
case 0:
break;
case 1:
gfx.data.flags |= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_X;
break;
case 2:
gfx.data.flags |= JSGRAPHICSFLAGS_INVERT_X | JSGRAPHICSFLAGS_INVERT_Y;
break;
case 3:
gfx.data.flags |= JSGRAPHICSFLAGS_SWAP_XY | JSGRAPHICSFLAGS_INVERT_Y;
break;
}
if (reflect) {
if (gfx.data.flags & JSGRAPHICSFLAGS_SWAP_XY)
gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_Y;
else
gfx.data.flags ^= JSGRAPHICSFLAGS_INVERT_X;
}
graphicsSetVar(&gfx);
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "drawImage",
"generate" : "jswrap_graphics_drawImage",
"params" : [
["image","JsVar","An object with the following fields `{ width : int, height : int, bpp : int, buffer : ArrayBuffer, transparent: optional int }`. bpp = bits per pixel, transparent (if defined) is the colour that will be treated as transparent"],
["x","int32","The X offset to draw the image"],
["y","int32","The Y offset to draw the image"]
]
}
Draw an image at the specified position. If the image is 1 bit, the graphics foreground/background colours will be used. Otherwise color data will be copied as-is. Bitmaps are rendered MSB-first
*/
void jswrap_graphics_drawImage(JsVar *parent, JsVar *image, int xPos, int yPos) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
if (!jsvIsObject(image)) {
jsExceptionHere(JSET_ERROR, "Expecting first argument to be an object");
return;
}
int imageWidth = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "width", 0));
int imageHeight = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "height", 0));
int imageBpp = (int)jsvGetIntegerAndUnLock(jsvObjectGetChild(image, "bpp", 0));
unsigned int imageBitMask = (unsigned int)((1L<<imageBpp)-1L);
JsVar *transpVar = jsvObjectGetChild(image, "transparent", 0);
bool imageIsTransparent = transpVar!=0;
unsigned int imageTransparentCol = (unsigned int)jsvGetInteger(transpVar);
jsvUnLock(transpVar);
JsVar *imageBuffer = jsvObjectGetChild(image, "buffer", 0);
if (!(jsvIsArrayBuffer(imageBuffer) && imageWidth>0 && imageHeight>0 && imageBpp>0 && imageBpp<=32)) {
jsExceptionHere(JSET_ERROR, "Expecting first argument to a valid Image");
jsvUnLock(imageBuffer);
return;
}
JsVar *imageBufferString = jsvGetArrayBufferBackingString(imageBuffer);
jsvUnLock(imageBuffer);
int x=0, y=0;
int bits=0;
unsigned int colData = 0;
JsvStringIterator it;
jsvStringIteratorNew(&it, imageBufferString, 0);
while ((bits>=imageBpp || jsvStringIteratorHasChar(&it)) && y<imageHeight) {
// Get the data we need...
while (bits < imageBpp) {
colData = (colData<<8) | ((unsigned char)jsvStringIteratorGetChar(&it));
jsvStringIteratorNext(&it);
bits += 8;
}
// extract just the bits we want
unsigned int col = (colData>>(bits-imageBpp))&imageBitMask;
bits -= imageBpp;
// Try and write pixel!
if (!imageIsTransparent || imageTransparentCol!=col) {
if (imageBpp==1)
col = col ? gfx.data.fgColor : gfx.data.bgColor;
graphicsSetPixel(&gfx, (short)(x+xPos), (short)(y+yPos), col);
}
// Go to next pixel
x++;
if (x>=imageWidth) {
x=0;
y++;
// we don't care about image height - we'll stop next time...
}
}
jsvStringIteratorFree(&it);
jsvUnLock(imageBufferString);
graphicsSetVar(&gfx); // gfx data changed because modified area
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "getModified",
"generate" : "jswrap_graphics_getModified",
"params" : [
["reset","bool","Whether to reset the modified area or not"]
],
"return" : ["JsVar","An object {x1,y1,x2,y2} containing the modified area, or undefined if not modified"]
}
Return the area of the Graphics canvas that has been modified, and optionally clear
the modified area to 0.
For instance if `g.setPixel(10,20)` was called, this would return `{x1:10, y1:20, x2:10, y2:20}`
*/
JsVar *jswrap_graphics_getModified(JsVar *parent, bool reset) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return 0;
JsVar *obj = 0;
if (gfx.data.modMinX <= gfx.data.modMaxX) { // do we have a rect?
obj = jsvNewObject();
if (obj) {
jsvObjectSetChildAndUnLock(obj, "x1", jsvNewFromInteger(gfx.data.modMinX));
jsvObjectSetChildAndUnLock(obj, "y1", jsvNewFromInteger(gfx.data.modMinY));
jsvObjectSetChildAndUnLock(obj, "x2", jsvNewFromInteger(gfx.data.modMaxX));
jsvObjectSetChildAndUnLock(obj, "y2", jsvNewFromInteger(gfx.data.modMaxY));
}
}
if (reset) {
gfx.data.modMaxX = -32768;
gfx.data.modMaxY = -32768;
gfx.data.modMinX = 32767;
gfx.data.modMinY = 32767;
graphicsSetVar(&gfx);
}
return obj;
}
/*JSON{
"type" : "method",
"class" : "Graphics",
"name" : "scroll",
"generate" : "jswrap_graphics_scroll",
"params" : [
["x","int32","X direction. >0 = to right"],
["y","int32","Y direction. >0 = down"]
]
}
Scroll the contents of this graphics in a certain direction. The remaining area
is filled with the background color.
Note: This uses repeated pixel reads and writes, so will not work on platforms that
don't support pixel reads.
*/
void jswrap_graphics_scroll(JsVar *parent, int xdir, int ydir) {
JsGraphics gfx; if (!graphicsGetFromVar(&gfx, parent)) return;
graphicsScroll(&gfx, xdir, ydir);
// update modified area
graphicsSetVar(&gfx);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_157_1 |
crossvul-cpp_data_bad_4214_0 | /*
* ndpi_main.c
*
* Copyright (C) 2011-20 - ntop.org
*
* This file is part of nDPI, an open source deep packet inspection
* library based on the OpenDPI and PACE technology by ipoque GmbH
*
* nDPI 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.
*
* nDPI 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 nDPI. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#define NDPI_CURRENT_PROTO NDPI_PROTOCOL_UNKNOWN
#include "ndpi_config.h"
#include "ndpi_api.h"
#include "ahocorasick.h"
#include "libcache.h"
#include <time.h>
#ifndef WIN32
#include <unistd.h>
#endif
#if defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__
#include <sys/endian.h>
#endif
#include "ndpi_content_match.c.inc"
#include "third_party/include/ndpi_patricia.h"
#include "third_party/include/ht_hash.h"
#include "third_party/include/ndpi_md5.h"
/* stun.c */
extern u_int32_t get_stun_lru_key(struct ndpi_flow_struct *flow, u_int8_t rev);
static int _ndpi_debug_callbacks = 0;
/* #define MATCH_DEBUG 1 */
/* ****************************************** */
static void *(*_ndpi_flow_malloc)(size_t size);
static void (*_ndpi_flow_free)(void *ptr);
static void *(*_ndpi_malloc)(size_t size);
static void (*_ndpi_free)(void *ptr);
/* ****************************************** */
/* Forward */
static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range,
ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root,
const char *_func, int _line);
static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root);
/* ****************************************** */
static inline uint8_t flow_is_proto(struct ndpi_flow_struct *flow, u_int16_t p) {
return((flow->detected_protocol_stack[0] == p) || (flow->detected_protocol_stack[1] == p));
}
/* ****************************************** */
void *ndpi_malloc(size_t size) {
return(_ndpi_malloc ? _ndpi_malloc(size) : malloc(size));
}
void *ndpi_flow_malloc(size_t size) {
return(_ndpi_flow_malloc ? _ndpi_flow_malloc(size) : ndpi_malloc(size));
}
/* ****************************************** */
void *ndpi_calloc(unsigned long count, size_t size) {
size_t len = count * size;
void *p = ndpi_malloc(len);
if(p)
memset(p, 0, len);
return(p);
}
/* ****************************************** */
void ndpi_free(void *ptr) {
if(_ndpi_free)
_ndpi_free(ptr);
else
free(ptr);
}
/* ****************************************** */
void ndpi_flow_free(void *ptr) {
if(_ndpi_flow_free)
_ndpi_flow_free(ptr);
else
ndpi_free_flow((struct ndpi_flow_struct *) ptr);
}
/* ****************************************** */
void *ndpi_realloc(void *ptr, size_t old_size, size_t new_size) {
void *ret = ndpi_malloc(new_size);
if(!ret)
return(ret);
else {
memcpy(ret, ptr, old_size);
ndpi_free(ptr);
return(ret);
}
}
/* ****************************************** */
char *ndpi_strdup(const char *s) {
int len = strlen(s);
char *m = ndpi_malloc(len + 1);
if(m) {
memcpy(m, s, len);
m[len] = '\0';
}
return(m);
}
/* *********************************************************************************** */
/* Opaque structure defined here */
struct ndpi_ptree
{
patricia_tree_t *v4;
patricia_tree_t *v6;
};
/* *********************************************************************************** */
u_int32_t ndpi_detection_get_sizeof_ndpi_flow_struct(void) {
return(sizeof(struct ndpi_flow_struct));
}
/* *********************************************************************************** */
u_int32_t ndpi_detection_get_sizeof_ndpi_id_struct(void) {
return(sizeof(struct ndpi_id_struct));
}
/* *********************************************************************************** */
u_int32_t ndpi_detection_get_sizeof_ndpi_flow_tcp_struct(void) {
return(sizeof(struct ndpi_flow_tcp_struct));
}
/* *********************************************************************************** */
u_int32_t ndpi_detection_get_sizeof_ndpi_flow_udp_struct(void) {
return(sizeof(struct ndpi_flow_udp_struct));
}
/* *********************************************************************************** */
char *ndpi_get_proto_by_id(struct ndpi_detection_module_struct *ndpi_str, u_int id) {
return((id >= ndpi_str->ndpi_num_supported_protocols) ? NULL : ndpi_str->proto_defaults[id].protoName);
}
/* *********************************************************************************** */
u_int16_t ndpi_get_proto_by_name(struct ndpi_detection_module_struct *ndpi_str, const char *name) {
u_int16_t i, num = ndpi_get_num_supported_protocols(ndpi_str);
for (i = 0; i < num; i++)
if(strcasecmp(ndpi_get_proto_by_id(ndpi_str, i), name) == 0)
return(i);
return(NDPI_PROTOCOL_UNKNOWN);
}
/* ************************************************************************************* */
#ifdef CODE_UNUSED
ndpi_port_range *ndpi_build_default_ports_range(ndpi_port_range *ports, u_int16_t portA_low, u_int16_t portA_high,
u_int16_t portB_low, u_int16_t portB_high, u_int16_t portC_low,
u_int16_t portC_high, u_int16_t portD_low, u_int16_t portD_high,
u_int16_t portE_low, u_int16_t portE_high) {
int i = 0;
ports[i].port_low = portA_low, ports[i].port_high = portA_high;
i++;
ports[i].port_low = portB_low, ports[i].port_high = portB_high;
i++;
ports[i].port_low = portC_low, ports[i].port_high = portC_high;
i++;
ports[i].port_low = portD_low, ports[i].port_high = portD_high;
i++;
ports[i].port_low = portE_low, ports[i].port_high = portE_high;
return(ports);
}
#endif
/* *********************************************************************************** */
ndpi_port_range *ndpi_build_default_ports(ndpi_port_range *ports, u_int16_t portA, u_int16_t portB, u_int16_t portC,
u_int16_t portD, u_int16_t portE) {
int i = 0;
ports[i].port_low = portA, ports[i].port_high = portA;
i++;
ports[i].port_low = portB, ports[i].port_high = portB;
i++;
ports[i].port_low = portC, ports[i].port_high = portC;
i++;
ports[i].port_low = portD, ports[i].port_high = portD;
i++;
ports[i].port_low = portE, ports[i].port_high = portE;
return(ports);
}
/* ********************************************************************************** */
void ndpi_set_proto_breed(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId, ndpi_protocol_breed_t breed) {
if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)
return;
else
ndpi_str->proto_defaults[protoId].protoBreed = breed;
}
/* ********************************************************************************** */
void ndpi_set_proto_category(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId,
ndpi_protocol_category_t protoCategory) {
if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)
return;
else
ndpi_str->proto_defaults[protoId].protoCategory = protoCategory;
}
/* ********************************************************************************** */
/*
There are some (master) protocols that are informative, meaning that it shows
what is the subprotocol about, but also that the subprotocol isn't a real protocol.
Example:
- DNS is informative as if we see a DNS request for www.facebook.com, the
returned protocol is DNS.Facebook, but Facebook isn't a real subprotocol but
rather it indicates a query for Facebook and not Facebook traffic.
- HTTP/SSL are NOT informative as SSL.Facebook (likely) means that this is
SSL (HTTPS) traffic containg Facebook traffic.
*/
u_int8_t ndpi_is_subprotocol_informative(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protoId) {
if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)
return(0);
switch (protoId) {
/* All dissectors that have calls to ndpi_match_host_subprotocol() */
case NDPI_PROTOCOL_DNS:
return(1);
break;
default:
return(0);
}
}
/* ********************************************************************************** */
void ndpi_exclude_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t protocol_id, const char *_file, const char *_func, int _line) {
if(protocol_id < NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) {
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
if(ndpi_str && ndpi_str->ndpi_log_level >= NDPI_LOG_DEBUG && ndpi_str->ndpi_debug_printf != NULL) {
(*(ndpi_str->ndpi_debug_printf))(protocol_id, ndpi_str, NDPI_LOG_DEBUG, _file, _func, _line, "exclude %s\n",
ndpi_get_proto_name(ndpi_str, protocol_id));
}
#endif
NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, protocol_id);
}
}
/* ********************************************************************************** */
void ndpi_set_proto_defaults(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_breed_t breed,
u_int16_t protoId, u_int8_t can_have_a_subprotocol, u_int16_t tcp_master_protoId[2],
u_int16_t udp_master_protoId[2], char *protoName, ndpi_protocol_category_t protoCategory,
ndpi_port_range *tcpDefPorts, ndpi_port_range *udpDefPorts) {
char *name;
int j;
if(protoId >= NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS) {
#ifdef DEBUG
NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: INTERNAL ERROR\n", protoName, protoId);
#endif
return;
}
if(ndpi_str->proto_defaults[protoId].protoName != NULL) {
#ifdef DEBUG
NDPI_LOG_ERR(ndpi_str, "[NDPI] %s/protoId=%d: already initialized. Ignoring it\n", protoName, protoId);
#endif
return;
}
name = ndpi_strdup(protoName);
if(ndpi_str->proto_defaults[protoId].protoName)
ndpi_free(ndpi_str->proto_defaults[protoId].protoName);
ndpi_str->proto_defaults[protoId].protoName = name, ndpi_str->proto_defaults[protoId].protoCategory = protoCategory,
ndpi_str->proto_defaults[protoId].protoId = protoId, ndpi_str->proto_defaults[protoId].protoBreed = breed;
ndpi_str->proto_defaults[protoId].can_have_a_subprotocol = can_have_a_subprotocol;
memcpy(&ndpi_str->proto_defaults[protoId].master_tcp_protoId, tcp_master_protoId, 2 * sizeof(u_int16_t));
memcpy(&ndpi_str->proto_defaults[protoId].master_udp_protoId, udp_master_protoId, 2 * sizeof(u_int16_t));
for (j = 0; j < MAX_DEFAULT_PORTS; j++) {
if(udpDefPorts[j].port_low != 0)
addDefaultPort(ndpi_str, &udpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->udpRoot,
__FUNCTION__, __LINE__);
if(tcpDefPorts[j].port_low != 0)
addDefaultPort(ndpi_str, &tcpDefPorts[j], &ndpi_str->proto_defaults[protoId], 0, &ndpi_str->tcpRoot,
__FUNCTION__, __LINE__);
/* No port range, just the lower port */
ndpi_str->proto_defaults[protoId].tcp_default_ports[j] = tcpDefPorts[j].port_low;
ndpi_str->proto_defaults[protoId].udp_default_ports[j] = udpDefPorts[j].port_low;
}
}
/* ******************************************************************** */
static int ndpi_default_ports_tree_node_t_cmp(const void *a, const void *b) {
ndpi_default_ports_tree_node_t *fa = (ndpi_default_ports_tree_node_t *) a;
ndpi_default_ports_tree_node_t *fb = (ndpi_default_ports_tree_node_t *) b;
//printf("[NDPI] %s(%d, %d)\n", __FUNCTION__, fa->default_port, fb->default_port);
return((fa->default_port == fb->default_port) ? 0 : ((fa->default_port < fb->default_port) ? -1 : 1));
}
/* ******************************************************************** */
void ndpi_default_ports_tree_node_t_walker(const void *node, const ndpi_VISIT which, const int depth) {
ndpi_default_ports_tree_node_t *f = *(ndpi_default_ports_tree_node_t **) node;
printf("<%d>Walk on node %s (%u)\n", depth,
which == ndpi_preorder ?
"ndpi_preorder" :
which == ndpi_postorder ?
"ndpi_postorder" :
which == ndpi_endorder ? "ndpi_endorder" : which == ndpi_leaf ? "ndpi_leaf" : "unknown",
f->default_port);
}
/* ******************************************************************** */
static void addDefaultPort(struct ndpi_detection_module_struct *ndpi_str, ndpi_port_range *range,
ndpi_proto_defaults_t *def, u_int8_t customUserProto, ndpi_default_ports_tree_node_t **root,
const char *_func, int _line) {
u_int16_t port;
for (port = range->port_low; port <= range->port_high; port++) {
ndpi_default_ports_tree_node_t *node =
(ndpi_default_ports_tree_node_t *) ndpi_malloc(sizeof(ndpi_default_ports_tree_node_t));
ndpi_default_ports_tree_node_t *ret;
if(!node) {
NDPI_LOG_ERR(ndpi_str, "%s:%d not enough memory\n", _func, _line);
break;
}
node->proto = def, node->default_port = port, node->customUserProto = customUserProto;
ret = (ndpi_default_ports_tree_node_t *) ndpi_tsearch(node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */
if(ret != node) {
NDPI_LOG_DBG(ndpi_str, "[NDPI] %s:%d found duplicate for port %u: overwriting it with new value\n", _func,
_line, port);
ret->proto = def;
ndpi_free(node);
}
}
}
/* ****************************************************** */
/*
NOTE
This function must be called with a semaphore set, this in order to avoid
changing the datastructures while using them
*/
static int removeDefaultPort(ndpi_port_range *range, ndpi_proto_defaults_t *def, ndpi_default_ports_tree_node_t **root) {
ndpi_default_ports_tree_node_t node;
u_int16_t port;
for (port = range->port_low; port <= range->port_high; port++) {
ndpi_default_ports_tree_node_t *ret;
node.proto = def, node.default_port = port;
ret = (ndpi_default_ports_tree_node_t *) ndpi_tdelete(
&node, (void *) root, ndpi_default_ports_tree_node_t_cmp); /* Add it to the tree */
if(ret != NULL) {
ndpi_free((ndpi_default_ports_tree_node_t *) ret);
return(0);
}
}
return(-1);
}
/* ****************************************************** */
static int ndpi_string_to_automa(struct ndpi_detection_module_struct *ndpi_str, ndpi_automa *automa, char *value,
u_int16_t protocol_id, ndpi_protocol_category_t category, ndpi_protocol_breed_t breed,
u_int8_t free_str_on_duplicate) {
AC_PATTERN_t ac_pattern;
AC_ERROR_t rc;
if((value == NULL) || (protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS))) {
NDPI_LOG_ERR(ndpi_str, "[NDPI] protoId=%d: INTERNAL ERROR\n", protocol_id);
return(-1);
}
if(automa->ac_automa == NULL)
return(-2);
ac_pattern.astring = value, ac_pattern.rep.number = protocol_id,
ac_pattern.rep.category = (u_int16_t) category, ac_pattern.rep.breed = (u_int16_t) breed;
#ifdef MATCH_DEBUG
printf("Adding to automa [%s][protocol_id: %u][category: %u][breed: %u]\n", value, protocol_id, category, breed);
#endif
if(value == NULL)
ac_pattern.length = 0;
else
ac_pattern.length = strlen(ac_pattern.astring);
rc = ac_automata_add(((AC_AUTOMATA_t *) automa->ac_automa), &ac_pattern);
if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS)
return(-2);
if(rc == ACERR_DUPLICATE_PATTERN && free_str_on_duplicate)
ndpi_free(value);
return(0);
}
/* ****************************************************** */
static int ndpi_add_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *_value, int protocol_id,
ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) {
int rv;
char *value = ndpi_strdup(_value);
if(!value)
return(-1);
#ifdef DEBUG
NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding [%s][%d]\n", value, protocol_id);
#endif
rv = ndpi_string_to_automa(ndpi_str, &ndpi_str->host_automa, value, protocol_id, category, breed, 1);
if(rv != 0)
ndpi_free(value);
return(rv);
}
/* ****************************************************** */
#ifdef CODE_UNUSED
int ndpi_add_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id,
ndpi_protocol_category_t category, ndpi_protocol_breed_t breed) {
return(ndpi_string_to_automa(ndpi_str, &ndpi_str->content_automa, value, protocol_id, category, breed, 0));
}
#endif
/* ****************************************************** */
/*
NOTE
This function must be called with a semaphore set, this in order to avoid
changing the datastructures while using them
*/
static int ndpi_remove_host_url_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *value, int protocol_id) {
NDPI_LOG_ERR(ndpi_str, "[NDPI] Missing implementation for proto %s/%d\n", value, protocol_id);
return(-1);
}
/* ******************************************************************** */
void ndpi_init_protocol_match(struct ndpi_detection_module_struct *ndpi_str, ndpi_protocol_match *match) {
u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO};
ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS];
if(ndpi_str->proto_defaults[match->protocol_id].protoName == NULL) {
ndpi_str->proto_defaults[match->protocol_id].protoName = ndpi_strdup(match->proto_name);
ndpi_str->proto_defaults[match->protocol_id].protoId = match->protocol_id;
ndpi_str->proto_defaults[match->protocol_id].protoCategory = match->protocol_category;
ndpi_str->proto_defaults[match->protocol_id].protoBreed = match->protocol_breed;
ndpi_set_proto_defaults(ndpi_str, ndpi_str->proto_defaults[match->protocol_id].protoBreed,
ndpi_str->proto_defaults[match->protocol_id].protoId, 0 /* can_have_a_subprotocol */,
no_master, no_master, ndpi_str->proto_defaults[match->protocol_id].protoName,
ndpi_str->proto_defaults[match->protocol_id].protoCategory,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
}
ndpi_add_host_url_subprotocol(ndpi_str, match->string_to_match, match->protocol_id, match->protocol_category,
match->protocol_breed);
}
/* ******************************************************************** */
/* Self check function to be called onli for testing purposes */
void ndpi_self_check_host_match() {
u_int32_t i, j;
for (i = 0; host_match[i].string_to_match != NULL; i++) {
for (j = 0; host_match[j].string_to_match != NULL; j++) {
if((i != j) && (strcmp(host_match[i].string_to_match, host_match[j].string_to_match) == 0)) {
printf("[INTERNAL ERROR]: Duplicate string detected '%s' [id: %u, id %u]\n",
host_match[i].string_to_match, i, j);
printf("\nPlease fix host_match[] in ndpi_content_match.c.inc\n");
exit(0);
}
}
}
}
/* ******************************************************************** */
static void init_string_based_protocols(struct ndpi_detection_module_struct *ndpi_str) {
int i;
for (i = 0; host_match[i].string_to_match != NULL; i++)
ndpi_init_protocol_match(ndpi_str, &host_match[i]);
ndpi_enable_loaded_categories(ndpi_str);
#ifdef MATCH_DEBUG
// ac_automata_display(ndpi_str->host_automa.ac_automa, 'n');
#endif
for (i = 0; ndpi_en_bigrams[i] != NULL; i++)
ndpi_string_to_automa(ndpi_str, &ndpi_str->bigrams_automa, (char *) ndpi_en_bigrams[i], 1, 1, 1, 0);
for (i = 0; ndpi_en_impossible_bigrams[i] != NULL; i++)
ndpi_string_to_automa(ndpi_str, &ndpi_str->impossible_bigrams_automa, (char *) ndpi_en_impossible_bigrams[i], 1,
1, 1, 0);
}
/* ******************************************************************** */
int ndpi_set_detection_preferences(struct ndpi_detection_module_struct *ndpi_str, ndpi_detection_preference pref,
int value) {
switch (pref) {
case ndpi_pref_direction_detect_disable:
ndpi_str->direction_detect_disable = (u_int8_t) value;
break;
default:
return(-1);
}
return(0);
}
/* ******************************************************************** */
static void ndpi_validate_protocol_initialization(struct ndpi_detection_module_struct *ndpi_str) {
int i;
for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) {
if(ndpi_str->proto_defaults[i].protoName == NULL) {
NDPI_LOG_ERR(ndpi_str,
"[NDPI] INTERNAL ERROR missing protoName initialization for [protoId=%d]: recovering\n", i);
} else {
if((i != NDPI_PROTOCOL_UNKNOWN) &&
(ndpi_str->proto_defaults[i].protoCategory == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) {
NDPI_LOG_ERR(ndpi_str,
"[NDPI] INTERNAL ERROR missing category [protoId=%d/%s] initialization: recovering\n", i,
ndpi_str->proto_defaults[i].protoName ? ndpi_str->proto_defaults[i].protoName : "???");
}
}
}
}
/* ******************************************************************** */
/* This function is used to map protocol name and default ports and it MUST
be updated whenever a new protocol is added to NDPI.
Do NOT add web services (NDPI_SERVICE_xxx) here.
*/
static void ndpi_init_protocol_defaults(struct ndpi_detection_module_struct *ndpi_str) {
ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS];
u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO}, custom_master[2];
/* Reset all settings */
memset(ndpi_str->proto_defaults, 0, sizeof(ndpi_str->proto_defaults));
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNRATED, NDPI_PROTOCOL_UNKNOWN, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Unknown", NDPI_PROTOCOL_CATEGORY_UNSPECIFIED,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_FTP_CONTROL, 0 /* can_have_a_subprotocol */,
no_master, no_master, "FTP_CONTROL", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 21, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_FTP_DATA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "FTP_DATA", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 20, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_POP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "POP3", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 110, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_POPS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "POPS", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 995, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MAIL_SMTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SMTP", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 25, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_SMTPS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SMTPS", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 465, 587, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MAIL_IMAP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IMAP", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 143, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MAIL_IMAPS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IMAPS", NDPI_PROTOCOL_CATEGORY_MAIL,
ndpi_build_default_ports(ports_a, 993, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNS, 1 /* can_have_a_subprotocol */,
no_master, no_master, "DNS", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 53, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 53, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IPP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IPP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IMO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IMO", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP, 1 /* can_have_a_subprotocol */,
no_master, no_master, "HTTP", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 80, 0 /* ntop */, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MDNS, 1 /* can_have_a_subprotocol */,
no_master, no_master, "MDNS", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5353, 5354, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "NTP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 123, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETBIOS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "NetBIOS", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 139, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 137, 138, 139, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NFS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "NFS", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER,
ndpi_build_default_ports(ports_a, 2049, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 2049, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSDP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SSDP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BGP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "BGP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 179, 2605, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SNMP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SNMP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 161, 162, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_XDMCP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "XDMCP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 177, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 177, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_DANGEROUS, NDPI_PROTOCOL_SMBV1, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SMBv1", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SYSLOG, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Syslog", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 514, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 514, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DHCP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 67, 68, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_POSTGRES, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PostgreSQL", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 5432, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MYSQL, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MySQL", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 3306, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECT_DOWNLOAD_LINK,
0 /* can_have_a_subprotocol */, no_master, no_master, "Direct_Download_Link",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_APPLEJUICE,
0 /* can_have_a_subprotocol */, no_master, no_master, "AppleJuice",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_DIRECTCONNECT,
0 /* can_have_a_subprotocol */, no_master, no_master, "DirectConnect",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NATS,
0 /* can_have_a_subprotocol */, no_master, no_master, "Nats",
NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_NTOP, 0 /* can_have_a_subprotocol */, no_master,
no_master, "ntop", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VMWARE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "VMware", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 903, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 902, 903, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FBZERO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "FacebookZero", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK,
ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_KONTIKI,
0 /* can_have_a_subprotocol */, no_master, no_master, "Kontiki",
NDPI_PROTOCOL_CATEGORY_MEDIA, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_OPENFT,
0 /* can_have_a_subprotocol */, no_master, no_master, "OpenFT",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_FASTTRACK,
0 /* can_have_a_subprotocol */, no_master, no_master, "FastTrack",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_GNUTELLA,
0 /* can_have_a_subprotocol */, no_master, no_master, "Gnutella",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_EDONKEY, 0 /* can_have_a_subprotocol */,
no_master, no_master, "eDonkey", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_BITTORRENT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "BitTorrent", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 51413, 53646, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 6771, 51413, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Skype", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKYPE_CALL,
0 /* can_have_a_subprotocol */, no_master, no_master, "SkypeCall",
NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TIKTOK, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TikTok", NDPI_PROTOCOL_CATEGORY_SOCIAL_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEREDO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Teredo", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 3544, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(
ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WECHAT, 0 /* can_have_a_subprotocol */, no_master, /* wechat.com */
no_master, "WeChat", NDPI_PROTOCOL_CATEGORY_CHAT, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEMCACHED, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Memcached", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 11211, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 11211, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMBV23, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SMBv23", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 445, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_MINING, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Mining", CUSTOM_CATEGORY_MINING,
ndpi_build_default_ports(ports_a, 8333, 30303, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NEST_LOG_SINK,
0 /* can_have_a_subprotocol */, no_master, no_master, "NestLogSink",
NDPI_PROTOCOL_CATEGORY_CLOUD,
ndpi_build_default_ports(ports_a, 11095, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MODBUS, 1 /* no subprotocol */, no_master,
no_master, "Modbus", NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */
ndpi_build_default_ports(ports_a, 502, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_CALL,
0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppCall",
NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DATASAVER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DataSaver", NDPI_PROTOCOL_CATEGORY_WEB /* dummy */,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SIGNAL, 0 /* can_have_a_subprotocol */,
no_master, /* https://signal.org */
no_master, "Signal", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOH_DOT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DoH_DoT", NDPI_PROTOCOL_CATEGORY_NETWORK /* dummy */,
ndpi_build_default_ports(ports_a, 853, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FREE_205, 0 /* can_have_a_subprotocol */,
no_master, no_master, "FREE_205", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WIREGUARD, 0 /* can_have_a_subprotocol */,
no_master, no_master, "WireGuard", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 51820, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_XBOX, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Xbox", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 3074, 3076, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 3074, 3076, 500, 3544, 4500) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PLAYSTATION, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Playstation", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 1935, 3478, 3479, 3480, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 3478, 3479, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQ, 0 /* can_have_a_subprotocol */, no_master,
no_master, "QQ", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_RTSP, 0 /* can_have_a_subprotocol */, no_master,
no_master, "RTSP", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 554, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 554, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ICECAST, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IceCast", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPLIVE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PPLive", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PPSTREAM, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PPStream", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ZATTOO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Zattoo", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SHOUTCAST, 0 /* can_have_a_subprotocol */,
no_master, no_master, "ShoutCast", NDPI_PROTOCOL_CATEGORY_MUSIC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOPCAST, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Sopcast", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVANTS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Tvants", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_TVUPLAYER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TVUplayer", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_DOWNLOAD,
1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Download",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_QQLIVE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "QQLive", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_THUNDER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Thunder", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_SOULSEEK, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Soulseek", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PS_VUE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PS_VUE", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_IRC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IRC", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 194, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 194, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AYIYA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Ayiya", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5072, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UNENCRYPTED_JABBER,
0 /* can_have_a_subprotocol */, no_master, no_master, "Unencrypted_Jabber",
NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OSCAR, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Oscar", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_BATTLEFIELD, 0 /* can_have_a_subprotocol */,
no_master, no_master, "BattleField", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_VRRP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "VRRP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STEAM, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Steam", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HALFLIFE2, 0 /* can_have_a_subprotocol */,
no_master, no_master, "HalfLife2", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLDOFWARCRAFT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "WorldOfWarcraft", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_HOTSPOT_SHIELD,
0 /* can_have_a_subprotocol */, no_master, no_master, "HotspotShield",
NDPI_PROTOCOL_CATEGORY_VPN, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_UNSAFE, NDPI_PROTOCOL_TELNET, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Telnet", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 23, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
custom_master[0] = NDPI_PROTOCOL_SIP, custom_master[1] = NDPI_PROTOCOL_H323;
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_STUN, 0 /* can_have_a_subprotocol */,
no_master, custom_master, "STUN", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 3478, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_IP_IPSEC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IPsec", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 500, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 500, 4500, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_GRE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "GRE", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "ICMP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IGMP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IGMP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_EGP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "EGP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_SCTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SCTP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_OSPF, 0 /* can_have_a_subprotocol */,
no_master, no_master, "OSPF", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 2604, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_IP_IN_IP,
0 /* can_have_a_subprotocol */, no_master, no_master, "IP_in_IP",
NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RTP", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RDP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RDP", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 3389, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 3389, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VNC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "VNC", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 5900, 5901, 5800, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PCANYWHERE,
0 /* can_have_a_subprotocol */, no_master, no_master, "PcAnywhere",
NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZOOM, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Zoom", NDPI_PROTOCOL_CATEGORY_VIDEO,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP_FILES,
0 /* can_have_a_subprotocol */, no_master, no_master, "WhatsAppFiles",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHATSAPP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "WhatsApp", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_TLS, 1 /* can_have_a_subprotocol */, no_master,
no_master, "TLS", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 443, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SSH, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SSH", NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 22, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_USENET, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Usenet", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MGCP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MGCP", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IAX, 0 /* can_have_a_subprotocol */,
no_master, no_master, "IAX", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 4569, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 4569, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AFP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "AFP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER,
ndpi_build_default_ports(ports_a, 548, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 548, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_HULU, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Hulu", NDPI_PROTOCOL_CATEGORY_STREAMING,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CHECKMK, 0 /* can_have_a_subprotocol */,
no_master, no_master, "CHECKMK", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER,
ndpi_build_default_ports(ports_a, 6556, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_STEALTHNET,
0 /* can_have_a_subprotocol */, no_master, no_master, "Stealthnet",
NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_AIMINI, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Aimini", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SIP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SIP", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 5060, 5061, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5060, 5061, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TRUPHONE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TruPhone", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IP_ICMPV6, 0 /* can_have_a_subprotocol */,
no_master, no_master, "ICMPV6", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DHCPV6, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DHCPV6", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_ARMAGETRON, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Armagetron", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CROSSFIRE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Crossfire", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_DOFUS, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Dofus", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FIESTA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Fiesta", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_FLORENSIA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Florensia", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_GUILDWARS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Guildwars", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_ACTIVESYNC,
1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_ActiveSync",
NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KERBEROS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Kerberos", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 88, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 88, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LDAP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "LDAP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 389, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 389, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MAPLESTORY, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MapleStory", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MSSQL_TDS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MsSQL-TDS", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 1433, 1434, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_PPTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "PPTP", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WARCRAFT3, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Warcraft3", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_WORLD_OF_KUNG_FU, 0 /* can_have_a_subprotocol */,
no_master, no_master, "WorldOfKungFu", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DCERPC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DCE_RPC", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 135, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NETFLOW, 0 /* can_have_a_subprotocol */,
no_master, no_master, "NetFlow", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 2055, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SFLOW, 0 /* can_have_a_subprotocol */,
no_master, no_master, "sFlow", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 6343, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_CONNECT,
1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Connect",
NDPI_PROTOCOL_CATEGORY_WEB, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HTTP_PROXY,
1 /* can_have_a_subprotocol */, no_master, no_master, "HTTP_Proxy",
NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 8080, 3128, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CITRIX, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Citrix", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 1494, 2598, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBEX, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Webex", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RADIUS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Radius", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 1812, 1813, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 1812, 1813, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMVIEWER,
0 /* can_have_a_subprotocol */, no_master, no_master, "TeamViewer",
NDPI_PROTOCOL_CATEGORY_REMOTE_ACCESS,
ndpi_build_default_ports(ports_a, 5938, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5938, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LOTUS_NOTES,
0 /* can_have_a_subprotocol */, no_master, no_master, "LotusNotes",
NDPI_PROTOCOL_CATEGORY_COLLABORATIVE,
ndpi_build_default_ports(ports_a, 1352, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(
ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SAP, 0 /* can_have_a_subprotocol */, no_master, no_master,
"SAP", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 3201, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_GTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "GTP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 2152, 2123, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UPNP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "UPnP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 1780, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 1900, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TELEGRAM, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Telegram", NDPI_PROTOCOL_CATEGORY_CHAT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_QUIC, 1 /* can_have_a_subprotocol */,
no_master, no_master, "QUIC", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 443, 80, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DIAMETER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Diameter", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 3868, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_APPLE_PUSH,
0 /* can_have_a_subprotocol */, no_master, no_master, "ApplePush",
NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DROPBOX, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Dropbox", NDPI_PROTOCOL_CATEGORY_CLOUD,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 17500, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SPOTIFY, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Spotify", NDPI_PROTOCOL_CATEGORY_MUSIC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MESSENGER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Messenger", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LISP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "LISP", NDPI_PROTOCOL_CATEGORY_CLOUD,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 4342, 4341, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_EAQ, 0 /* can_have_a_subprotocol */,
no_master, no_master, "EAQ", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 6000, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_KAKAOTALK_VOICE,
0 /* can_have_a_subprotocol */, no_master, no_master, "KakaoTalk_Voice",
NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_MPEGTS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MPEG_TS", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
/* http://en.wikipedia.org/wiki/Link-local_Multicast_Name_Resolution */
ndpi_set_proto_defaults(
ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_LLMNR, 0 /* can_have_a_subprotocol */, no_master, no_master,
"LLMNR", NDPI_PROTOCOL_CATEGORY_NETWORK, ndpi_build_default_ports(ports_a, 5355, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5355, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */
ndpi_set_proto_defaults(
ndpi_str, NDPI_PROTOCOL_POTENTIALLY_DANGEROUS, NDPI_PROTOCOL_REMOTE_SCAN, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RemoteScan", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 6077, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 6078, 0, 0, 0, 0) /* UDP */); /* Missing dissector: port based only */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_H323, 0 /* can_have_a_subprotocol */,
no_master, no_master, "H323", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 1719, 1720, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 1719, 1720, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_OPENVPN, 0 /* can_have_a_subprotocol */,
no_master, no_master, "OpenVPN", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 1194, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 1194, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_NOE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "NOE", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CISCOVPN, 0 /* can_have_a_subprotocol */,
no_master, no_master, "CiscoVPN", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 10000, 8008, 8009, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 10000, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TEAMSPEAK, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TeamSpeak", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SKINNY, 0 /* can_have_a_subprotocol */,
no_master, no_master, "CiscoSkinny", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 2000, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTCP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RTCP", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RSYNC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RSYNC", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER,
ndpi_build_default_ports(ports_a, 873, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ORACLE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Oracle", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 1521, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CORBA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Corba", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_UBUNTUONE, 0 /* can_have_a_subprotocol */,
no_master, no_master, "UbuntuONE", NDPI_PROTOCOL_CATEGORY_CLOUD,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WHOIS_DAS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Whois-DAS", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 43, 4343, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_COLLECTD, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Collectd", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 25826, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOCKS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SOCKS", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 1080, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 1080, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TFTP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TFTP", NDPI_PROTOCOL_CATEGORY_DATA_TRANSFER,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 69, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RTMP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RTMP", NDPI_PROTOCOL_CATEGORY_MEDIA,
ndpi_build_default_ports(ports_a, 1935, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_PANDO, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Pando_Media_Booster", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MEGACO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Megaco", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 2944, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_REDIS, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Redis", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 6379, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZMQ, 0 /* can_have_a_subprotocol */,
no_master, no_master, "ZeroMQ", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_VHUA, 0 /* can_have_a_subprotocol */, no_master,
no_master, "VHUA", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 58267, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_STARCRAFT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Starcraft", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 1119, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 1119, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_UBNTAC2, 0 /* can_have_a_subprotocol */,
no_master, no_master, "UBNTAC2", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 10001, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_VIBER, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Viber", NDPI_PROTOCOL_CATEGORY_VOIP,
ndpi_build_default_ports(ports_a, 7985, 5242, 5243, 4244, 0), /* TCP */
ndpi_build_default_ports(ports_b, 7985, 7987, 5242, 5243, 4244)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_COAP, 0 /* can_have_a_subprotocol */, no_master,
no_master, "COAP", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 5683, 5684, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_MQTT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "MQTT", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 1883, 8883, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SOMEIP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SOMEIP", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 30491, 30501, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 30491, 30501, 30490, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_RX, 0 /* can_have_a_subprotocol */,
no_master, no_master, "RX", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_GIT, 0 /* can_have_a_subprotocol */, no_master,
no_master, "Git", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE,
ndpi_build_default_ports(ports_a, 9418, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DRDA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DRDA", NDPI_PROTOCOL_CATEGORY_DATABASE,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_HANGOUT_DUO,
0 /* can_have_a_subprotocol */, no_master, no_master, "GoogleHangoutDuo",
NDPI_PROTOCOL_CATEGORY_VOIP, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BJNP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "BJNP", NDPI_PROTOCOL_CATEGORY_SYSTEM_OS,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 8612, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_SMPP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "SMPP", NDPI_PROTOCOL_CATEGORY_DOWNLOAD_FT,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_OOKLA, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Ookla", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMQP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "AMQP", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_DNSCRYPT, 0 /* can_have_a_subprotocol */,
no_master, no_master, "DNScrypt", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0), /* TCP */
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0)); /* UDP */
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TINC, 0 /* can_have_a_subprotocol */,
no_master, no_master, "TINC", NDPI_PROTOCOL_CATEGORY_VPN,
ndpi_build_default_ports(ports_a, 655, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 655, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_FIX, 0 /* can_have_a_subprotocol */, no_master,
no_master, "FIX", NDPI_PROTOCOL_CATEGORY_RPC,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_NINTENDO, 0 /* can_have_a_subprotocol */,
no_master, no_master, "Nintendo", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_FUN, NDPI_PROTOCOL_CSGO, 0 /* can_have_a_subprotocol */, no_master,
no_master, "CSGO", NDPI_PROTOCOL_CATEGORY_GAME,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AJP, 0 /* can_have_a_subprotocol */,
no_master, no_master, "AJP", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 8009, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_TARGUS_GETDATA,
0 /* can_have_a_subprotocol */, no_master, no_master, "Targus Dataspeed",
NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 5001, 5201, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5001, 5201, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_AMAZON_VIDEO,
0 /* can_have_a_subprotocol */, no_master, no_master, "AmazonVideo",
NDPI_PROTOCOL_CATEGORY_CLOUD, ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_DNP3, 1 /* no subprotocol */, no_master,
no_master, "DNP3", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 20000, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_IEC60870, 1 /* no subprotocol */,
no_master, no_master, "IEC60870",
NDPI_PROTOCOL_CATEGORY_NETWORK, /* Perhaps IoT in the future */
ndpi_build_default_ports(ports_a, 2404, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_BLOOMBERG, 1 /* no subprotocol */,
no_master, no_master, "Bloomberg", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_CAPWAP, 1 /* no subprotocol */, no_master,
no_master, "CAPWAP", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 5246, 5247, 0, 0, 0) /* UDP */
);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_ZABBIX, 1 /* no subprotocol */, no_master,
no_master, "Zabbix", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 10050, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */
);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_S7COMM, 1 /* no subprotocol */, no_master,
no_master, "s7comm", NDPI_PROTOCOL_CATEGORY_NETWORK,
ndpi_build_default_ports(ports_a, 102, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_SAFE, NDPI_PROTOCOL_MSTEAMS, 1 /* no subprotocol */, no_master,
no_master, "Teams", NDPI_PROTOCOL_CATEGORY_COLLABORATIVE,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */
);
ndpi_set_proto_defaults(ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, NDPI_PROTOCOL_WEBSOCKET,
1 /* can_have_a_subprotocol */, no_master,
no_master, "WebSocket", NDPI_PROTOCOL_CATEGORY_WEB,
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
#ifdef CUSTOM_NDPI_PROTOCOLS
#include "../../../nDPI-custom/custom_ndpi_main.c"
#endif
/* calling function for host and content matched protocols */
init_string_based_protocols(ndpi_str);
ndpi_validate_protocol_initialization(ndpi_str);
}
/* ****************************************************** */
#ifdef CUSTOM_NDPI_PROTOCOLS
#include "../../../nDPI-custom/custom_ndpi_protocols.c"
#endif
/* ****************************************************** */
static int ac_match_handler(AC_MATCH_t *m, AC_TEXT_t *txt, AC_REP_t *match) {
int min_len = (txt->length < m->patterns->length) ? txt->length : m->patterns->length;
char buf[64] = {'\0'}, *whatfound;
int min_buf_len = (txt->length > 63 /* sizeof(buf)-1 */) ? 63 : txt->length;
u_int buf_len = strlen(buf);
strncpy(buf, txt->astring, min_buf_len);
buf[min_buf_len] = '\0';
#ifdef MATCH_DEBUG
printf("Searching [to search: %s/%u][pattern: %s/%u] [len: %d][match_num: %u][%s]\n", buf,
(unigned int) txt->length, m->patterns->astring, (unigned int) m->patterns->length, min_len, m->match_num,
m->patterns->astring);
#endif
whatfound = strstr(buf, m->patterns->astring);
#ifdef MATCH_DEBUG
printf("[NDPI] %s() [searching=%s][pattern=%s][%s][%c]\n", __FUNCTION__, buf, m->patterns->astring,
whatfound ? whatfound : "<NULL>", whatfound[-1]);
#endif
if(whatfound) {
/*
The patch below allows in case of pattern ws.amazon.com
to avoid matching aws.amazon.com whereas a.ws.amazon.com
has to match
*/
if((whatfound != buf) && (m->patterns->astring[0] != '.') /* The searched pattern does not start with . */
&& strchr(m->patterns->astring, '.') /* The matched pattern has a . (e.g. numeric or sym IPs) */) {
int len = strlen(m->patterns->astring);
if((whatfound[-1] != '.') || ((m->patterns->astring[len - 1] != '.') &&
(whatfound[len] != '\0') /* endsWith does not hold here */)) {
return(0);
} else {
memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t)); /* Partial match? */
return(0); /* Keep searching as probably there is a better match */
}
}
}
/*
Return 1 for stopping to the first match.
We might consider searching for the more
specific match, paying more cpu cycles.
*/
memcpy(match, &m->patterns[0].rep, sizeof(AC_REP_t));
if(((buf_len >= min_len) && (strncmp(&buf[buf_len - min_len], m->patterns->astring, min_len) == 0)) ||
(strncmp(buf, m->patterns->astring, min_len) == 0) /* begins with */
) {
#ifdef MATCH_DEBUG
printf("Found match [%s][%s] [len: %d]"
// "[proto_id: %u]"
"\n",
buf, m->patterns->astring, min_len /* , *matching_protocol_id */);
#endif
return(1); /* If the pattern found matches the string at the beginning we stop here */
} else {
#ifdef MATCH_DEBUG
printf("NO match found: continue\n");
#endif
return(0); /* 0 to continue searching, !0 to stop */
}
}
/* ******************************************************************** */
static int fill_prefix_v4(prefix_t *p, const struct in_addr *a, int b, int mb) {
if(b < 0 || b > mb)
return(-1);
memset(p, 0, sizeof(prefix_t));
memcpy(&p->add.sin, a, (mb + 7) / 8);
p->family = AF_INET;
p->bitlen = b;
p->ref_count = 0;
return(0);
}
/* ******************************************* */
static int fill_prefix_v6(prefix_t *prefix, const struct in6_addr *addr, int bits, int maxbits) {
#ifdef PATRICIA_IPV6
if(bits < 0 || bits > maxbits)
return -1;
memcpy(&prefix->add.sin6, addr, (maxbits + 7) / 8);
prefix->family = AF_INET6, prefix->bitlen = bits, prefix->ref_count = 0;
return 0;
#else
return(-1);
#endif
}
/* ******************************************* */
u_int16_t ndpi_network_ptree_match(struct ndpi_detection_module_struct *ndpi_str,
struct in_addr *pin /* network byte order */) {
prefix_t prefix;
patricia_node_t *node;
/* Make sure all in network byte order otherwise compares wont work */
fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits);
node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix);
return(node ? node->value.uv.user_value : NDPI_PROTOCOL_UNKNOWN);
}
/* ******************************************* */
u_int16_t ndpi_network_port_ptree_match(struct ndpi_detection_module_struct *ndpi_str,
struct in_addr *pin /* network byte order */,
u_int16_t port /* network byte order */) {
prefix_t prefix;
patricia_node_t *node;
/* Make sure all in network byte order otherwise compares wont work */
fill_prefix_v4(&prefix, pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits);
node = ndpi_patricia_search_best(ndpi_str->protocols_ptree, &prefix);
if(node) {
if((node->value.uv.additional_user_value == 0)
|| (node->value.uv.additional_user_value == port))
return(node->value.uv.user_value);
}
return(NDPI_PROTOCOL_UNKNOWN);
}
/* ******************************************* */
#if 0
static u_int8_t tor_ptree_match(struct ndpi_detection_module_struct *ndpi_str, struct in_addr *pin) {
return((ndpi_network_ptree_match(ndpi_str, pin) == NDPI_PROTOCOL_TOR) ? 1 : 0);
}
#endif
/* ******************************************* */
u_int8_t ndpi_is_tor_flow(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) {
struct ndpi_packet_struct *packet = &flow->packet;
if(packet->tcp != NULL) {
if(packet->iph) {
if(flow->guessed_host_protocol_id == NDPI_PROTOCOL_TOR)
return(1);
}
}
return(0);
}
/* ******************************************* */
static patricia_node_t *add_to_ptree(patricia_tree_t *tree, int family, void *addr, int bits) {
prefix_t prefix;
patricia_node_t *node;
fill_prefix_v4(&prefix, (struct in_addr *) addr, bits, tree->maxbits);
node = ndpi_patricia_lookup(tree, &prefix);
if(node) memset(&node->value, 0, sizeof(node->value));
return(node);
}
/* ******************************************* */
/*
Load a file containing IPv4 addresses in CIDR format as 'protocol_id'
Return: the number of entries loaded or -1 in case of error
*/
int ndpi_load_ipv4_ptree(struct ndpi_detection_module_struct *ndpi_str,
const char *path, u_int16_t protocol_id) {
char buffer[128], *line, *addr, *cidr, *saveptr;
FILE *fd;
int len;
u_int num_loaded = 0;
fd = fopen(path, "r");
if(fd == NULL) {
NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno));
return(-1);
}
while (1) {
line = fgets(buffer, sizeof(buffer), fd);
if(line == NULL)
break;
len = strlen(line);
if((len <= 1) || (line[0] == '#'))
continue;
line[len - 1] = '\0';
addr = strtok_r(line, "/", &saveptr);
if(addr) {
struct in_addr pin;
patricia_node_t *node;
cidr = strtok_r(NULL, "\n", &saveptr);
pin.s_addr = inet_addr(addr);
if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, cidr ? atoi(cidr) : 32 /* bits */)) != NULL) {
node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = 0 /* port */;
num_loaded++;
}
}
}
fclose(fd);
return(num_loaded);
}
/* ******************************************* */
static void ndpi_init_ptree_ipv4(struct ndpi_detection_module_struct *ndpi_str,
void *ptree, ndpi_network host_list[],
u_int8_t skip_tor_hosts) {
int i;
for (i = 0; host_list[i].network != 0x0; i++) {
struct in_addr pin;
patricia_node_t *node;
if(skip_tor_hosts && (host_list[i].value == NDPI_PROTOCOL_TOR))
continue;
pin.s_addr = htonl(host_list[i].network);
if((node = add_to_ptree(ptree, AF_INET, &pin, host_list[i].cidr /* bits */)) != NULL) {
node->value.uv.user_value = host_list[i].value, node->value.uv.additional_user_value = 0;
}
}
}
/* ******************************************* */
static int ndpi_add_host_ip_subprotocol(struct ndpi_detection_module_struct *ndpi_str,
char *value, u_int16_t protocol_id) {
patricia_node_t *node;
struct in_addr pin;
int bits = 32;
char *ptr = strrchr(value, '/');
u_int16_t port = 0; /* Format ip:8.248.73.247:443 */
char *double_column;
if(ptr) {
ptr[0] = '\0';
ptr++;
if((double_column = strrchr(ptr, ':')) != NULL) {
double_column[0] = '\0';
port = atoi(&double_column[1]);
}
if(atoi(ptr) >= 0 && atoi(ptr) <= 32)
bits = atoi(ptr);
} else {
/*
Let's check if there is the port defined
Example: ip:8.248.73.247:443@AmazonPrime
*/
double_column = strrchr(value, ':');
if(double_column) {
double_column[0] = '\0';
port = atoi(&double_column[1]);
}
}
inet_pton(AF_INET, value, &pin);
if((node = add_to_ptree(ndpi_str->protocols_ptree, AF_INET, &pin, bits)) != NULL) {
node->value.uv.user_value = protocol_id, node->value.uv.additional_user_value = htons(port);
}
return(0);
}
void set_ndpi_malloc(void *(*__ndpi_malloc)(size_t size)) {
_ndpi_malloc = __ndpi_malloc;
}
void set_ndpi_flow_malloc(void *(*__ndpi_flow_malloc)(size_t size)) {
_ndpi_flow_malloc = __ndpi_flow_malloc;
}
void set_ndpi_free(void (*__ndpi_free)(void *ptr)) {
_ndpi_free = __ndpi_free;
}
void set_ndpi_flow_free(void (*__ndpi_flow_free)(void *ptr)) {
_ndpi_flow_free = __ndpi_flow_free;
}
void ndpi_debug_printf(unsigned int proto, struct ndpi_detection_module_struct *ndpi_str, ndpi_log_level_t log_level,
const char *file_name, const char *func_name, int line_number, const char *format, ...) {
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
va_list args;
#define MAX_STR_LEN 250
char str[MAX_STR_LEN];
if(ndpi_str != NULL && log_level > NDPI_LOG_ERROR && proto > 0 && proto < NDPI_MAX_SUPPORTED_PROTOCOLS &&
!NDPI_ISSET(&ndpi_str->debug_bitmask, proto))
return;
va_start(args, format);
vsnprintf(str, sizeof(str) - 1, format, args);
va_end(args);
if(ndpi_str != NULL) {
printf("%s:%s:%-3d - [%s]: %s", file_name, func_name, line_number, ndpi_get_proto_name(ndpi_str, proto), str);
} else {
printf("Proto: %u, %s", proto, str);
}
#endif
}
void set_ndpi_debug_function(struct ndpi_detection_module_struct *ndpi_str, ndpi_debug_function_ptr ndpi_debug_printf) {
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
ndpi_str->ndpi_debug_printf = ndpi_debug_printf;
#endif
}
/* ****************************************** */
/* Keep it in order and in sync with ndpi_protocol_category_t in ndpi_typedefs.h */
static const char *categories[] = {
"Unspecified",
"Media",
"VPN",
"Email",
"DataTransfer",
"Web",
"SocialNetwork",
"Download-FileTransfer-FileSharing",
"Game",
"Chat",
"VoIP",
"Database",
"RemoteAccess",
"Cloud",
"Network",
"Collaborative",
"RPC",
"Streaming",
"System",
"SoftwareUpdate",
"",
"",
"",
"",
"",
"Music",
"Video",
"Shopping",
"Productivity",
"FileSharing",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"",
"Mining", /* 99 */
"Malware",
"Advertisement",
"Banned_Site",
"Site_Unavailable",
"Allowed_Site",
"Antimalware",
};
/* ******************************************************************** */
struct ndpi_detection_module_struct *ndpi_init_detection_module(ndpi_init_prefs prefs) {
struct ndpi_detection_module_struct *ndpi_str = ndpi_malloc(sizeof(struct ndpi_detection_module_struct));
int i;
if(ndpi_str == NULL) {
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
NDPI_LOG_ERR(ndpi_str, "ndpi_init_detection_module initial malloc failed for ndpi_str\n");
#endif /* NDPI_ENABLE_DEBUG_MESSAGES */
return(NULL);
}
memset(ndpi_str, 0, sizeof(struct ndpi_detection_module_struct));
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
set_ndpi_debug_function(ndpi_str, (ndpi_debug_function_ptr) ndpi_debug_printf);
#endif /* NDPI_ENABLE_DEBUG_MESSAGES */
if((ndpi_str->protocols_ptree = ndpi_New_Patricia(32 /* IPv4 */)) != NULL)
ndpi_init_ptree_ipv4(ndpi_str, ndpi_str->protocols_ptree, host_protocol_list, prefs & ndpi_dont_load_tor_hosts);
NDPI_BITMASK_RESET(ndpi_str->detection_bitmask);
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
ndpi_str->user_data = NULL;
#endif
ndpi_str->ticks_per_second = 1000; /* ndpi_str->ticks_per_second */
ndpi_str->tcp_max_retransmission_window_size = NDPI_DEFAULT_MAX_TCP_RETRANSMISSION_WINDOW_SIZE;
ndpi_str->directconnect_connection_ip_tick_timeout =
NDPI_DIRECTCONNECT_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->rtsp_connection_timeout = NDPI_RTSP_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->tvants_connection_timeout = NDPI_TVANTS_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->irc_timeout = NDPI_IRC_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->gnutella_timeout = NDPI_GNUTELLA_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->battlefield_timeout = NDPI_BATTLEFIELD_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->thunder_timeout = NDPI_THUNDER_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->yahoo_detect_http_connections = NDPI_YAHOO_DETECT_HTTP_CONNECTIONS;
ndpi_str->yahoo_lan_video_timeout = NDPI_YAHOO_LAN_VIDEO_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->zattoo_connection_timeout = NDPI_ZATTOO_CONNECTION_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->jabber_stun_timeout = NDPI_JABBER_STUN_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->jabber_file_transfer_timeout = NDPI_JABBER_FT_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->soulseek_connection_ip_tick_timeout =
NDPI_SOULSEEK_CONNECTION_IP_TICK_TIMEOUT * ndpi_str->ticks_per_second;
ndpi_str->ndpi_num_supported_protocols = NDPI_MAX_SUPPORTED_PROTOCOLS;
ndpi_str->ndpi_num_custom_protocols = 0;
ndpi_str->host_automa.ac_automa = ac_automata_init(ac_match_handler);
ndpi_str->content_automa.ac_automa = ac_automata_init(ac_match_handler);
ndpi_str->bigrams_automa.ac_automa = ac_automata_init(ac_match_handler);
ndpi_str->impossible_bigrams_automa.ac_automa = ac_automata_init(ac_match_handler);
if((sizeof(categories) / sizeof(char *)) != NDPI_PROTOCOL_NUM_CATEGORIES) {
NDPI_LOG_ERR(ndpi_str, "[NDPI] invalid categories length: expected %u, got %u\n", NDPI_PROTOCOL_NUM_CATEGORIES,
(unsigned int) (sizeof(categories) / sizeof(char *)));
return(NULL);
}
ndpi_str->custom_categories.hostnames.ac_automa = ac_automata_init(ac_match_handler);
ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler);
ndpi_str->custom_categories.ipAddresses = ndpi_New_Patricia(32 /* IPv4 */);
ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */);
if((ndpi_str->custom_categories.ipAddresses == NULL) || (ndpi_str->custom_categories.ipAddresses_shadow == NULL))
return(NULL);
ndpi_init_protocol_defaults(ndpi_str);
for (i = 0; i < NUM_CUSTOM_CATEGORIES; i++)
snprintf(ndpi_str->custom_category_labels[i], CUSTOM_CATEGORY_LABEL_LEN, "User custom category %u",
(unsigned int) (i + 1));
return(ndpi_str);
}
/* *********************************************** */
void ndpi_finalize_initalization(struct ndpi_detection_module_struct *ndpi_str) {
u_int i;
for (i = 0; i < 4; i++) {
ndpi_automa *automa;
switch (i) {
case 0:
automa = &ndpi_str->host_automa;
break;
case 1:
automa = &ndpi_str->content_automa;
break;
case 2:
automa = &ndpi_str->bigrams_automa;
break;
case 3:
automa = &ndpi_str->impossible_bigrams_automa;
break;
default:
automa = NULL;
break;
}
if(automa) {
ac_automata_finalize((AC_AUTOMATA_t *) automa->ac_automa);
automa->ac_automa_finalized = 1;
}
}
}
/* *********************************************** */
/* Wrappers */
void *ndpi_init_automa(void) {
return(ac_automata_init(ac_match_handler));
}
/* ****************************************************** */
int ndpi_add_string_value_to_automa(void *_automa, char *str, u_int32_t num) {
AC_PATTERN_t ac_pattern;
AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa;
AC_ERROR_t rc;
if(automa == NULL)
return(-1);
memset(&ac_pattern, 0, sizeof(ac_pattern));
ac_pattern.astring = str;
ac_pattern.rep.number = num;
ac_pattern.length = strlen(ac_pattern.astring);
rc = ac_automata_add(automa, &ac_pattern);
return(rc == ACERR_SUCCESS || rc == ACERR_DUPLICATE_PATTERN ? 0 : -1);
}
/* ****************************************************** */
int ndpi_add_string_to_automa(void *_automa, char *str) {
return(ndpi_add_string_value_to_automa(_automa, str, 1));
}
/* ****************************************************** */
void ndpi_free_automa(void *_automa) {
ac_automata_release((AC_AUTOMATA_t *) _automa, 0);
}
/* ****************************************************** */
void ndpi_finalize_automa(void *_automa) {
ac_automata_finalize((AC_AUTOMATA_t *) _automa);
}
/* ****************************************************** */
int ndpi_match_string(void *_automa, char *string_to_match) {
AC_REP_t match = { NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED };
AC_TEXT_t ac_input_text;
AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa;
int rc;
if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0'))
return(-2);
ac_input_text.astring = string_to_match, ac_input_text.length = strlen(string_to_match);
rc = ac_automata_search(automa, &ac_input_text, &match);
/*
As ac_automata_search can detect partial matches and continue the search process
in case rc == 0 (i.e. no match), we need to check if there is a partial match
and in this case return it
*/
if((rc == 0) && (match.number != 0))
rc = 1;
return(rc ? match.number : 0);
}
/* ****************************************************** */
int ndpi_match_string_protocol_id(void *_automa, char *string_to_match,
u_int match_len, u_int16_t *protocol_id,
ndpi_protocol_category_t *category,
ndpi_protocol_breed_t *breed) {
AC_TEXT_t ac_input_text;
AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa;
AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED };
int rc;
*protocol_id = (u_int16_t)-1;
if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0'))
return(-2);
ac_input_text.astring = string_to_match, ac_input_text.length = match_len;
rc = ac_automata_search(automa, &ac_input_text, &match);
/*
As ac_automata_search can detect partial matches and continue the search process
in case rc == 0 (i.e. no match), we need to check if there is a partial match
and in this case return it
*/
if((rc == 0) && (match.number != 0))
rc = 1;
if(rc)
*protocol_id = (u_int16_t)match.number, *category = match.category,
*breed = match.breed;
else
*protocol_id = NDPI_PROTOCOL_UNKNOWN;
return((*protocol_id != NDPI_PROTOCOL_UNKNOWN) ? 0 : -1);
}
/* ****************************************************** */
int ndpi_match_string_value(void *_automa, char *string_to_match,
u_int match_len, u_int32_t *num) {
AC_TEXT_t ac_input_text;
AC_AUTOMATA_t *automa = (AC_AUTOMATA_t *) _automa;
AC_REP_t match = { 0, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED };
int rc;
*num = (u_int32_t)-1;
if((automa == NULL) || (string_to_match == NULL) || (string_to_match[0] == '\0'))
return(-2);
ac_input_text.astring = string_to_match, ac_input_text.length = match_len;
rc = ac_automata_search(automa, &ac_input_text, &match);
/*
As ac_automata_search can detect partial matches and continue the search process
in case rc == 0 (i.e. no match), we need to check if there is a partial match
and in this case return it
*/
if((rc == 0) && (match.number != 0))
rc = 1;
if(rc)
*num = match.number;
else
*num = 0;
return(rc ? 0 : -1);
}
/* *********************************************** */
int ndpi_match_custom_category(struct ndpi_detection_module_struct *ndpi_str,
char *name, u_int name_len,
ndpi_protocol_category_t *category) {
ndpi_protocol_breed_t breed;
u_int16_t id;
int rc = ndpi_match_string_protocol_id(ndpi_str->custom_categories.hostnames.ac_automa,
name, name_len, &id, category, &breed);
return(rc);
}
/* *********************************************** */
int ndpi_get_custom_category_match(struct ndpi_detection_module_struct *ndpi_str,
char *name_or_ip, u_int name_len,
ndpi_protocol_category_t *id) {
char ipbuf[64], *ptr;
struct in_addr pin;
u_int cp_len = ndpi_min(sizeof(ipbuf) - 1, name_len);
if(!ndpi_str->custom_categories.categories_loaded)
return(-1);
if(cp_len > 0) {
memcpy(ipbuf, name_or_ip, cp_len);
ipbuf[cp_len] = '\0';
} else
ipbuf[0] = '\0';
ptr = strrchr(ipbuf, '/');
if(ptr)
ptr[0] = '\0';
if(inet_pton(AF_INET, ipbuf, &pin) == 1) {
/* Search IP */
prefix_t prefix;
patricia_node_t *node;
/* Make sure all in network byte order otherwise compares wont work */
fill_prefix_v4(&prefix, &pin, 32, ((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits);
node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix);
if(node) {
*id = node->value.uv.user_value;
return(0);
}
return(-1);
} else {
/* Search Host */
return(ndpi_match_custom_category(ndpi_str, name_or_ip, name_len, id));
}
}
/* *********************************************** */
static void free_ptree_data(void *data) {
;
}
/* ****************************************************** */
void ndpi_exit_detection_module(struct ndpi_detection_module_struct *ndpi_str) {
if(ndpi_str != NULL) {
int i;
for (i = 0; i < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS); i++) {
if(ndpi_str->proto_defaults[i].protoName)
ndpi_free(ndpi_str->proto_defaults[i].protoName);
}
/* NDPI_PROTOCOL_TINC */
if(ndpi_str->tinc_cache)
cache_free((cache_t)(ndpi_str->tinc_cache));
if(ndpi_str->ookla_cache)
ndpi_lru_free_cache(ndpi_str->ookla_cache);
if(ndpi_str->stun_cache)
ndpi_lru_free_cache(ndpi_str->stun_cache);
if(ndpi_str->msteams_cache)
ndpi_lru_free_cache(ndpi_str->msteams_cache);
if(ndpi_str->protocols_ptree)
ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->protocols_ptree, free_ptree_data);
if(ndpi_str->udpRoot != NULL)
ndpi_tdestroy(ndpi_str->udpRoot, ndpi_free);
if(ndpi_str->tcpRoot != NULL)
ndpi_tdestroy(ndpi_str->tcpRoot, ndpi_free);
if(ndpi_str->host_automa.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->host_automa.ac_automa,
1 /* free patterns strings memory */);
if(ndpi_str->content_automa.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->content_automa.ac_automa, 0);
if(ndpi_str->bigrams_automa.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->bigrams_automa.ac_automa, 0);
if(ndpi_str->impossible_bigrams_automa.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->impossible_bigrams_automa.ac_automa, 0);
if(ndpi_str->custom_categories.hostnames.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa,
1 /* free patterns strings memory */);
if(ndpi_str->custom_categories.hostnames_shadow.ac_automa != NULL)
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa,
1 /* free patterns strings memory */);
if(ndpi_str->custom_categories.ipAddresses != NULL)
ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data);
if(ndpi_str->custom_categories.ipAddresses_shadow != NULL)
ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses_shadow, free_ptree_data);
#ifdef CUSTOM_NDPI_PROTOCOLS
#include "../../../nDPI-custom/ndpi_exit_detection_module.c"
#endif
ndpi_free(ndpi_str);
}
}
/* ****************************************************** */
int ndpi_get_protocol_id_master_proto(struct ndpi_detection_module_struct *ndpi_str, u_int16_t protocol_id,
u_int16_t **tcp_master_proto, u_int16_t **udp_master_proto) {
if(protocol_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) {
*tcp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_tcp_protoId,
*udp_master_proto = ndpi_str->proto_defaults[NDPI_PROTOCOL_UNKNOWN].master_udp_protoId;
return(-1);
}
*tcp_master_proto = ndpi_str->proto_defaults[protocol_id].master_tcp_protoId,
*udp_master_proto = ndpi_str->proto_defaults[protocol_id].master_udp_protoId;
return(0);
}
/* ****************************************************** */
static ndpi_default_ports_tree_node_t *ndpi_get_guessed_protocol_id(struct ndpi_detection_module_struct *ndpi_str,
u_int8_t proto, u_int16_t sport, u_int16_t dport) {
ndpi_default_ports_tree_node_t node;
if(sport && dport) {
int low = ndpi_min(sport, dport);
int high = ndpi_max(sport, dport);
const void *ret;
node.default_port = low; /* Check server port first */
ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot,
ndpi_default_ports_tree_node_t_cmp);
if(ret == NULL) {
node.default_port = high;
ret = ndpi_tfind(&node, (proto == IPPROTO_TCP) ? (void *) &ndpi_str->tcpRoot : (void *) &ndpi_str->udpRoot,
ndpi_default_ports_tree_node_t_cmp);
}
if(ret)
return(*(ndpi_default_ports_tree_node_t **) ret);
}
return(NULL);
}
/* ****************************************************** */
/*
These are UDP protocols that must fit a single packet
and thus that if have NOT been detected they cannot be guessed
as they have been excluded
*/
u_int8_t is_udp_guessable_protocol(u_int16_t l7_guessed_proto) {
switch (l7_guessed_proto) {
case NDPI_PROTOCOL_QUIC:
case NDPI_PROTOCOL_SNMP:
case NDPI_PROTOCOL_NETFLOW:
/* TODO: add more protocols (if any missing) */
return(1);
}
return(0);
}
/* ****************************************************** */
u_int16_t ndpi_guess_protocol_id(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int8_t proto, u_int16_t sport, u_int16_t dport, u_int8_t *user_defined_proto) {
*user_defined_proto = 0; /* Default */
if(sport && dport) {
ndpi_default_ports_tree_node_t *found = ndpi_get_guessed_protocol_id(ndpi_str, proto, sport, dport);
if(found != NULL) {
u_int16_t guessed_proto = found->proto->protoId;
/* We need to check if the guessed protocol isn't excluded by nDPI */
if(flow && (proto == IPPROTO_UDP) &&
NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, guessed_proto) &&
is_udp_guessable_protocol(guessed_proto))
return(NDPI_PROTOCOL_UNKNOWN);
else {
*user_defined_proto = found->customUserProto;
return(guessed_proto);
}
}
} else {
/* No TCP/UDP */
switch (proto) {
case NDPI_IPSEC_PROTOCOL_ESP:
case NDPI_IPSEC_PROTOCOL_AH:
return(NDPI_PROTOCOL_IP_IPSEC);
break;
case NDPI_GRE_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_GRE);
break;
case NDPI_ICMP_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_ICMP);
break;
case NDPI_IGMP_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_IGMP);
break;
case NDPI_EGP_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_EGP);
break;
case NDPI_SCTP_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_SCTP);
break;
case NDPI_OSPF_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_OSPF);
break;
case NDPI_IPIP_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_IP_IN_IP);
break;
case NDPI_ICMPV6_PROTOCOL_TYPE:
return(NDPI_PROTOCOL_IP_ICMPV6);
break;
case 112:
return(NDPI_PROTOCOL_IP_VRRP);
break;
}
}
return(NDPI_PROTOCOL_UNKNOWN);
}
/* ******************************************************************** */
u_int ndpi_get_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) {
return(ndpi_str->ndpi_num_supported_protocols);
}
/* ******************************************************************** */
#ifdef WIN32
char *strsep(char **sp, char *sep) {
char *p, *s;
if(sp == NULL || *sp == NULL || **sp == '\0')
return(NULL);
s = *sp;
p = s + strcspn(s, sep);
if(*p != '\0')
*p++ = '\0';
*sp = p;
return(s);
}
#endif
/* ******************************************************************** */
int ndpi_handle_rule(struct ndpi_detection_module_struct *ndpi_str, char *rule, u_int8_t do_add) {
char *at, *proto, *elem;
ndpi_proto_defaults_t *def;
u_int16_t subprotocol_id, i;
at = strrchr(rule, '@');
if(at == NULL) {
NDPI_LOG_ERR(ndpi_str, "Invalid rule '%s'\n", rule);
return(-1);
} else
at[0] = 0, proto = &at[1];
for (i = 0; proto[i] != '\0'; i++) {
switch (proto[i]) {
case '/':
case '&':
case '^':
case ':':
case ';':
case '\'':
case '"':
case ' ':
proto[i] = '_';
break;
}
}
for (i = 0, def = NULL; i < (int) ndpi_str->ndpi_num_supported_protocols; i++) {
if(ndpi_str->proto_defaults[i].protoName && strcasecmp(ndpi_str->proto_defaults[i].protoName, proto) == 0) {
def = &ndpi_str->proto_defaults[i];
subprotocol_id = i;
break;
}
}
if(def == NULL) {
if(!do_add) {
/* We need to remove a rule */
NDPI_LOG_ERR(ndpi_str, "Unable to find protocol '%s': skipping rule '%s'\n", proto, rule);
return(-3);
} else {
ndpi_port_range ports_a[MAX_DEFAULT_PORTS], ports_b[MAX_DEFAULT_PORTS];
u_int16_t no_master[2] = {NDPI_PROTOCOL_NO_MASTER_PROTO, NDPI_PROTOCOL_NO_MASTER_PROTO};
if(ndpi_str->ndpi_num_custom_protocols >= (NDPI_MAX_NUM_CUSTOM_PROTOCOLS - 1)) {
NDPI_LOG_ERR(ndpi_str, "Too many protocols defined (%u): skipping protocol %s\n",
ndpi_str->ndpi_num_custom_protocols, proto);
return(-2);
}
ndpi_set_proto_defaults(
ndpi_str, NDPI_PROTOCOL_ACCEPTABLE, ndpi_str->ndpi_num_supported_protocols,
0 /* can_have_a_subprotocol */, no_master, no_master, proto,
NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, /* TODO add protocol category support in rules */
ndpi_build_default_ports(ports_a, 0, 0, 0, 0, 0) /* TCP */,
ndpi_build_default_ports(ports_b, 0, 0, 0, 0, 0) /* UDP */);
def = &ndpi_str->proto_defaults[ndpi_str->ndpi_num_supported_protocols];
subprotocol_id = ndpi_str->ndpi_num_supported_protocols;
ndpi_str->ndpi_num_supported_protocols++, ndpi_str->ndpi_num_custom_protocols++;
}
}
while ((elem = strsep(&rule, ",")) != NULL) {
char *attr = elem, *value = NULL;
ndpi_port_range range;
int is_tcp = 0, is_udp = 0, is_ip = 0;
if(strncmp(attr, "tcp:", 4) == 0)
is_tcp = 1, value = &attr[4];
else if(strncmp(attr, "udp:", 4) == 0)
is_udp = 1, value = &attr[4];
else if(strncmp(attr, "ip:", 3) == 0)
is_ip = 1, value = &attr[3];
else if(strncmp(attr, "host:", 5) == 0) {
/* host:"<value>",host:"<value>",.....@<subproto> */
value = &attr[5];
if(value[0] == '"')
value++; /* remove leading " */
if(value[strlen(value) - 1] == '"')
value[strlen(value) - 1] = '\0'; /* remove trailing " */
}
if(is_tcp || is_udp) {
u_int p_low, p_high;
if(sscanf(value, "%u-%u", &p_low, &p_high) == 2)
range.port_low = p_low, range.port_high = p_high;
else
range.port_low = range.port_high = atoi(&elem[4]);
if(do_add)
addDefaultPort(ndpi_str, &range, def, 1 /* Custom user proto */,
is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot, __FUNCTION__, __LINE__);
else
removeDefaultPort(&range, def, is_tcp ? &ndpi_str->tcpRoot : &ndpi_str->udpRoot);
} else if(is_ip) {
/* NDPI_PROTOCOL_TOR */
ndpi_add_host_ip_subprotocol(ndpi_str, value, subprotocol_id);
} else {
if(do_add)
ndpi_add_host_url_subprotocol(ndpi_str, value, subprotocol_id, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED,
NDPI_PROTOCOL_ACCEPTABLE);
else
ndpi_remove_host_url_subprotocol(ndpi_str, value, subprotocol_id);
}
}
return(0);
}
/* ******************************************************************** */
/*
* Format:
*
* <host|ip> <category_id>
*
* Notes:
* - host and category are separated by a single TAB
* - empty lines or lines starting with # are ignored
*/
int ndpi_load_categories_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) {
char buffer[512], *line, *name, *category, *saveptr;
FILE *fd;
int len, num = 0;
fd = fopen(path, "r");
if(fd == NULL) {
NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno));
return(-1);
}
while (1) {
line = fgets(buffer, sizeof(buffer), fd);
if(line == NULL)
break;
len = strlen(line);
if((len <= 1) || (line[0] == '#'))
continue;
line[len - 1] = '\0';
name = strtok_r(line, "\t", &saveptr);
if(name) {
category = strtok_r(NULL, "\t", &saveptr);
if(category) {
int rc = ndpi_load_category(ndpi_str, name, (ndpi_protocol_category_t) atoi(category));
if(rc >= 0)
num++;
}
}
}
fclose(fd);
ndpi_enable_loaded_categories(ndpi_str);
return(num);
}
/* ******************************************************************** */
/*
Format:
<tcp|udp>:<port>,<tcp|udp>:<port>,.....@<proto>
Subprotocols Format:
host:"<value>",host:"<value>",.....@<subproto>
IP based Subprotocols Format (<value> is IP or CIDR):
ip:<value>,ip:<value>,.....@<subproto>
Example:
tcp:80,tcp:3128@HTTP
udp:139@NETBIOS
*/
int ndpi_load_protocols_file(struct ndpi_detection_module_struct *ndpi_str, const char *path) {
FILE *fd;
char *buffer, *old_buffer;
int chunk_len = 512, buffer_len = chunk_len, old_buffer_len;
int i, rc = -1;
fd = fopen(path, "r");
if(fd == NULL) {
NDPI_LOG_ERR(ndpi_str, "Unable to open file %s [%s]\n", path, strerror(errno));
goto error;
}
buffer = ndpi_malloc(buffer_len);
if(buffer == NULL) {
NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n");
goto close_fd;
}
while (1) {
char *line = buffer;
int line_len = buffer_len;
while ((line = fgets(line, line_len, fd)) != NULL && line[strlen(line) - 1] != '\n') {
i = strlen(line);
old_buffer = buffer;
old_buffer_len = buffer_len;
buffer_len += chunk_len;
buffer = ndpi_realloc(old_buffer, old_buffer_len, buffer_len);
if(buffer == NULL) {
NDPI_LOG_ERR(ndpi_str, "Memory allocation failure\n");
ndpi_free(old_buffer);
goto close_fd;
}
line = &buffer[i];
line_len = chunk_len;
}
if(!line) /* safety check */
break;
i = strlen(buffer);
if((i <= 1) || (buffer[0] == '#'))
continue;
else
buffer[i - 1] = '\0';
ndpi_handle_rule(ndpi_str, buffer, 1);
}
rc = 0;
ndpi_free(buffer);
close_fd:
fclose(fd);
error:
return(rc);
}
/* ******************************************************************** */
/* ntop */
void ndpi_set_bitmask_protocol_detection(char *label, struct ndpi_detection_module_struct *ndpi_str,
const NDPI_PROTOCOL_BITMASK *detection_bitmask, const u_int32_t idx,
u_int16_t ndpi_protocol_id,
void (*func)(struct ndpi_detection_module_struct *,
struct ndpi_flow_struct *flow),
const NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_bitmask,
u_int8_t b_save_bitmask_unknow, u_int8_t b_add_detection_bitmask) {
/*
Compare specify protocol bitmask with main detection bitmask
*/
if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(*detection_bitmask, ndpi_protocol_id) != 0) {
#ifdef DEBUG
NDPI_LOG_DBG2(ndpi_str,
"[NDPI] ndpi_set_bitmask_protocol_detection: %s : [callback_buffer] idx= %u, [proto_defaults] "
"protocol_id=%u\n",
label, idx, ndpi_protocol_id);
#endif
if(ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx != 0) {
NDPI_LOG_DBG2(ndpi_str, "[NDPI] Internal error: protocol %s/%u has been already registered\n", label,
ndpi_protocol_id);
#ifdef DEBUG
} else {
NDPI_LOG_DBG2(ndpi_str, "[NDPI] Adding %s with protocol id %d\n", label, ndpi_protocol_id);
#endif
}
/*
Set function and index protocol within proto_default structure for port protocol detection
and callback_buffer function for DPI protocol detection
*/
ndpi_str->proto_defaults[ndpi_protocol_id].protoIdx = idx;
ndpi_str->proto_defaults[ndpi_protocol_id].func = ndpi_str->callback_buffer[idx].func = func;
/*
Set ndpi_selection_bitmask for protocol
*/
ndpi_str->callback_buffer[idx].ndpi_selection_bitmask = ndpi_selection_bitmask;
/*
Reset protocol detection bitmask via NDPI_PROTOCOL_UNKNOWN and than add specify protocol bitmast to callback
buffer.
*/
if(b_save_bitmask_unknow)
NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, NDPI_PROTOCOL_UNKNOWN);
if(b_add_detection_bitmask)
NDPI_ADD_PROTOCOL_TO_BITMASK(ndpi_str->callback_buffer[idx].detection_bitmask, ndpi_protocol_id);
NDPI_SAVE_AS_BITMASK(ndpi_str->callback_buffer[idx].excluded_protocol_bitmask, ndpi_protocol_id);
}
}
/* ******************************************************************** */
void ndpi_set_protocol_detection_bitmask2(struct ndpi_detection_module_struct *ndpi_str,
const NDPI_PROTOCOL_BITMASK *dbm) {
NDPI_PROTOCOL_BITMASK detection_bitmask_local;
NDPI_PROTOCOL_BITMASK *detection_bitmask = &detection_bitmask_local;
u_int32_t a = 0;
NDPI_BITMASK_SET(detection_bitmask_local, *dbm);
NDPI_BITMASK_SET(ndpi_str->detection_bitmask, *dbm);
/* set this here to zero to be interrupt safe */
ndpi_str->callback_buffer_size = 0;
/* HTTP */
init_http_dissector(ndpi_str, &a, detection_bitmask);
/* STARCRAFT */
init_starcraft_dissector(ndpi_str, &a, detection_bitmask);
/* TLS */
init_tls_dissector(ndpi_str, &a, detection_bitmask);
/* STUN */
init_stun_dissector(ndpi_str, &a, detection_bitmask);
/* RTP */
init_rtp_dissector(ndpi_str, &a, detection_bitmask);
/* RTSP */
init_rtsp_dissector(ndpi_str, &a, detection_bitmask);
/* RDP */
init_rdp_dissector(ndpi_str, &a, detection_bitmask);
/* SIP */
init_sip_dissector(ndpi_str, &a, detection_bitmask);
/* IMO */
init_imo_dissector(ndpi_str, &a, detection_bitmask);
/* Teredo */
init_teredo_dissector(ndpi_str, &a, detection_bitmask);
/* EDONKEY */
init_edonkey_dissector(ndpi_str, &a, detection_bitmask);
/* FASTTRACK */
init_fasttrack_dissector(ndpi_str, &a, detection_bitmask);
/* GNUTELLA */
init_gnutella_dissector(ndpi_str, &a, detection_bitmask);
/* DIRECTCONNECT */
init_directconnect_dissector(ndpi_str, &a, detection_bitmask);
/* NATS */
init_nats_dissector(ndpi_str, &a, detection_bitmask);
/* YAHOO */
init_yahoo_dissector(ndpi_str, &a, detection_bitmask);
/* OSCAR */
init_oscar_dissector(ndpi_str, &a, detection_bitmask);
/* APPLEJUICE */
init_applejuice_dissector(ndpi_str, &a, detection_bitmask);
/* SOULSEEK */
init_soulseek_dissector(ndpi_str, &a, detection_bitmask);
/* SOCKS */
init_socks_dissector(ndpi_str, &a, detection_bitmask);
/* IRC */
init_irc_dissector(ndpi_str, &a, detection_bitmask);
/* JABBER */
init_jabber_dissector(ndpi_str, &a, detection_bitmask);
/* MAIL_POP */
init_mail_pop_dissector(ndpi_str, &a, detection_bitmask);
/* MAIL_IMAP */
init_mail_imap_dissector(ndpi_str, &a, detection_bitmask);
/* MAIL_SMTP */
init_mail_smtp_dissector(ndpi_str, &a, detection_bitmask);
/* USENET */
init_usenet_dissector(ndpi_str, &a, detection_bitmask);
/* DNS */
init_dns_dissector(ndpi_str, &a, detection_bitmask);
/* FILETOPIA */
init_fbzero_dissector(ndpi_str, &a, detection_bitmask);
/* VMWARE */
init_vmware_dissector(ndpi_str, &a, detection_bitmask);
/* NON_TCP_UDP */
init_non_tcp_udp_dissector(ndpi_str, &a, detection_bitmask);
/* TVANTS */
init_tvants_dissector(ndpi_str, &a, detection_bitmask);
/* SOPCAST */
init_sopcast_dissector(ndpi_str, &a, detection_bitmask);
/* TVUPLAYER */
init_tvuplayer_dissector(ndpi_str, &a, detection_bitmask);
/* PPSTREAM */
init_ppstream_dissector(ndpi_str, &a, detection_bitmask);
/* PPLIVE */
init_pplive_dissector(ndpi_str, &a, detection_bitmask);
/* IAX */
init_iax_dissector(ndpi_str, &a, detection_bitmask);
/* MGPC */
init_mgpc_dissector(ndpi_str, &a, detection_bitmask);
/* ZATTOO */
init_zattoo_dissector(ndpi_str, &a, detection_bitmask);
/* QQ */
init_qq_dissector(ndpi_str, &a, detection_bitmask);
/* SSH */
init_ssh_dissector(ndpi_str, &a, detection_bitmask);
/* AYIYA */
init_ayiya_dissector(ndpi_str, &a, detection_bitmask);
/* THUNDER */
init_thunder_dissector(ndpi_str, &a, detection_bitmask);
/* VNC */
init_vnc_dissector(ndpi_str, &a, detection_bitmask);
/* TEAMVIEWER */
init_teamviewer_dissector(ndpi_str, &a, detection_bitmask);
/* DHCP */
init_dhcp_dissector(ndpi_str, &a, detection_bitmask);
/* STEAM */
init_steam_dissector(ndpi_str, &a, detection_bitmask);
/* HALFLIFE2 */
init_halflife2_dissector(ndpi_str, &a, detection_bitmask);
/* XBOX */
init_xbox_dissector(ndpi_str, &a, detection_bitmask);
/* HTTP_APPLICATION_ACTIVESYNC */
init_http_activesync_dissector(ndpi_str, &a, detection_bitmask);
/* SMB */
init_smb_dissector(ndpi_str, &a, detection_bitmask);
/* MINING */
init_mining_dissector(ndpi_str, &a, detection_bitmask);
/* TELNET */
init_telnet_dissector(ndpi_str, &a, detection_bitmask);
/* NTP */
init_ntp_dissector(ndpi_str, &a, detection_bitmask);
/* NFS */
init_nfs_dissector(ndpi_str, &a, detection_bitmask);
/* SSDP */
init_ssdp_dissector(ndpi_str, &a, detection_bitmask);
/* WORLD_OF_WARCRAFT */
init_world_of_warcraft_dissector(ndpi_str, &a, detection_bitmask);
/* POSTGRES */
init_postgres_dissector(ndpi_str, &a, detection_bitmask);
/* MYSQL */
init_mysql_dissector(ndpi_str, &a, detection_bitmask);
/* BGP */
init_bgp_dissector(ndpi_str, &a, detection_bitmask);
/* BATTLEFIELD */
init_battlefield_dissector(ndpi_str, &a, detection_bitmask);
/* PCANYWHERE */
init_pcanywhere_dissector(ndpi_str, &a, detection_bitmask);
/* SNMP */
init_snmp_dissector(ndpi_str, &a, detection_bitmask);
/* KONTIKI */
init_kontiki_dissector(ndpi_str, &a, detection_bitmask);
/* ICECAST */
init_icecast_dissector(ndpi_str, &a, detection_bitmask);
/* SHOUTCAST */
init_shoutcast_dissector(ndpi_str, &a, detection_bitmask);
/* KERBEROS */
init_kerberos_dissector(ndpi_str, &a, detection_bitmask);
/* OPENFT */
init_openft_dissector(ndpi_str, &a, detection_bitmask);
/* SYSLOG */
init_syslog_dissector(ndpi_str, &a, detection_bitmask);
/* DIRECT_DOWNLOAD_LINK */
init_directdownloadlink_dissector(ndpi_str, &a, detection_bitmask);
/* NETBIOS */
init_netbios_dissector(ndpi_str, &a, detection_bitmask);
/* MDNS */
init_mdns_dissector(ndpi_str, &a, detection_bitmask);
/* IPP */
init_ipp_dissector(ndpi_str, &a, detection_bitmask);
/* LDAP */
init_ldap_dissector(ndpi_str, &a, detection_bitmask);
/* WARCRAFT3 */
init_warcraft3_dissector(ndpi_str, &a, detection_bitmask);
/* XDMCP */
init_xdmcp_dissector(ndpi_str, &a, detection_bitmask);
/* TFTP */
init_tftp_dissector(ndpi_str, &a, detection_bitmask);
/* MSSQL_TDS */
init_mssql_tds_dissector(ndpi_str, &a, detection_bitmask);
/* PPTP */
init_pptp_dissector(ndpi_str, &a, detection_bitmask);
/* STEALTHNET */
init_stealthnet_dissector(ndpi_str, &a, detection_bitmask);
/* DHCPV6 */
init_dhcpv6_dissector(ndpi_str, &a, detection_bitmask);
/* AFP */
init_afp_dissector(ndpi_str, &a, detection_bitmask);
/* check_mk */
init_checkmk_dissector(ndpi_str, &a, detection_bitmask);
/* AIMINI */
init_aimini_dissector(ndpi_str, &a, detection_bitmask);
/* FLORENSIA */
init_florensia_dissector(ndpi_str, &a, detection_bitmask);
/* MAPLESTORY */
init_maplestory_dissector(ndpi_str, &a, detection_bitmask);
/* DOFUS */
init_dofus_dissector(ndpi_str, &a, detection_bitmask);
/* WORLD_OF_KUNG_FU */
init_world_of_kung_fu_dissector(ndpi_str, &a, detection_bitmask);
/* FIESTA */
init_fiesta_dissector(ndpi_str, &a, detection_bitmask);
/* CROSSIFIRE */
init_crossfire_dissector(ndpi_str, &a, detection_bitmask);
/* GUILDWARS */
init_guildwars_dissector(ndpi_str, &a, detection_bitmask);
/* ARMAGETRON */
init_armagetron_dissector(ndpi_str, &a, detection_bitmask);
/* DROPBOX */
init_dropbox_dissector(ndpi_str, &a, detection_bitmask);
/* SPOTIFY */
init_spotify_dissector(ndpi_str, &a, detection_bitmask);
/* RADIUS */
init_radius_dissector(ndpi_str, &a, detection_bitmask);
/* CITRIX */
init_citrix_dissector(ndpi_str, &a, detection_bitmask);
/* LOTUS_NOTES */
init_lotus_notes_dissector(ndpi_str, &a, detection_bitmask);
/* GTP */
init_gtp_dissector(ndpi_str, &a, detection_bitmask);
/* DCERPC */
init_dcerpc_dissector(ndpi_str, &a, detection_bitmask);
/* NETFLOW */
init_netflow_dissector(ndpi_str, &a, detection_bitmask);
/* SFLOW */
init_sflow_dissector(ndpi_str, &a, detection_bitmask);
/* H323 */
init_h323_dissector(ndpi_str, &a, detection_bitmask);
/* OPENVPN */
init_openvpn_dissector(ndpi_str, &a, detection_bitmask);
/* NOE */
init_noe_dissector(ndpi_str, &a, detection_bitmask);
/* CISCOVPN */
init_ciscovpn_dissector(ndpi_str, &a, detection_bitmask);
/* TEAMSPEAK */
init_teamspeak_dissector(ndpi_str, &a, detection_bitmask);
/* TOR */
init_tor_dissector(ndpi_str, &a, detection_bitmask);
/* SKINNY */
init_skinny_dissector(ndpi_str, &a, detection_bitmask);
/* RTCP */
init_rtcp_dissector(ndpi_str, &a, detection_bitmask);
/* RSYNC */
init_rsync_dissector(ndpi_str, &a, detection_bitmask);
/* WHOIS_DAS */
init_whois_das_dissector(ndpi_str, &a, detection_bitmask);
/* ORACLE */
init_oracle_dissector(ndpi_str, &a, detection_bitmask);
/* CORBA */
init_corba_dissector(ndpi_str, &a, detection_bitmask);
/* RTMP */
init_rtmp_dissector(ndpi_str, &a, detection_bitmask);
/* FTP_CONTROL */
init_ftp_control_dissector(ndpi_str, &a, detection_bitmask);
/* FTP_DATA */
init_ftp_data_dissector(ndpi_str, &a, detection_bitmask);
/* PANDO */
init_pando_dissector(ndpi_str, &a, detection_bitmask);
/* MEGACO */
init_megaco_dissector(ndpi_str, &a, detection_bitmask);
/* REDIS */
init_redis_dissector(ndpi_str, &a, detection_bitmask);
/* UPnP */
init_upnp_dissector(ndpi_str, &a, detection_bitmask);
/* VHUA */
init_vhua_dissector(ndpi_str, &a, detection_bitmask);
/* ZMQ */
init_zmq_dissector(ndpi_str, &a, detection_bitmask);
/* TELEGRAM */
init_telegram_dissector(ndpi_str, &a, detection_bitmask);
/* QUIC */
init_quic_dissector(ndpi_str, &a, detection_bitmask);
/* DIAMETER */
init_diameter_dissector(ndpi_str, &a, detection_bitmask);
/* APPLE_PUSH */
init_apple_push_dissector(ndpi_str, &a, detection_bitmask);
/* EAQ */
init_eaq_dissector(ndpi_str, &a, detection_bitmask);
/* KAKAOTALK_VOICE */
init_kakaotalk_voice_dissector(ndpi_str, &a, detection_bitmask);
/* MPEGTS */
init_mpegts_dissector(ndpi_str, &a, detection_bitmask);
/* UBNTAC2 */
init_ubntac2_dissector(ndpi_str, &a, detection_bitmask);
/* COAP */
init_coap_dissector(ndpi_str, &a, detection_bitmask);
/* MQTT */
init_mqtt_dissector(ndpi_str, &a, detection_bitmask);
/* SOME/IP */
init_someip_dissector(ndpi_str, &a, detection_bitmask);
/* RX */
init_rx_dissector(ndpi_str, &a, detection_bitmask);
/* GIT */
init_git_dissector(ndpi_str, &a, detection_bitmask);
/* HANGOUT */
init_hangout_dissector(ndpi_str, &a, detection_bitmask);
/* DRDA */
init_drda_dissector(ndpi_str, &a, detection_bitmask);
/* BJNP */
init_bjnp_dissector(ndpi_str, &a, detection_bitmask);
/* SMPP */
init_smpp_dissector(ndpi_str, &a, detection_bitmask);
/* TINC */
init_tinc_dissector(ndpi_str, &a, detection_bitmask);
/* FIX */
init_fix_dissector(ndpi_str, &a, detection_bitmask);
/* NINTENDO */
init_nintendo_dissector(ndpi_str, &a, detection_bitmask);
/* MODBUS */
init_modbus_dissector(ndpi_str, &a, detection_bitmask);
/* CAPWAP */
init_capwap_dissector(ndpi_str, &a, detection_bitmask);
/* ZABBIX */
init_zabbix_dissector(ndpi_str, &a, detection_bitmask);
/*** Put false-positive sensitive protocols at the end ***/
/* VIBER */
init_viber_dissector(ndpi_str, &a, detection_bitmask);
/* SKYPE */
init_skype_dissector(ndpi_str, &a, detection_bitmask);
/* BITTORRENT */
init_bittorrent_dissector(ndpi_str, &a, detection_bitmask);
/* WHATSAPP */
init_whatsapp_dissector(ndpi_str, &a, detection_bitmask);
/* OOKLA */
init_ookla_dissector(ndpi_str, &a, detection_bitmask);
/* AMQP */
init_amqp_dissector(ndpi_str, &a, detection_bitmask);
/* CSGO */
init_csgo_dissector(ndpi_str, &a, detection_bitmask);
/* LISP */
init_lisp_dissector(ndpi_str, &a, detection_bitmask);
/* AJP */
init_ajp_dissector(ndpi_str, &a, detection_bitmask);
/* Memcached */
init_memcached_dissector(ndpi_str, &a, detection_bitmask);
/* Nest Log Sink */
init_nest_log_sink_dissector(ndpi_str, &a, detection_bitmask);
/* WireGuard VPN */
init_wireguard_dissector(ndpi_str, &a, detection_bitmask);
/* Amazon_Video */
init_amazon_video_dissector(ndpi_str, &a, detection_bitmask);
/* Targus Getdata */
init_targus_getdata_dissector(ndpi_str, &a, detection_bitmask);
/* S7 comm */
init_s7comm_dissector(ndpi_str, &a, detection_bitmask);
/* IEC 60870-5-104 */
init_104_dissector(ndpi_str, &a, detection_bitmask);
/* WEBSOCKET */
init_websocket_dissector(ndpi_str, &a, detection_bitmask);
#ifdef CUSTOM_NDPI_PROTOCOLS
#include "../../../nDPI-custom/custom_ndpi_main_init.c"
#endif
/* ----------------------------------------------------------------- */
ndpi_str->callback_buffer_size = a;
NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size is %u\n", ndpi_str->callback_buffer_size);
/* now build the specific buffer for tcp, udp and non_tcp_udp */
ndpi_str->callback_buffer_size_tcp_payload = 0;
ndpi_str->callback_buffer_size_tcp_no_payload = 0;
for (a = 0; a < ndpi_str->callback_buffer_size; a++) {
if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask &
(NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP |
NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) {
if(_ndpi_debug_callbacks)
NDPI_LOG_DBG2(ndpi_str, "callback_buffer_tcp_payload, adding buffer %u as entry %u\n", a,
ndpi_str->callback_buffer_size_tcp_payload);
memcpy(&ndpi_str->callback_buffer_tcp_payload[ndpi_str->callback_buffer_size_tcp_payload],
&ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct));
ndpi_str->callback_buffer_size_tcp_payload++;
if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) ==
0) {
if(_ndpi_debug_callbacks)
NDPI_LOG_DBG2(
ndpi_str,
"\tcallback_buffer_tcp_no_payload, additional adding buffer %u to no_payload process\n", a);
memcpy(&ndpi_str->callback_buffer_tcp_no_payload[ndpi_str->callback_buffer_size_tcp_no_payload],
&ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct));
ndpi_str->callback_buffer_size_tcp_no_payload++;
}
}
}
ndpi_str->callback_buffer_size_udp = 0;
for (a = 0; a < ndpi_str->callback_buffer_size; a++) {
if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask &
(NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP |
NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC)) != 0) {
if(_ndpi_debug_callbacks)
NDPI_LOG_DBG2(ndpi_str, "callback_buffer_size_udp: adding buffer : %u as entry %u\n", a,
ndpi_str->callback_buffer_size_udp);
memcpy(&ndpi_str->callback_buffer_udp[ndpi_str->callback_buffer_size_udp], &ndpi_str->callback_buffer[a],
sizeof(struct ndpi_call_function_struct));
ndpi_str->callback_buffer_size_udp++;
}
}
ndpi_str->callback_buffer_size_non_tcp_udp = 0;
for (a = 0; a < ndpi_str->callback_buffer_size; a++) {
if((ndpi_str->callback_buffer[a].ndpi_selection_bitmask &
(NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP |
NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP)) == 0 ||
(ndpi_str->callback_buffer[a].ndpi_selection_bitmask & NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC) !=
0) {
if(_ndpi_debug_callbacks)
NDPI_LOG_DBG2(ndpi_str, "callback_buffer_non_tcp_udp: adding buffer : %u as entry %u\n", a,
ndpi_str->callback_buffer_size_non_tcp_udp);
memcpy(&ndpi_str->callback_buffer_non_tcp_udp[ndpi_str->callback_buffer_size_non_tcp_udp],
&ndpi_str->callback_buffer[a], sizeof(struct ndpi_call_function_struct));
ndpi_str->callback_buffer_size_non_tcp_udp++;
}
}
}
#ifdef NDPI_DETECTION_SUPPORT_IPV6
/* handle extension headers in IPv6 packets
* arguments:
* l4ptr: pointer to the byte following the initial IPv6 header
* l4len: the length of the IPv6 packet excluding the IPv6 header
* nxt_hdr: next header value from the IPv6 header
* result:
* l4ptr: pointer to the start of the actual packet payload
* l4len: length of the actual payload
* nxt_hdr: protocol of the actual payload
* returns 0 upon success and 1 upon failure
*/
int ndpi_handle_ipv6_extension_headers(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t **l4ptr,
u_int16_t *l4len, u_int8_t *nxt_hdr) {
while ((*nxt_hdr == 0 || *nxt_hdr == 43 || *nxt_hdr == 44 || *nxt_hdr == 60 || *nxt_hdr == 135 || *nxt_hdr == 59)) {
u_int16_t ehdr_len;
// no next header
if(*nxt_hdr == 59) {
return(1);
}
// fragment extension header has fixed size of 8 bytes and the first byte is the next header type
if(*nxt_hdr == 44) {
if(*l4len < 8) {
return(1);
}
*nxt_hdr = (*l4ptr)[0];
*l4len -= 8;
(*l4ptr) += 8;
continue;
}
// the other extension headers have one byte for the next header type
// and one byte for the extension header length in 8 byte steps minus the first 8 bytes
if(*l4len < 2) {
return(1);
}
ehdr_len = (*l4ptr)[1];
ehdr_len *= 8;
ehdr_len += 8;
if(*l4len < ehdr_len) {
return(1);
}
*nxt_hdr = (*l4ptr)[0];
*l4len -= ehdr_len;
(*l4ptr) += ehdr_len;
}
return(0);
}
#endif /* NDPI_DETECTION_SUPPORT_IPV6 */
static u_int8_t ndpi_iph_is_valid_and_not_fragmented(const struct ndpi_iphdr *iph, const u_int16_t ipsize) {
//#ifdef REQUIRE_FULL_PACKETS
if(ipsize < iph->ihl * 4 || ipsize < ntohs(iph->tot_len) || ntohs(iph->tot_len) < iph->ihl * 4 ||
(iph->frag_off & htons(0x1FFF)) != 0) {
return(0);
}
//#endif
return(1);
}
static u_int8_t ndpi_detection_get_l4_internal(struct ndpi_detection_module_struct *ndpi_str, const u_int8_t *l3,
u_int16_t l3_len, const u_int8_t **l4_return, u_int16_t *l4_len_return,
u_int8_t *l4_protocol_return, u_int32_t flags) {
const struct ndpi_iphdr *iph = NULL;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
const struct ndpi_ipv6hdr *iph_v6 = NULL;
#endif
u_int16_t l4len = 0;
const u_int8_t *l4ptr = NULL;
u_int8_t l4protocol = 0;
if(l3 == NULL || l3_len < sizeof(struct ndpi_iphdr))
return(1);
if((iph = (const struct ndpi_iphdr *) l3) == NULL)
return(1);
if(iph->version == IPVERSION && iph->ihl >= 5) {
NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n");
}
#ifdef NDPI_DETECTION_SUPPORT_IPV6
else if(iph->version == 6 && l3_len >= sizeof(struct ndpi_ipv6hdr)) {
NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n");
iph_v6 = (const struct ndpi_ipv6hdr *) l3;
iph = NULL;
}
#endif
else {
return(1);
}
if((flags & NDPI_DETECTION_ONLY_IPV6) && iph != NULL) {
NDPI_LOG_DBG2(ndpi_str, "ipv4 header found but excluded by flag\n");
return(1);
}
#ifdef NDPI_DETECTION_SUPPORT_IPV6
else if((flags & NDPI_DETECTION_ONLY_IPV4) && iph_v6 != NULL) {
NDPI_LOG_DBG2(ndpi_str, "ipv6 header found but excluded by flag\n");
return(1);
}
#endif
if(iph != NULL && ndpi_iph_is_valid_and_not_fragmented(iph, l3_len)) {
u_int16_t len = ntohs(iph->tot_len);
u_int16_t hlen = (iph->ihl * 4);
l4ptr = (((const u_int8_t *) iph) + iph->ihl * 4);
if(len == 0)
len = l3_len;
l4len = (len > hlen) ? (len - hlen) : 0;
l4protocol = iph->protocol;
}
#ifdef NDPI_DETECTION_SUPPORT_IPV6
else if(iph_v6 != NULL && (l3_len - sizeof(struct ndpi_ipv6hdr)) >= ntohs(iph_v6->ip6_hdr.ip6_un1_plen)) {
l4ptr = (((const u_int8_t *) iph_v6) + sizeof(struct ndpi_ipv6hdr));
l4len = ntohs(iph_v6->ip6_hdr.ip6_un1_plen);
l4protocol = iph_v6->ip6_hdr.ip6_un1_nxt;
// we need to handle IPv6 extension headers if present
if(ndpi_handle_ipv6_extension_headers(ndpi_str, &l4ptr, &l4len, &l4protocol) != 0) {
return(1);
}
}
#endif
else {
return(1);
}
if(l4_return != NULL) {
*l4_return = l4ptr;
}
if(l4_len_return != NULL) {
*l4_len_return = l4len;
}
if(l4_protocol_return != NULL) {
*l4_protocol_return = l4protocol;
}
return(0);
}
/* ************************************************ */
void ndpi_apply_flow_protocol_to_packet(struct ndpi_flow_struct *flow, struct ndpi_packet_struct *packet) {
memcpy(&packet->detected_protocol_stack, &flow->detected_protocol_stack, sizeof(packet->detected_protocol_stack));
memcpy(&packet->protocol_stack_info, &flow->protocol_stack_info, sizeof(packet->protocol_stack_info));
}
/* ************************************************ */
static int ndpi_init_packet_header(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow,
unsigned short packetlen) {
const struct ndpi_iphdr *decaps_iph = NULL;
u_int16_t l3len;
u_int16_t l4len;
const u_int8_t *l4ptr;
u_int8_t l4protocol;
u_int8_t l4_result;
if(!flow)
return(1);
/* reset payload_packet_len, will be set if ipv4 tcp or udp */
flow->packet.payload_packet_len = 0;
flow->packet.l4_packet_len = 0;
flow->packet.l3_packet_len = packetlen;
flow->packet.tcp = NULL, flow->packet.udp = NULL;
flow->packet.generic_l4_ptr = NULL;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
flow->packet.iphv6 = NULL;
#endif /* NDPI_DETECTION_SUPPORT_IPV6 */
ndpi_apply_flow_protocol_to_packet(flow, &flow->packet);
l3len = flow->packet.l3_packet_len;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(flow->packet.iph != NULL) {
#endif /* NDPI_DETECTION_SUPPORT_IPV6 */
decaps_iph = flow->packet.iph;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
}
#endif /* NDPI_DETECTION_SUPPORT_IPV6 */
if(decaps_iph && decaps_iph->version == IPVERSION && decaps_iph->ihl >= 5) {
NDPI_LOG_DBG2(ndpi_str, "ipv4 header\n");
}
#ifdef NDPI_DETECTION_SUPPORT_IPV6
else if(decaps_iph && decaps_iph->version == 6 && l3len >= sizeof(struct ndpi_ipv6hdr) &&
(ndpi_str->ip_version_limit & NDPI_DETECTION_ONLY_IPV4) == 0) {
NDPI_LOG_DBG2(ndpi_str, "ipv6 header\n");
flow->packet.iphv6 = (struct ndpi_ipv6hdr *) flow->packet.iph;
flow->packet.iph = NULL;
}
#endif
else {
flow->packet.iph = NULL;
return(1);
}
/* needed:
* - unfragmented packets
* - ip header <= packet len
* - ip total length >= packet len
*/
l4ptr = NULL;
l4len = 0;
l4protocol = 0;
l4_result =
ndpi_detection_get_l4_internal(ndpi_str, (const u_int8_t *) decaps_iph, l3len, &l4ptr, &l4len, &l4protocol, 0);
if(l4_result != 0) {
return(1);
}
flow->packet.l4_protocol = l4protocol;
flow->packet.l4_packet_len = l4len;
flow->l4_proto = l4protocol;
/* tcp / udp detection */
if(l4protocol == IPPROTO_TCP && flow->packet.l4_packet_len >= 20 /* min size of tcp */) {
/* tcp */
flow->packet.tcp = (struct ndpi_tcphdr *) l4ptr;
if(flow->packet.l4_packet_len >= flow->packet.tcp->doff * 4) {
flow->packet.payload_packet_len = flow->packet.l4_packet_len - flow->packet.tcp->doff * 4;
flow->packet.actual_payload_len = flow->packet.payload_packet_len;
flow->packet.payload = ((u_int8_t *) flow->packet.tcp) + (flow->packet.tcp->doff * 4);
/* check for new tcp syn packets, here
* idea: reset detection state if a connection is unknown
*/
if(flow->packet.tcp->syn != 0 && flow->packet.tcp->ack == 0 && flow->init_finished != 0 &&
flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) {
u_int8_t backup;
u_int16_t backup1, backup2;
if(flow->http.url) {
ndpi_free(flow->http.url);
flow->http.url = NULL;
}
if(flow->http.content_type) {
ndpi_free(flow->http.content_type);
flow->http.content_type = NULL;
}
if(flow->http.user_agent) {
ndpi_free(flow->http.user_agent);
flow->http.user_agent = NULL;
}
if(flow->kerberos_buf.pktbuf) {
ndpi_free(flow->kerberos_buf.pktbuf);
flow->kerberos_buf.pktbuf = NULL;
}
if(flow->l4.tcp.tls.message.buffer) {
ndpi_free(flow->l4.tcp.tls.message.buffer);
flow->l4.tcp.tls.message.buffer = NULL;
flow->l4.tcp.tls.message.buffer_len = flow->l4.tcp.tls.message.buffer_used = 0;
}
backup = flow->num_processed_pkts;
backup1 = flow->guessed_protocol_id;
backup2 = flow->guessed_host_protocol_id;
memset(flow, 0, sizeof(*(flow)));
flow->num_processed_pkts = backup;
flow->guessed_protocol_id = backup1;
flow->guessed_host_protocol_id = backup2;
NDPI_LOG_DBG(ndpi_str, "tcp syn packet for unknown protocol, reset detection state\n");
}
} else {
/* tcp header not complete */
flow->packet.tcp = NULL;
}
} else if(l4protocol == IPPROTO_UDP && flow->packet.l4_packet_len >= 8 /* size of udp */) {
flow->packet.udp = (struct ndpi_udphdr *) l4ptr;
flow->packet.payload_packet_len = flow->packet.l4_packet_len - 8;
flow->packet.payload = ((u_int8_t *) flow->packet.udp) + 8;
} else {
flow->packet.generic_l4_ptr = l4ptr;
}
return(0);
}
/* ************************************************ */
void ndpi_connection_tracking(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow) {
if(!flow) {
return;
} else {
/* const for gcc code optimization and cleaner code */
struct ndpi_packet_struct *packet = &flow->packet;
const struct ndpi_iphdr *iph = packet->iph;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
const struct ndpi_ipv6hdr *iphv6 = packet->iphv6;
#endif
const struct ndpi_tcphdr *tcph = packet->tcp;
const struct ndpi_udphdr *udph = flow->packet.udp;
packet->tcp_retransmission = 0, packet->packet_direction = 0;
if(ndpi_str->direction_detect_disable) {
packet->packet_direction = flow->packet_direction;
} else {
if(iph != NULL && ntohl(iph->saddr) < ntohl(iph->daddr))
packet->packet_direction = 1;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(iphv6 != NULL && NDPI_COMPARE_IPV6_ADDRESS_STRUCTS(&iphv6->ip6_src, &iphv6->ip6_dst) != 0)
packet->packet_direction = 1;
#endif
}
packet->packet_lines_parsed_complete = 0;
if(flow->init_finished == 0) {
flow->init_finished = 1;
flow->setup_packet_direction = packet->packet_direction;
}
if(tcph != NULL) {
/* reset retried bytes here before setting it */
packet->num_retried_bytes = 0;
if(!ndpi_str->direction_detect_disable)
packet->packet_direction = (ntohs(tcph->source) < ntohs(tcph->dest)) ? 1 : 0;
if(tcph->syn != 0 && tcph->ack == 0 && flow->l4.tcp.seen_syn == 0 && flow->l4.tcp.seen_syn_ack == 0 &&
flow->l4.tcp.seen_ack == 0) {
flow->l4.tcp.seen_syn = 1;
}
if(tcph->syn != 0 && tcph->ack != 0 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 0 &&
flow->l4.tcp.seen_ack == 0) {
flow->l4.tcp.seen_syn_ack = 1;
}
if(tcph->syn == 0 && tcph->ack == 1 && flow->l4.tcp.seen_syn == 1 && flow->l4.tcp.seen_syn_ack == 1 &&
flow->l4.tcp.seen_ack == 0) {
flow->l4.tcp.seen_ack = 1;
}
if((flow->next_tcp_seq_nr[0] == 0 && flow->next_tcp_seq_nr[1] == 0) ||
(flow->next_tcp_seq_nr[0] == 0 || flow->next_tcp_seq_nr[1] == 0)) {
/* initialize tcp sequence counters */
/* the ack flag needs to be set to get valid sequence numbers from the other
* direction. Usually it will catch the second packet syn+ack but it works
* also for asymmetric traffic where it will use the first data packet
*
* if the syn flag is set add one to the sequence number,
* otherwise use the payload length.
*/
if(tcph->ack != 0) {
flow->next_tcp_seq_nr[flow->packet.packet_direction] =
ntohl(tcph->seq) + (tcph->syn ? 1 : packet->payload_packet_len);
flow->next_tcp_seq_nr[1 - flow->packet.packet_direction] = ntohl(tcph->ack_seq);
}
} else if(packet->payload_packet_len > 0) {
/* check tcp sequence counters */
if(((u_int32_t)(ntohl(tcph->seq) - flow->next_tcp_seq_nr[packet->packet_direction])) >
ndpi_str->tcp_max_retransmission_window_size) {
packet->tcp_retransmission = 1;
/* CHECK IF PARTIAL RETRY IS HAPPENING */
if((flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq) <
packet->payload_packet_len)) {
/* num_retried_bytes actual_payload_len hold info about the partial retry
analyzer which require this info can make use of this info
Other analyzer can use packet->payload_packet_len */
packet->num_retried_bytes =
(u_int16_t)(flow->next_tcp_seq_nr[packet->packet_direction] - ntohl(tcph->seq));
packet->actual_payload_len = packet->payload_packet_len - packet->num_retried_bytes;
flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len;
}
}
/* normal path
actual_payload_len is initialized to payload_packet_len during tcp header parsing itself.
It will be changed only in case of retransmission */
else {
packet->num_retried_bytes = 0;
flow->next_tcp_seq_nr[packet->packet_direction] = ntohl(tcph->seq) + packet->payload_packet_len;
}
}
if(tcph->rst) {
flow->next_tcp_seq_nr[0] = 0;
flow->next_tcp_seq_nr[1] = 0;
}
} else if(udph != NULL) {
if(!ndpi_str->direction_detect_disable)
packet->packet_direction = (htons(udph->source) < htons(udph->dest)) ? 1 : 0;
}
if(flow->packet_counter < MAX_PACKET_COUNTER && packet->payload_packet_len) {
flow->packet_counter++;
}
if(flow->packet_direction_counter[packet->packet_direction] < MAX_PACKET_COUNTER &&
packet->payload_packet_len) {
flow->packet_direction_counter[packet->packet_direction]++;
}
if(flow->byte_counter[packet->packet_direction] + packet->payload_packet_len >
flow->byte_counter[packet->packet_direction]) {
flow->byte_counter[packet->packet_direction] += packet->payload_packet_len;
}
}
}
/* ************************************************ */
void check_ndpi_other_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) {
if(!flow)
return;
void *func = NULL;
u_int32_t a;
u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx;
int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId;
NDPI_PROTOCOL_BITMASK detection_bitmask;
NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]);
if((proto_id != NDPI_PROTOCOL_UNKNOWN) &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 &&
(ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) {
if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL))
ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow),
func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func;
}
for (a = 0; a < ndpi_str->callback_buffer_size_non_tcp_udp; a++) {
if((func != ndpi_str->callback_buffer_non_tcp_udp[a].func) &&
(ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer_non_tcp_udp[a].ndpi_selection_bitmask &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer_non_tcp_udp[a].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_non_tcp_udp[a].detection_bitmask, detection_bitmask) != 0) {
if(ndpi_str->callback_buffer_non_tcp_udp[a].func != NULL)
ndpi_str->callback_buffer_non_tcp_udp[a].func(ndpi_str, flow);
if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN)
break; /* Stop after detecting the first protocol */
}
}
}
/* ************************************************ */
void check_ndpi_udp_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) {
void *func = NULL;
u_int32_t a;
u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx;
int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId;
NDPI_PROTOCOL_BITMASK detection_bitmask;
NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]);
if((proto_id != NDPI_PROTOCOL_UNKNOWN) &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 &&
(ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) {
if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL))
ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow),
func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func;
}
if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) {
for (a = 0; a < ndpi_str->callback_buffer_size_udp; a++) {
if((func != ndpi_str->callback_buffer_udp[a].func) &&
(ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer_udp[a].ndpi_selection_bitmask &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer_udp[a].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_udp[a].detection_bitmask, detection_bitmask) != 0) {
ndpi_str->callback_buffer_udp[a].func(ndpi_str, flow);
// NDPI_LOG_DBG(ndpi_str, "[UDP,CALL] dissector of protocol as callback_buffer idx = %d\n",a);
if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN)
break; /* Stop after detecting the first protocol */
} else if(_ndpi_debug_callbacks)
NDPI_LOG_DBG2(ndpi_str, "[UDP,SKIP] dissector of protocol as callback_buffer idx = %d\n", a);
}
}
}
/* ************************************************ */
void check_ndpi_tcp_flow_func(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow,
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) {
void *func = NULL;
u_int32_t a;
u_int16_t proto_index = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoIdx;
int16_t proto_id = ndpi_str->proto_defaults[flow->guessed_protocol_id].protoId;
NDPI_PROTOCOL_BITMASK detection_bitmask;
NDPI_SAVE_AS_BITMASK(detection_bitmask, flow->packet.detected_protocol_stack[0]);
if(flow->packet.payload_packet_len != 0) {
if((proto_id != NDPI_PROTOCOL_UNKNOWN) &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 &&
(ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) {
if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL))
ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow),
func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func;
}
if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) {
for (a = 0; a < ndpi_str->callback_buffer_size_tcp_payload; a++) {
if((func != ndpi_str->callback_buffer_tcp_payload[a].func) &&
(ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer_tcp_payload[a].ndpi_selection_bitmask &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer_tcp_payload[a].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_payload[a].detection_bitmask,
detection_bitmask) != 0) {
ndpi_str->callback_buffer_tcp_payload[a].func(ndpi_str, flow);
if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN)
break; /* Stop after detecting the first protocol */
}
}
}
} else {
/* no payload */
if((proto_id != NDPI_PROTOCOL_UNKNOWN) &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer[proto_index].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer[proto_index].detection_bitmask, detection_bitmask) != 0 &&
(ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer[proto_index].ndpi_selection_bitmask) {
if((flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(ndpi_str->proto_defaults[flow->guessed_protocol_id].func != NULL) &&
((ndpi_str->callback_buffer[flow->guessed_protocol_id].ndpi_selection_bitmask &
NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD) == 0))
ndpi_str->proto_defaults[flow->guessed_protocol_id].func(ndpi_str, flow),
func = ndpi_str->proto_defaults[flow->guessed_protocol_id].func;
}
for (a = 0; a < ndpi_str->callback_buffer_size_tcp_no_payload; a++) {
if((func != ndpi_str->callback_buffer_tcp_payload[a].func) &&
(ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask & *ndpi_selection_packet) ==
ndpi_str->callback_buffer_tcp_no_payload[a].ndpi_selection_bitmask &&
NDPI_BITMASK_COMPARE(flow->excluded_protocol_bitmask,
ndpi_str->callback_buffer_tcp_no_payload[a].excluded_protocol_bitmask) == 0 &&
NDPI_BITMASK_COMPARE(ndpi_str->callback_buffer_tcp_no_payload[a].detection_bitmask,
detection_bitmask) != 0) {
ndpi_str->callback_buffer_tcp_no_payload[a].func(ndpi_str, flow);
if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN)
break; /* Stop after detecting the first protocol */
}
}
}
}
/* ********************************************************************************* */
void ndpi_check_flow_func(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE *ndpi_selection_packet) {
if(flow->packet.tcp != NULL)
check_ndpi_tcp_flow_func(ndpi_str, flow, ndpi_selection_packet);
else if(flow->packet.udp != NULL)
check_ndpi_udp_flow_func(ndpi_str, flow, ndpi_selection_packet);
else
check_ndpi_other_flow_func(ndpi_str, flow, ndpi_selection_packet);
}
/* ********************************************************************************* */
u_int16_t ndpi_guess_host_protocol_id(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow) {
u_int16_t ret = NDPI_PROTOCOL_UNKNOWN;
if(flow->packet.iph) {
struct in_addr addr;
u_int16_t sport, dport;
addr.s_addr = flow->packet.iph->saddr;
if((flow->l4_proto == IPPROTO_TCP) && flow->packet.tcp)
sport = flow->packet.tcp->source, dport = flow->packet.tcp->dest;
else if((flow->l4_proto == IPPROTO_UDP) && flow->packet.udp)
sport = flow->packet.udp->source, dport = flow->packet.udp->dest;
else
sport = dport = 0;
/* guess host protocol */
ret = ndpi_network_port_ptree_match(ndpi_str, &addr, sport);
if(ret == NDPI_PROTOCOL_UNKNOWN) {
addr.s_addr = flow->packet.iph->daddr;
ret = ndpi_network_port_ptree_match(ndpi_str, &addr, dport);
}
}
return(ret);
}
/* ********************************************************************************* */
ndpi_protocol ndpi_detection_giveup(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int8_t enable_guess, u_int8_t *protocol_was_guessed) {
ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED};
*protocol_was_guessed = 0;
if(flow == NULL)
return(ret);
/* Init defaults */
ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0];
ret.category = flow->category;
/* Ensure that we don't change our mind if detection is already complete */
if((ret.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN))
return(ret);
/* TODO: add the remaining stage_XXXX protocols */
if(flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) {
u_int16_t guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN, guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN;
if(flow->guessed_protocol_id == NDPI_PROTOCOL_STUN)
goto check_stun_export;
else if((flow->guessed_protocol_id == NDPI_PROTOCOL_HANGOUT_DUO) ||
(flow->guessed_protocol_id == NDPI_PROTOCOL_MESSENGER) ||
(flow->guessed_protocol_id == NDPI_PROTOCOL_WHATSAPP_CALL)) {
*protocol_was_guessed = 1;
ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_protocol_id, NDPI_PROTOCOL_UNKNOWN);
}
else if((flow->l4.tcp.tls.hello_processed == 1) &&
(flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0')) {
*protocol_was_guessed = 1;
ndpi_set_detected_protocol(ndpi_str, flow, NDPI_PROTOCOL_TLS, NDPI_PROTOCOL_UNKNOWN);
} else if(enable_guess) {
if((flow->guessed_protocol_id == NDPI_PROTOCOL_UNKNOWN) && (flow->packet.l4_protocol == IPPROTO_TCP) &&
flow->l4.tcp.tls.hello_processed)
flow->guessed_protocol_id = NDPI_PROTOCOL_TLS;
guessed_protocol_id = flow->guessed_protocol_id, guessed_host_protocol_id = flow->guessed_host_protocol_id;
if((guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
((flow->packet.l4_protocol == IPPROTO_UDP) &&
NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_host_protocol_id) &&
is_udp_guessable_protocol(guessed_host_protocol_id)))
flow->guessed_host_protocol_id = guessed_host_protocol_id = NDPI_PROTOCOL_UNKNOWN;
/* Ignore guessed protocol if they have been discarded */
if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN)
// && (guessed_host_protocol_id == NDPI_PROTOCOL_UNKNOWN)
&& (flow->packet.l4_protocol == IPPROTO_UDP) &&
NDPI_ISSET(&flow->excluded_protocol_bitmask, guessed_protocol_id) &&
is_udp_guessable_protocol(guessed_protocol_id))
flow->guessed_protocol_id = guessed_protocol_id = NDPI_PROTOCOL_UNKNOWN;
if((guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) || (guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) {
if((guessed_protocol_id == 0) && (flow->protos.stun_ssl.stun.num_binding_requests > 0) &&
(flow->protos.stun_ssl.stun.num_processed_pkts > 0))
guessed_protocol_id = NDPI_PROTOCOL_STUN;
if(flow->host_server_name[0] != '\0') {
ndpi_protocol_match_result ret_match;
memset(&ret_match, 0, sizeof(ret_match));
ndpi_match_host_subprotocol(ndpi_str, flow, (char *) flow->host_server_name,
strlen((const char *) flow->host_server_name), &ret_match,
NDPI_PROTOCOL_DNS);
if(ret_match.protocol_id != NDPI_PROTOCOL_UNKNOWN)
guessed_host_protocol_id = ret_match.protocol_id;
}
*protocol_was_guessed = 1;
ndpi_int_change_protocol(ndpi_str, flow, guessed_host_protocol_id, guessed_protocol_id);
}
}
} else if(enable_guess) {
if(flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) {
*protocol_was_guessed = 1;
flow->detected_protocol_stack[1] = flow->guessed_protocol_id;
}
if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) {
*protocol_was_guessed = 1;
flow->detected_protocol_stack[0] = flow->guessed_host_protocol_id;
}
if(flow->detected_protocol_stack[1] == flow->detected_protocol_stack[0]) {
*protocol_was_guessed = 1;
flow->detected_protocol_stack[1] = flow->guessed_host_protocol_id;
}
}
if((flow->detected_protocol_stack[0] == NDPI_PROTOCOL_UNKNOWN) &&
(flow->guessed_protocol_id == NDPI_PROTOCOL_STUN)) {
check_stun_export:
if(flow->protos.stun_ssl.stun.num_processed_pkts || flow->protos.stun_ssl.stun.num_udp_pkts) {
// if(/* (flow->protos.stun_ssl.stun.num_processed_pkts >= NDPI_MIN_NUM_STUN_DETECTION) */
*protocol_was_guessed = 1;
ndpi_set_detected_protocol(ndpi_str, flow, flow->guessed_host_protocol_id, NDPI_PROTOCOL_STUN);
}
}
ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0];
if(ret.master_protocol == NDPI_PROTOCOL_STUN) {
if(ret.app_protocol == NDPI_PROTOCOL_FACEBOOK)
ret.app_protocol = NDPI_PROTOCOL_MESSENGER;
else if(ret.app_protocol == NDPI_PROTOCOL_GOOGLE) {
/*
As Google has recently introduced Duo,
we need to distinguish between it and hangout
thing that should be handled by the STUN dissector
*/
ret.app_protocol = NDPI_PROTOCOL_HANGOUT_DUO;
}
}
if(ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) {
*protocol_was_guessed = 1;
ndpi_fill_protocol_category(ndpi_str, flow, &ret);
}
return(ret);
}
/* ********************************************************************************* */
void ndpi_process_extra_packet(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
const unsigned char *packet, const unsigned short packetlen,
const u_int64_t current_tick_l, struct ndpi_id_struct *src, struct ndpi_id_struct *dst) {
if(flow == NULL)
return;
if(flow->server_id == NULL)
flow->server_id = dst; /* Default */
/* need at least 20 bytes for ip header */
if(packetlen < 20) {
return;
}
flow->packet.tick_timestamp_l = current_tick_l;
flow->packet.tick_timestamp = (u_int32_t)(current_tick_l / ndpi_str->ticks_per_second);
/* parse packet */
flow->packet.iph = (struct ndpi_iphdr *) packet;
/* we are interested in ipv4 packet */
/* set up the packet headers for the extra packet function to use if it wants */
if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0)
return;
/* detect traffic for tcp or udp only */
flow->src = src, flow->dst = dst;
ndpi_connection_tracking(ndpi_str, flow);
/* call the extra packet function (which may add more data/info to flow) */
if(flow->extra_packets_func) {
if((flow->extra_packets_func(ndpi_str, flow)) == 0)
flow->check_extra_packets = 0;
if(++flow->num_extra_packets_checked == flow->max_extra_packets_to_check)
flow->extra_packets_func = NULL; /* Enough packets detected */
}
}
/* ********************************************************************************* */
int ndpi_load_ip_category(struct ndpi_detection_module_struct *ndpi_str, const char *ip_address_and_mask,
ndpi_protocol_category_t category) {
patricia_node_t *node;
struct in_addr pin;
int bits = 32;
char *ptr;
char ipbuf[64];
strncpy(ipbuf, ip_address_and_mask, sizeof(ipbuf));
ipbuf[sizeof(ipbuf) - 1] = '\0';
ptr = strrchr(ipbuf, '/');
if(ptr) {
*(ptr++) = '\0';
if(atoi(ptr) >= 0 && atoi(ptr) <= 32)
bits = atoi(ptr);
}
if(inet_pton(AF_INET, ipbuf, &pin) != 1) {
NDPI_LOG_DBG2(ndpi_str, "Invalid ip/ip+netmask: %s\n", ip_address_and_mask);
return(-1);
}
if((node = add_to_ptree(ndpi_str->custom_categories.ipAddresses_shadow, AF_INET, &pin, bits)) != NULL) {
node->value.uv.user_value = (u_int16_t)category, node->value.uv.additional_user_value = 0;
}
return(0);
}
/* ********************************************************************************* */
int ndpi_load_hostname_category(struct ndpi_detection_module_struct *ndpi_str, const char *name_to_add,
ndpi_protocol_category_t category) {
char *name;
if(name_to_add == NULL)
return(-1);
name = ndpi_strdup(name_to_add);
if(name == NULL)
return(-1);
#if 0
printf("===> %s() Loading %s as %u\n", __FUNCTION__, name, category);
#endif
AC_PATTERN_t ac_pattern;
AC_ERROR_t rc;
memset(&ac_pattern, 0, sizeof(ac_pattern));
if(ndpi_str->custom_categories.hostnames_shadow.ac_automa == NULL) {
free(name);
return(-1);
}
ac_pattern.astring = name, ac_pattern.length = strlen(ac_pattern.astring);
ac_pattern.rep.number = (u_int32_t) category, ac_pattern.rep.category = category;;
rc = ac_automata_add(ndpi_str->custom_categories.hostnames_shadow.ac_automa, &ac_pattern);
if(rc != ACERR_DUPLICATE_PATTERN && rc != ACERR_SUCCESS) {
free(name);
return(-1);
}
if(rc == ACERR_DUPLICATE_PATTERN)
free(name);
return(0);
}
/* ********************************************************************************* */
/* Loads an IP or name category */
int ndpi_load_category(struct ndpi_detection_module_struct *ndpi_struct, const char *ip_or_name,
ndpi_protocol_category_t category) {
int rv;
/* Try to load as IP address first */
rv = ndpi_load_ip_category(ndpi_struct, ip_or_name, category);
if(rv < 0) {
/* IP load failed, load as hostname */
rv = ndpi_load_hostname_category(ndpi_struct, ip_or_name, category);
}
return(rv);
}
/* ********************************************************************************* */
int ndpi_enable_loaded_categories(struct ndpi_detection_module_struct *ndpi_str) {
int i;
/* First add the nDPI known categories matches */
for (i = 0; category_match[i].string_to_match != NULL; i++)
ndpi_load_category(ndpi_str, category_match[i].string_to_match, category_match[i].protocol_category);
/* Free */
ac_automata_release((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames.ac_automa,
1 /* free patterns strings memory */);
/* Finalize */
ac_automata_finalize((AC_AUTOMATA_t *) ndpi_str->custom_categories.hostnames_shadow.ac_automa);
/* Swap */
ndpi_str->custom_categories.hostnames.ac_automa = ndpi_str->custom_categories.hostnames_shadow.ac_automa;
/* Realloc */
ndpi_str->custom_categories.hostnames_shadow.ac_automa = ac_automata_init(ac_match_handler);
if(ndpi_str->custom_categories.ipAddresses != NULL)
ndpi_Destroy_Patricia((patricia_tree_t *) ndpi_str->custom_categories.ipAddresses, free_ptree_data);
ndpi_str->custom_categories.ipAddresses = ndpi_str->custom_categories.ipAddresses_shadow;
ndpi_str->custom_categories.ipAddresses_shadow = ndpi_New_Patricia(32 /* IPv4 */);
ndpi_str->custom_categories.categories_loaded = 1;
return(0);
}
/* ********************************************************************************* */
int ndpi_fill_ip_protocol_category(struct ndpi_detection_module_struct *ndpi_str, u_int32_t saddr, u_int32_t daddr,
ndpi_protocol *ret) {
if(ndpi_str->custom_categories.categories_loaded) {
prefix_t prefix;
patricia_node_t *node;
if(saddr == 0)
node = NULL;
else {
/* Make sure all in network byte order otherwise compares wont work */
fill_prefix_v4(&prefix, (struct in_addr *) &saddr, 32,
((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits);
node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix);
}
if(!node) {
if(daddr != 0) {
fill_prefix_v4(&prefix, (struct in_addr *) &daddr, 32,
((patricia_tree_t *) ndpi_str->protocols_ptree)->maxbits);
node = ndpi_patricia_search_best(ndpi_str->custom_categories.ipAddresses, &prefix);
}
}
if(node) {
ret->category = (ndpi_protocol_category_t) node->value.uv.user_value;
return(1);
}
}
ret->category = ndpi_get_proto_category(ndpi_str, *ret);
return(0);
}
/* ********************************************************************************* */
void ndpi_fill_protocol_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
ndpi_protocol *ret) {
if(ndpi_str->custom_categories.categories_loaded) {
if(flow->guessed_header_category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) {
flow->category = ret->category = flow->guessed_header_category;
return;
}
if(flow->host_server_name[0] != '\0') {
u_int32_t id;
int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->host_server_name,
strlen((char *) flow->host_server_name), &id);
if(rc == 0) {
flow->category = ret->category = (ndpi_protocol_category_t) id;
return;
}
}
if(flow->l4.tcp.tls.hello_processed == 1 &&
flow->protos.stun_ssl.ssl.client_requested_server_name[0] != '\0') {
u_int32_t id;
int rc = ndpi_match_custom_category(ndpi_str, (char *) flow->protos.stun_ssl.ssl.client_requested_server_name,
strlen(flow->protos.stun_ssl.ssl.client_requested_server_name), &id);
if(rc == 0) {
flow->category = ret->category = (ndpi_protocol_category_t) id;
return;
}
}
}
flow->category = ret->category = ndpi_get_proto_category(ndpi_str, *ret);
}
/* ********************************************************************************* */
static void ndpi_reset_packet_line_info(struct ndpi_packet_struct *packet) {
packet->parsed_lines = 0, packet->empty_line_position_set = 0, packet->host_line.ptr = NULL,
packet->host_line.len = 0, packet->referer_line.ptr = NULL, packet->referer_line.len = 0,
packet->content_line.ptr = NULL, packet->content_line.len = 0, packet->accept_line.ptr = NULL,
packet->accept_line.len = 0, packet->user_agent_line.ptr = NULL, packet->user_agent_line.len = 0,
packet->http_url_name.ptr = NULL, packet->http_url_name.len = 0, packet->http_encoding.ptr = NULL,
packet->http_encoding.len = 0, packet->http_transfer_encoding.ptr = NULL, packet->http_transfer_encoding.len = 0,
packet->http_contentlen.ptr = NULL, packet->http_contentlen.len = 0, packet->http_cookie.ptr = NULL,
packet->http_cookie.len = 0, packet->http_origin.len = 0, packet->http_origin.ptr = NULL,
packet->http_x_session_type.ptr = NULL, packet->http_x_session_type.len = 0, packet->server_line.ptr = NULL,
packet->server_line.len = 0, packet->http_method.ptr = NULL, packet->http_method.len = 0,
packet->http_response.ptr = NULL, packet->http_response.len = 0, packet->http_num_headers = 0;
}
/* ********************************************************************************* */
static void ndpi_reconcile_protocols(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow,
ndpi_protocol *ret) {
/*
Skype for a host doing MS Teams means MS Teams
(MS Teams uses Skype as transport protocol for voice/video)
*/
switch(ret->app_protocol) {
case NDPI_PROTOCOL_MSTEAMS:
if(flow->packet.iph && flow->packet.tcp) {
// printf("====>> NDPI_PROTOCOL_MSTEAMS\n");
if(ndpi_str->msteams_cache == NULL)
ndpi_str->msteams_cache = ndpi_lru_cache_init(1024);
if(ndpi_str->msteams_cache)
ndpi_lru_add_to_cache(ndpi_str->msteams_cache,
flow->packet.iph->saddr,
flow->packet.tick_timestamp & 0xFFFF /* 16 bit */);
}
break;
case NDPI_PROTOCOL_SKYPE:
case NDPI_PROTOCOL_SKYPE_CALL:
if(flow->packet.iph
&& flow->packet.udp
&& ndpi_str->msteams_cache) {
u_int16_t when;
if(ndpi_lru_find_cache(ndpi_str->msteams_cache, flow->packet.iph->saddr,
&when, 0 /* Don't remove it as it can be used for other connections */)) {
u_int16_t tdiff = (flow->packet.tick_timestamp & 0xFFFF) - when;
if(tdiff < 60 /* sec */) {
// printf("====>> NDPI_PROTOCOL_SKYPE(_CALL) -> NDPI_PROTOCOL_MSTEAMS [%u]\n", tdiff);
ret->app_protocol = NDPI_PROTOCOL_MSTEAMS;
/* Refresh cache */
ndpi_lru_add_to_cache(ndpi_str->msteams_cache,
flow->packet.iph->saddr,
flow->packet.tick_timestamp & 0xFFFF /* 16 bit */);
}
}
}
break;
} /* switch */
}
/* ********************************************************************************* */
ndpi_protocol ndpi_detection_process_packet(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow, const unsigned char *packet,
const unsigned short packetlen, const u_int64_t current_tick_l,
struct ndpi_id_struct *src, struct ndpi_id_struct *dst) {
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE ndpi_selection_packet;
u_int32_t a;
ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED};
if(ndpi_str->ndpi_log_level >= NDPI_LOG_TRACE)
NDPI_LOG(flow ? flow->detected_protocol_stack[0] : NDPI_PROTOCOL_UNKNOWN, ndpi_str, NDPI_LOG_TRACE,
"START packet processing\n");
if(flow == NULL)
return(ret);
else
ret.category = flow->category;
flow->num_processed_pkts++;
/* Init default */
ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0];
if(flow->server_id == NULL)
flow->server_id = dst; /* Default */
if(flow->detected_protocol_stack[0] != NDPI_PROTOCOL_UNKNOWN) {
if(flow->check_extra_packets) {
ndpi_process_extra_packet(ndpi_str, flow, packet, packetlen, current_tick_l, src, dst);
/* Update in case of new match */
ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0],
ret.category = flow->category;
goto invalidate_ptr;
} else
goto ret_protocols;
}
/* need at least 20 bytes for ip header */
if(packetlen < 20) {
/* reset protocol which is normally done in init_packet_header */
ndpi_int_reset_packet_protocol(&flow->packet);
goto invalidate_ptr;
}
flow->packet.tick_timestamp_l = current_tick_l;
flow->packet.tick_timestamp = (u_int32_t)(current_tick_l / ndpi_str->ticks_per_second);
/* parse packet */
flow->packet.iph = (struct ndpi_iphdr *) packet;
/* we are interested in ipv4 packet */
if(ndpi_init_packet_header(ndpi_str, flow, packetlen) != 0)
goto invalidate_ptr;
/* detect traffic for tcp or udp only */
flow->src = src, flow->dst = dst;
ndpi_connection_tracking(ndpi_str, flow);
/* build ndpi_selection packet bitmask */
ndpi_selection_packet = NDPI_SELECTION_BITMASK_PROTOCOL_COMPLETE_TRAFFIC;
if(flow->packet.iph != NULL)
ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IP | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6;
if(flow->packet.tcp != NULL)
ndpi_selection_packet |=
(NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP);
if(flow->packet.udp != NULL)
ndpi_selection_packet |=
(NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP | NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP);
if(flow->packet.payload_packet_len != 0)
ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_HAS_PAYLOAD;
if(flow->packet.tcp_retransmission == 0)
ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_NO_TCP_RETRANSMISSION;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(flow->packet.iphv6 != NULL)
ndpi_selection_packet |= NDPI_SELECTION_BITMASK_PROTOCOL_IPV6 | NDPI_SELECTION_BITMASK_PROTOCOL_IPV4_OR_IPV6;
#endif /* NDPI_DETECTION_SUPPORT_IPV6 */
if((!flow->protocol_id_already_guessed) && (
#ifdef NDPI_DETECTION_SUPPORT_IPV6
flow->packet.iphv6 ||
#endif
flow->packet.iph)) {
u_int16_t sport, dport;
u_int8_t protocol;
u_int8_t user_defined_proto;
flow->protocol_id_already_guessed = 1;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(flow->packet.iphv6 != NULL) {
protocol = flow->packet.iphv6->ip6_hdr.ip6_un1_nxt;
} else
#endif
{
protocol = flow->packet.iph->protocol;
}
if(flow->packet.udp)
sport = ntohs(flow->packet.udp->source), dport = ntohs(flow->packet.udp->dest);
else if(flow->packet.tcp)
sport = ntohs(flow->packet.tcp->source), dport = ntohs(flow->packet.tcp->dest);
else
sport = dport = 0;
/* guess protocol */
flow->guessed_protocol_id =
(int16_t) ndpi_guess_protocol_id(ndpi_str, flow, protocol, sport, dport, &user_defined_proto);
flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow);
if(ndpi_str->custom_categories.categories_loaded && flow->packet.iph) {
ndpi_fill_ip_protocol_category(ndpi_str, flow->packet.iph->saddr, flow->packet.iph->daddr, &ret);
flow->guessed_header_category = ret.category;
} else
flow->guessed_header_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED;
if(flow->guessed_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) {
/* This is a custom protocol and it has priority over everything else */
ret.master_protocol = NDPI_PROTOCOL_UNKNOWN,
ret.app_protocol = flow->guessed_protocol_id ? flow->guessed_protocol_id : flow->guessed_host_protocol_id;
ndpi_fill_protocol_category(ndpi_str, flow, &ret);
goto invalidate_ptr;
}
if(user_defined_proto && flow->guessed_protocol_id != NDPI_PROTOCOL_UNKNOWN) {
if(flow->packet.iph) {
if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) {
u_int8_t protocol_was_guessed;
/* ret.master_protocol = flow->guessed_protocol_id , ret.app_protocol = flow->guessed_host_protocol_id; /\* ****** *\/ */
ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed);
}
ndpi_fill_protocol_category(ndpi_str, flow, &ret);
goto invalidate_ptr;
}
} else {
/* guess host protocol */
if(flow->packet.iph) {
flow->guessed_host_protocol_id = ndpi_guess_host_protocol_id(ndpi_str, flow);
/*
We could implement a shortcut here skipping dissectors for
protocols we have identified by other means such as with the IP
However we do NOT stop here and skip invoking the dissectors
because we want to dissect the flow (e.g. dissect the TLS)
and extract metadata.
*/
#if SKIP_INVOKING_THE_DISSECTORS
if(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) {
/*
We have identified a protocol using the IP address so
it is not worth to dissect the traffic as we already have
the solution
*/
ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id;
}
#endif
}
}
}
if(flow->guessed_host_protocol_id >= NDPI_MAX_SUPPORTED_PROTOCOLS) {
/* This is a custom protocol and it has priority over everything else */
ret.master_protocol = flow->guessed_protocol_id, ret.app_protocol = flow->guessed_host_protocol_id;
ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet);
ndpi_fill_protocol_category(ndpi_str, flow, &ret);
goto invalidate_ptr;
}
ndpi_check_flow_func(ndpi_str, flow, &ndpi_selection_packet);
a = flow->packet.detected_protocol_stack[0];
if(NDPI_COMPARE_PROTOCOL_TO_BITMASK(ndpi_str->detection_bitmask, a) == 0)
a = NDPI_PROTOCOL_UNKNOWN;
if(a != NDPI_PROTOCOL_UNKNOWN) {
int i;
for (i = 0; i < sizeof(flow->host_server_name); i++) {
if(flow->host_server_name[i] != '\0')
flow->host_server_name[i] = tolower(flow->host_server_name[i]);
else {
flow->host_server_name[i] = '\0';
break;
}
}
}
ret_protocols:
if(flow->detected_protocol_stack[1] != NDPI_PROTOCOL_UNKNOWN) {
ret.master_protocol = flow->detected_protocol_stack[1], ret.app_protocol = flow->detected_protocol_stack[0];
if(ret.app_protocol == ret.master_protocol)
ret.master_protocol = NDPI_PROTOCOL_UNKNOWN;
} else
ret.app_protocol = flow->detected_protocol_stack[0];
/* Don't overwrite the category if already set */
if((flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN))
ndpi_fill_protocol_category(ndpi_str, flow, &ret);
else
ret.category = flow->category;
if((flow->num_processed_pkts == 1) && (ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) &&
(ret.app_protocol == NDPI_PROTOCOL_UNKNOWN) && flow->packet.tcp && (flow->packet.tcp->syn == 0) &&
(flow->guessed_protocol_id == 0)) {
u_int8_t protocol_was_guessed;
/*
This is a TCP flow
- whose first packet is NOT a SYN
- no protocol has been detected
We don't see how future packets can match anything
hence we giveup here
*/
ret = ndpi_detection_giveup(ndpi_str, flow, 0, &protocol_was_guessed);
}
if((ret.master_protocol == NDPI_PROTOCOL_UNKNOWN) && (ret.app_protocol != NDPI_PROTOCOL_UNKNOWN) &&
(flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN)) {
ret.master_protocol = ret.app_protocol;
ret.app_protocol = flow->guessed_host_protocol_id;
}
if((!flow->risk_checked) && (ret.master_protocol != NDPI_PROTOCOL_UNKNOWN)) {
ndpi_default_ports_tree_node_t *found;
u_int16_t *default_ports, sport, dport;
if(flow->packet.udp)
found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_UDP,
sport = ntohs(flow->packet.udp->source),
dport = ntohs(flow->packet.udp->dest)),
default_ports = ndpi_str->proto_defaults[ret.master_protocol].udp_default_ports;
else if(flow->packet.tcp)
found = ndpi_get_guessed_protocol_id(ndpi_str, IPPROTO_TCP,
sport = ntohs(flow->packet.tcp->source),
dport = ntohs(flow->packet.tcp->dest)),
default_ports = ndpi_str->proto_defaults[ret.master_protocol].tcp_default_ports;
else
found = NULL, default_ports = NULL;
if(found
&& (found->proto->protoId != NDPI_PROTOCOL_UNKNOWN)
&& (found->proto->protoId != ret.master_protocol)) {
// printf("******** %u / %u\n", found->proto->protoId, ret.master_protocol);
NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT);
} else if(default_ports && (default_ports[0] != 0)) {
u_int8_t found = 0, i;
for(i=0; (i<MAX_DEFAULT_PORTS) && (default_ports[i] != 0); i++) {
if((default_ports[i] == sport) || (default_ports[i] == dport)) {
found = 1;
break;
}
} /* for */
if(!found) {
// printf("******** Invalid default port\n");
NDPI_SET_BIT(flow->risk, NDPI_KNOWN_PROTOCOL_ON_NON_STANDARD_PORT);
}
}
flow->risk_checked = 1;
}
ndpi_reconcile_protocols(ndpi_str, flow, &ret);
invalidate_ptr:
/*
Invalidate packet memory to avoid accessing the pointers below
when the packet is no longer accessible
*/
flow->packet.iph = NULL, flow->packet.tcp = NULL, flow->packet.udp = NULL, flow->packet.payload = NULL;
ndpi_reset_packet_line_info(&flow->packet);
return(ret);
}
/* ********************************************************************************* */
u_int32_t ndpi_bytestream_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) {
u_int32_t val;
val = 0;
// cancel if eof, ' ' or line end chars are reached
while (*str >= '0' && *str <= '9' && max_chars_to_read > 0) {
val *= 10;
val += *str - '0';
str++;
max_chars_to_read = max_chars_to_read - 1;
*bytes_read = *bytes_read + 1;
}
return(val);
}
/* ********************************************************************************* */
#ifdef CODE_UNUSED
u_int32_t ndpi_bytestream_dec_or_hex_to_number(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) {
u_int32_t val;
val = 0;
if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') {
return(ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read));
} else {
/*use base 16 system */
str += 2;
max_chars_to_read -= 2;
*bytes_read = *bytes_read + 2;
while (max_chars_to_read > 0) {
if(*str >= '0' && *str <= '9') {
val *= 16;
val += *str - '0';
} else if(*str >= 'a' && *str <= 'f') {
val *= 16;
val += *str + 10 - 'a';
} else if(*str >= 'A' && *str <= 'F') {
val *= 16;
val += *str + 10 - 'A';
} else {
break;
}
str++;
max_chars_to_read = max_chars_to_read - 1;
*bytes_read = *bytes_read + 1;
}
}
return(val);
}
#endif
/* ********************************************************************************* */
u_int64_t ndpi_bytestream_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) {
u_int64_t val;
val = 0;
// cancel if eof, ' ' or line end chars are reached
while (max_chars_to_read > 0 && *str >= '0' && *str <= '9') {
val *= 10;
val += *str - '0';
str++;
max_chars_to_read = max_chars_to_read - 1;
*bytes_read = *bytes_read + 1;
}
return(val);
}
/* ********************************************************************************* */
u_int64_t ndpi_bytestream_dec_or_hex_to_number64(const u_int8_t *str, u_int16_t max_chars_to_read,
u_int16_t *bytes_read) {
u_int64_t val;
val = 0;
if(max_chars_to_read <= 2 || str[0] != '0' || str[1] != 'x') {
return(ndpi_bytestream_to_number64(str, max_chars_to_read, bytes_read));
} else {
/*use base 16 system */
str += 2;
max_chars_to_read -= 2;
*bytes_read = *bytes_read + 2;
while (max_chars_to_read > 0) {
if(*str >= '0' && *str <= '9') {
val *= 16;
val += *str - '0';
} else if(*str >= 'a' && *str <= 'f') {
val *= 16;
val += *str + 10 - 'a';
} else if(*str >= 'A' && *str <= 'F') {
val *= 16;
val += *str + 10 - 'A';
} else {
break;
}
str++;
max_chars_to_read = max_chars_to_read - 1;
*bytes_read = *bytes_read + 1;
}
}
return(val);
}
/* ********************************************************************************* */
u_int32_t ndpi_bytestream_to_ipv4(const u_int8_t *str, u_int16_t max_chars_to_read, u_int16_t *bytes_read) {
u_int32_t val;
u_int16_t read = 0;
u_int16_t oldread;
u_int32_t c;
/* ip address must be X.X.X.X with each X between 0 and 255 */
oldread = read;
c = ndpi_bytestream_to_number(str, max_chars_to_read, &read);
if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.')
return(0);
read++;
val = c << 24;
oldread = read;
c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read);
if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.')
return(0);
read++;
val = val + (c << 16);
oldread = read;
c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read);
if(c > 255 || oldread == read || max_chars_to_read == read || str[read] != '.')
return(0);
read++;
val = val + (c << 8);
oldread = read;
c = ndpi_bytestream_to_number(&str[read], max_chars_to_read - read, &read);
if(c > 255 || oldread == read || max_chars_to_read == read)
return(0);
val = val + c;
*bytes_read = *bytes_read + read;
return(htonl(val));
}
/* ********************************************************************************* */
/* internal function for every detection to parse one packet and to increase the info buffer */
void ndpi_parse_packet_line_info(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) {
u_int32_t a;
struct ndpi_packet_struct *packet = &flow->packet;
if((packet->payload_packet_len < 3) || (packet->payload == NULL))
return;
if(packet->packet_lines_parsed_complete != 0)
return;
packet->packet_lines_parsed_complete = 1;
ndpi_reset_packet_line_info(packet);
packet->line[packet->parsed_lines].ptr = packet->payload;
packet->line[packet->parsed_lines].len = 0;
for (a = 0; (a < packet->payload_packet_len) && (packet->parsed_lines < NDPI_MAX_PARSE_LINES_PER_PACKET); a++) {
if((a + 1) >= packet->payload_packet_len)
return; /* Return if only one byte remains (prevent invalid reads past end-of-buffer) */
if(get_u_int16_t(packet->payload, a) == ntohs(0x0d0a)) {
/* If end of line char sequence CR+NL "\r\n", process line */
if(((a + 3) <= packet->payload_packet_len)
&& (get_u_int16_t(packet->payload, a+2) == ntohs(0x0d0a))) {
/* \r\n\r\n */
int diff; /* No unsigned ! */
u_int32_t a1 = a + 4;
diff = ndpi_min(packet->payload_packet_len-a1, sizeof(flow->initial_binary_bytes));
if(diff > 0) {
memcpy(&flow->initial_binary_bytes, &packet->payload[a1], diff);
flow->initial_binary_bytes_len = diff;
}
}
packet->line[packet->parsed_lines].len =
(u_int16_t)(((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr));
/* First line of a HTTP response parsing. Expected a "HTTP/1.? ???" */
if(packet->parsed_lines == 0 && packet->line[0].len >= NDPI_STATICSTRING_LEN("HTTP/1.X 200 ") &&
strncasecmp((const char *) packet->line[0].ptr, "HTTP/1.", NDPI_STATICSTRING_LEN("HTTP/1.")) == 0 &&
packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] > '0' && /* response code between 000 and 699 */
packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.X ")] < '6') {
packet->http_response.ptr = &packet->line[0].ptr[NDPI_STATICSTRING_LEN("HTTP/1.1 ")];
packet->http_response.len = packet->line[0].len - NDPI_STATICSTRING_LEN("HTTP/1.1 ");
packet->http_num_headers++;
/* Set server HTTP response code */
if(packet->payload_packet_len >= 12) {
char buf[4];
/* Set server HTTP response code */
strncpy(buf, (char *) &packet->payload[9], 3);
buf[3] = '\0';
flow->http.response_status_code = atoi(buf);
/* https://en.wikipedia.org/wiki/List_of_HTTP_status_codes */
if((flow->http.response_status_code < 100) || (flow->http.response_status_code > 509))
flow->http.response_status_code = 0; /* Out of range */
}
}
/* "Server:" header line in HTTP response */
if(packet->line[packet->parsed_lines].len > NDPI_STATICSTRING_LEN("Server:") + 1 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr,
"Server:", NDPI_STATICSTRING_LEN("Server:")) == 0) {
// some stupid clients omit a space and place the servername directly after the colon
if(packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")] == ' ') {
packet->server_line.ptr =
&packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:") + 1];
packet->server_line.len =
packet->line[packet->parsed_lines].len - (NDPI_STATICSTRING_LEN("Server:") + 1);
} else {
packet->server_line.ptr = &packet->line[packet->parsed_lines].ptr[NDPI_STATICSTRING_LEN("Server:")];
packet->server_line.len = packet->line[packet->parsed_lines].len - NDPI_STATICSTRING_LEN("Server:");
}
packet->http_num_headers++;
}
/* "Host:" header line in HTTP request */
if(packet->line[packet->parsed_lines].len > 6 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Host:", 5) == 0) {
// some stupid clients omit a space and place the hostname directly after the colon
if(packet->line[packet->parsed_lines].ptr[5] == ' ') {
packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[6];
packet->host_line.len = packet->line[packet->parsed_lines].len - 6;
} else {
packet->host_line.ptr = &packet->line[packet->parsed_lines].ptr[5];
packet->host_line.len = packet->line[packet->parsed_lines].len - 5;
}
packet->http_num_headers++;
}
/* "X-Forwarded-For:" header line in HTTP request. Commonly used for HTTP proxies. */
if(packet->line[packet->parsed_lines].len > 17 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Forwarded-For:", 16) == 0) {
// some stupid clients omit a space and place the hostname directly after the colon
if(packet->line[packet->parsed_lines].ptr[16] == ' ') {
packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[17];
packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 17;
} else {
packet->forwarded_line.ptr = &packet->line[packet->parsed_lines].ptr[16];
packet->forwarded_line.len = packet->line[packet->parsed_lines].len - 16;
}
packet->http_num_headers++;
}
/* "Content-Type:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 14 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Type: ", 14) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type: ", 14) == 0)) {
packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[14];
packet->content_line.len = packet->line[packet->parsed_lines].len - 14;
while ((packet->content_line.len > 0) && (packet->content_line.ptr[0] == ' '))
packet->content_line.len--, packet->content_line.ptr++;
packet->http_num_headers++;
}
/* "Content-Type:" header line in HTTP AGAIN. Probably a bogus response without space after ":" */
if((packet->content_line.len == 0) && (packet->line[packet->parsed_lines].len > 13) &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-type:", 13) == 0)) {
packet->content_line.ptr = &packet->line[packet->parsed_lines].ptr[13];
packet->content_line.len = packet->line[packet->parsed_lines].len - 13;
packet->http_num_headers++;
}
if(packet->content_line.len > 0) {
/* application/json; charset=utf-8 */
char separator[] = {';', '\r', '\0'};
int i;
for (i = 0; separator[i] != '\0'; i++) {
char *c = memchr((char *) packet->content_line.ptr, separator[i], packet->content_line.len);
if(c != NULL)
packet->content_line.len = c - (char *) packet->content_line.ptr;
}
}
/* "Accept:" header line in HTTP request. */
if(packet->line[packet->parsed_lines].len > 8 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept: ", 8) == 0) {
packet->accept_line.ptr = &packet->line[packet->parsed_lines].ptr[8];
packet->accept_line.len = packet->line[packet->parsed_lines].len - 8;
packet->http_num_headers++;
}
/* "Referer:" header line in HTTP request. */
if(packet->line[packet->parsed_lines].len > 9 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Referer: ", 9) == 0) {
packet->referer_line.ptr = &packet->line[packet->parsed_lines].ptr[9];
packet->referer_line.len = packet->line[packet->parsed_lines].len - 9;
packet->http_num_headers++;
}
/* "User-Agent:" header line in HTTP request. */
if(packet->line[packet->parsed_lines].len > 12 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-Agent: ", 12) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "User-agent: ", 12) == 0)) {
packet->user_agent_line.ptr = &packet->line[packet->parsed_lines].ptr[12];
packet->user_agent_line.len = packet->line[packet->parsed_lines].len - 12;
packet->http_num_headers++;
}
/* "Content-Encoding:" header line in HTTP response (and request?). */
if(packet->line[packet->parsed_lines].len > 18 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Encoding: ", 18) == 0) {
packet->http_encoding.ptr = &packet->line[packet->parsed_lines].ptr[18];
packet->http_encoding.len = packet->line[packet->parsed_lines].len - 18;
packet->http_num_headers++;
}
/* "Transfer-Encoding:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 19 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Transfer-Encoding: ", 19) == 0) {
packet->http_transfer_encoding.ptr = &packet->line[packet->parsed_lines].ptr[19];
packet->http_transfer_encoding.len = packet->line[packet->parsed_lines].len - 19;
packet->http_num_headers++;
}
/* "Content-Length:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 16 &&
((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Length: ", 16) == 0) ||
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "content-length: ", 16) == 0))) {
packet->http_contentlen.ptr = &packet->line[packet->parsed_lines].ptr[16];
packet->http_contentlen.len = packet->line[packet->parsed_lines].len - 16;
packet->http_num_headers++;
}
/* "Content-Disposition"*/
if(packet->line[packet->parsed_lines].len > 21 &&
((strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Content-Disposition: ", 21) == 0))) {
packet->content_disposition_line.ptr = &packet->line[packet->parsed_lines].ptr[21];
packet->content_disposition_line.len = packet->line[packet->parsed_lines].len - 21;
packet->http_num_headers++;
}
/* "Cookie:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 8 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Cookie: ", 8) == 0) {
packet->http_cookie.ptr = &packet->line[packet->parsed_lines].ptr[8];
packet->http_cookie.len = packet->line[packet->parsed_lines].len - 8;
packet->http_num_headers++;
}
/* "Origin:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 8 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Origin: ", 8) == 0) {
packet->http_origin.ptr = &packet->line[packet->parsed_lines].ptr[8];
packet->http_origin.len = packet->line[packet->parsed_lines].len - 8;
packet->http_num_headers++;
}
/* "X-Session-Type:" header line in HTTP. */
if(packet->line[packet->parsed_lines].len > 16 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "X-Session-Type: ", 16) == 0) {
packet->http_x_session_type.ptr = &packet->line[packet->parsed_lines].ptr[16];
packet->http_x_session_type.len = packet->line[packet->parsed_lines].len - 16;
packet->http_num_headers++;
}
/* Identification and counting of other HTTP headers.
* We consider the most common headers, but there are many others,
* which can be seen at references below:
* - https://tools.ietf.org/html/rfc7230
* - https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
*/
if((packet->line[packet->parsed_lines].len > 6 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Date: ", 6) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Vary: ", 6) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "ETag: ", 6) == 0)) ||
(packet->line[packet->parsed_lines].len > 8 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Pragma: ", 8) == 0) ||
(packet->line[packet->parsed_lines].len > 9 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Expires: ", 9) == 0) ||
(packet->line[packet->parsed_lines].len > 12 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Set-Cookie: ", 12) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Keep-Alive: ", 12) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Connection: ", 12) == 0)) ||
(packet->line[packet->parsed_lines].len > 15 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Last-Modified: ", 15) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Ranges: ", 15) == 0)) ||
(packet->line[packet->parsed_lines].len > 17 &&
(strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Language: ", 17) == 0 ||
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr, "Accept-Encoding: ", 17) == 0)) ||
(packet->line[packet->parsed_lines].len > 27 &&
strncasecmp((const char *) packet->line[packet->parsed_lines].ptr,
"Upgrade-Insecure-Requests: ", 27) == 0)) {
/* Just count. In the future, if needed, this if can be splited to parse these headers */
packet->http_num_headers++;
}
if(packet->line[packet->parsed_lines].len == 0) {
packet->empty_line_position = a;
packet->empty_line_position_set = 1;
}
if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1))
return;
packet->parsed_lines++;
packet->line[packet->parsed_lines].ptr = &packet->payload[a + 2];
packet->line[packet->parsed_lines].len = 0;
a++; /* next char in the payload */
}
}
if(packet->parsed_lines >= 1) {
packet->line[packet->parsed_lines].len =
(u_int16_t)(((unsigned long) &packet->payload[packet->payload_packet_len]) -
((unsigned long) packet->line[packet->parsed_lines].ptr));
packet->parsed_lines++;
}
}
/* ********************************************************************************* */
void ndpi_parse_packet_line_info_any(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) {
struct ndpi_packet_struct *packet = &flow->packet;
u_int32_t a;
u_int16_t end = packet->payload_packet_len;
if(packet->packet_lines_parsed_complete != 0)
return;
packet->packet_lines_parsed_complete = 1;
packet->parsed_lines = 0;
if(packet->payload_packet_len == 0)
return;
packet->line[packet->parsed_lines].ptr = packet->payload;
packet->line[packet->parsed_lines].len = 0;
for (a = 0; a < end; a++) {
if(packet->payload[a] == 0x0a) {
packet->line[packet->parsed_lines].len = (u_int16_t)(
((unsigned long) &packet->payload[a]) - ((unsigned long) packet->line[packet->parsed_lines].ptr));
if(a > 0 && packet->payload[a - 1] == 0x0d)
packet->line[packet->parsed_lines].len--;
if(packet->parsed_lines >= (NDPI_MAX_PARSE_LINES_PER_PACKET - 1))
break;
packet->parsed_lines++;
packet->line[packet->parsed_lines].ptr = &packet->payload[a + 1];
packet->line[packet->parsed_lines].len = 0;
if((a + 1) >= packet->payload_packet_len)
break;
//a++;
}
}
}
/* ********************************************************************************* */
u_int16_t ndpi_check_for_email_address(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t counter) {
struct ndpi_packet_struct *packet = &flow->packet;
NDPI_LOG_DBG2(ndpi_str, "called ndpi_check_for_email_address\n");
if(packet->payload_packet_len > counter && ((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') ||
(packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') ||
(packet->payload[counter] >= '0' && packet->payload[counter] <= '9') ||
packet->payload[counter] == '-' || packet->payload[counter] == '_')) {
NDPI_LOG_DBG2(ndpi_str, "first letter\n");
counter++;
while (packet->payload_packet_len > counter &&
((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') ||
(packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') ||
(packet->payload[counter] >= '0' && packet->payload[counter] <= '9') ||
packet->payload[counter] == '-' || packet->payload[counter] == '_' ||
packet->payload[counter] == '.')) {
NDPI_LOG_DBG2(ndpi_str, "further letter\n");
counter++;
if(packet->payload_packet_len > counter && packet->payload[counter] == '@') {
NDPI_LOG_DBG2(ndpi_str, "@\n");
counter++;
while (packet->payload_packet_len > counter &&
((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') ||
(packet->payload[counter] >= 'A' && packet->payload[counter] <= 'Z') ||
(packet->payload[counter] >= '0' && packet->payload[counter] <= '9') ||
packet->payload[counter] == '-' || packet->payload[counter] == '_')) {
NDPI_LOG_DBG2(ndpi_str, "letter\n");
counter++;
if(packet->payload_packet_len > counter && packet->payload[counter] == '.') {
NDPI_LOG_DBG2(ndpi_str, ".\n");
counter++;
if(packet->payload_packet_len > counter + 1 &&
((packet->payload[counter] >= 'a' && packet->payload[counter] <= 'z') &&
(packet->payload[counter + 1] >= 'a' && packet->payload[counter + 1] <= 'z'))) {
NDPI_LOG_DBG2(ndpi_str, "two letters\n");
counter += 2;
if(packet->payload_packet_len > counter &&
(packet->payload[counter] == ' ' || packet->payload[counter] == ';')) {
NDPI_LOG_DBG2(ndpi_str, "whitespace1\n");
return(counter);
} else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' &&
packet->payload[counter] <= 'z') {
NDPI_LOG_DBG2(ndpi_str, "one letter\n");
counter++;
if(packet->payload_packet_len > counter &&
(packet->payload[counter] == ' ' || packet->payload[counter] == ';')) {
NDPI_LOG_DBG2(ndpi_str, "whitespace2\n");
return(counter);
} else if(packet->payload_packet_len > counter && packet->payload[counter] >= 'a' &&
packet->payload[counter] <= 'z') {
counter++;
if(packet->payload_packet_len > counter &&
(packet->payload[counter] == ' ' || packet->payload[counter] == ';')) {
NDPI_LOG_DBG2(ndpi_str, "whitespace3\n");
return(counter);
} else {
return(0);
}
} else {
return(0);
}
} else {
return(0);
}
} else {
return(0);
}
}
}
return(0);
}
}
}
return(0);
}
#ifdef NDPI_ENABLE_DEBUG_MESSAGES
/* ********************************************************************************* */
void ndpi_debug_get_last_log_function_line(struct ndpi_detection_module_struct *ndpi_str, const char **file,
const char **func, u_int32_t *line) {
*file = "";
*func = "";
if(ndpi_str->ndpi_debug_print_file != NULL)
*file = ndpi_str->ndpi_debug_print_file;
if(ndpi_str->ndpi_debug_print_function != NULL)
*func = ndpi_str->ndpi_debug_print_function;
*line = ndpi_str->ndpi_debug_print_line;
}
#endif
/* ********************************************************************************* */
u_int8_t ndpi_detection_get_l4(const u_int8_t *l3, u_int16_t l3_len, const u_int8_t **l4_return,
u_int16_t *l4_len_return, u_int8_t *l4_protocol_return, u_int32_t flags) {
return(ndpi_detection_get_l4_internal(NULL, l3, l3_len, l4_return, l4_len_return, l4_protocol_return, flags));
}
/* ********************************************************************************* */
void ndpi_set_detected_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) {
struct ndpi_id_struct *src = flow->src, *dst = flow->dst;
ndpi_int_change_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol);
if(src != NULL) {
NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, upper_detected_protocol);
if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN)
NDPI_ADD_PROTOCOL_TO_BITMASK(src->detected_protocol_bitmask, lower_detected_protocol);
}
if(dst != NULL) {
NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, upper_detected_protocol);
if(lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN)
NDPI_ADD_PROTOCOL_TO_BITMASK(dst->detected_protocol_bitmask, lower_detected_protocol);
}
}
/* ********************************************************************************* */
u_int16_t ndpi_get_flow_masterprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow) {
return(flow->detected_protocol_stack[1]);
}
/* ********************************************************************************* */
void ndpi_int_change_flow_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) {
if(!flow)
return;
flow->detected_protocol_stack[0] = upper_detected_protocol,
flow->detected_protocol_stack[1] = lower_detected_protocol;
}
/* ********************************************************************************* */
void ndpi_int_change_packet_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) {
struct ndpi_packet_struct *packet = &flow->packet;
/* NOTE: everything below is identically to change_flow_protocol
* except flow->packet If you want to change something here,
* don't! Change it for the flow function and apply it here
* as well */
if(!packet)
return;
packet->detected_protocol_stack[0] = upper_detected_protocol,
packet->detected_protocol_stack[1] = lower_detected_protocol;
}
/* ********************************************************************************* */
/* generic function for changing the protocol
*
* what it does is:
* 1.update the flow protocol stack with the new protocol
* 2.update the packet protocol stack with the new protocol
*/
void ndpi_int_change_protocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
u_int16_t upper_detected_protocol, u_int16_t lower_detected_protocol) {
if((upper_detected_protocol == NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol != NDPI_PROTOCOL_UNKNOWN))
upper_detected_protocol = lower_detected_protocol;
if(upper_detected_protocol == lower_detected_protocol)
lower_detected_protocol = NDPI_PROTOCOL_UNKNOWN;
if((upper_detected_protocol != NDPI_PROTOCOL_UNKNOWN) && (lower_detected_protocol == NDPI_PROTOCOL_UNKNOWN)) {
if((flow->guessed_host_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(upper_detected_protocol != flow->guessed_host_protocol_id)) {
if(ndpi_str->proto_defaults[upper_detected_protocol].can_have_a_subprotocol) {
lower_detected_protocol = upper_detected_protocol;
upper_detected_protocol = flow->guessed_host_protocol_id;
}
}
}
ndpi_int_change_flow_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol);
ndpi_int_change_packet_protocol(ndpi_str, flow, upper_detected_protocol, lower_detected_protocol);
}
/* ********************************************************************************* */
void ndpi_int_change_category(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
ndpi_protocol_category_t protocol_category) {
flow->category = protocol_category;
}
/* ********************************************************************************* */
/* turns a packet back to unknown */
void ndpi_int_reset_packet_protocol(struct ndpi_packet_struct *packet) {
int a;
for (a = 0; a < NDPI_PROTOCOL_SIZE; a++)
packet->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN;
}
/* ********************************************************************************* */
void ndpi_int_reset_protocol(struct ndpi_flow_struct *flow) {
if(flow) {
int a;
for (a = 0; a < NDPI_PROTOCOL_SIZE; a++)
flow->detected_protocol_stack[a] = NDPI_PROTOCOL_UNKNOWN;
}
}
/* ********************************************************************************* */
void NDPI_PROTOCOL_IP_clear(ndpi_ip_addr_t *ip) {
memset(ip, 0, sizeof(ndpi_ip_addr_t));
}
/* ********************************************************************************* */
#ifdef CODE_UNUSED
/* NTOP */
int NDPI_PROTOCOL_IP_is_set(const ndpi_ip_addr_t *ip) {
return(memcmp(ip, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", sizeof(ndpi_ip_addr_t)) != 0);
}
#endif
/* ********************************************************************************* */
/* check if the source ip address in packet and ip are equal */
/* NTOP */
int ndpi_packet_src_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) {
#ifdef NDPI_DETECTION_SUPPORT_IPV6
/* IPv6 */
if(packet->iphv6 != NULL) {
if(packet->iphv6->ip6_src.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] &&
packet->iphv6->ip6_src.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] &&
packet->iphv6->ip6_src.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] &&
packet->iphv6->ip6_src.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3])
return(1);
//else
return(0);
}
#endif
/* IPv4 */
if(packet->iph->saddr == ip->ipv4)
return(1);
return(0);
}
/* ********************************************************************************* */
/* check if the destination ip address in packet and ip are equal */
int ndpi_packet_dst_ip_eql(const struct ndpi_packet_struct *packet, const ndpi_ip_addr_t *ip) {
#ifdef NDPI_DETECTION_SUPPORT_IPV6
/* IPv6 */
if(packet->iphv6 != NULL) {
if(packet->iphv6->ip6_dst.u6_addr.u6_addr32[0] == ip->ipv6.u6_addr.u6_addr32[0] &&
packet->iphv6->ip6_dst.u6_addr.u6_addr32[1] == ip->ipv6.u6_addr.u6_addr32[1] &&
packet->iphv6->ip6_dst.u6_addr.u6_addr32[2] == ip->ipv6.u6_addr.u6_addr32[2] &&
packet->iphv6->ip6_dst.u6_addr.u6_addr32[3] == ip->ipv6.u6_addr.u6_addr32[3])
return(1);
//else
return(0);
}
#endif
/* IPv4 */
if(packet->iph->saddr == ip->ipv4)
return(1);
return(0);
}
/* ********************************************************************************* */
/* get the source ip address from packet and put it into ip */
/* NTOP */
void ndpi_packet_src_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) {
NDPI_PROTOCOL_IP_clear(ip);
#ifdef NDPI_DETECTION_SUPPORT_IPV6
/* IPv6 */
if(packet->iphv6 != NULL) {
ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_src.u6_addr.u6_addr32[0];
ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_src.u6_addr.u6_addr32[1];
ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_src.u6_addr.u6_addr32[2];
ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_src.u6_addr.u6_addr32[3];
} else
#endif
/* IPv4 */
ip->ipv4 = packet->iph->saddr;
}
/* ********************************************************************************* */
/* get the destination ip address from packet and put it into ip */
/* NTOP */
void ndpi_packet_dst_ip_get(const struct ndpi_packet_struct *packet, ndpi_ip_addr_t *ip) {
NDPI_PROTOCOL_IP_clear(ip);
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(packet->iphv6 != NULL) {
ip->ipv6.u6_addr.u6_addr32[0] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[0];
ip->ipv6.u6_addr.u6_addr32[1] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[1];
ip->ipv6.u6_addr.u6_addr32[2] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[2];
ip->ipv6.u6_addr.u6_addr32[3] = packet->iphv6->ip6_dst.u6_addr.u6_addr32[3];
} else
#endif
ip->ipv4 = packet->iph->daddr;
}
/* ********************************************************************************* */
u_int8_t ndpi_is_ipv6(const ndpi_ip_addr_t *ip) {
#ifdef NDPI_DETECTION_SUPPORT_IPV6
return(ip->ipv6.u6_addr.u6_addr32[1] != 0 || ip->ipv6.u6_addr.u6_addr32[2] != 0 ||
ip->ipv6.u6_addr.u6_addr32[3] != 0);
#else
return(0);
#endif
}
/* ********************************************************************************* */
char *ndpi_get_ip_string(const ndpi_ip_addr_t *ip, char *buf, u_int buf_len) {
const u_int8_t *a = (const u_int8_t *) &ip->ipv4;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
if(ndpi_is_ipv6(ip)) {
if(inet_ntop(AF_INET6, &ip->ipv6.u6_addr, buf, buf_len) == NULL)
buf[0] = '\0';
return(buf);
}
#endif
snprintf(buf, buf_len, "%u.%u.%u.%u", a[0], a[1], a[2], a[3]);
return(buf);
}
/* ****************************************************** */
/* Returns -1 on failutre, otherwise fills parsed_ip and returns the IP version */
int ndpi_parse_ip_string(const char *ip_str, ndpi_ip_addr_t *parsed_ip) {
int rv = -1;
memset(parsed_ip, 0, sizeof(*parsed_ip));
if(strchr(ip_str, '.')) {
if(inet_pton(AF_INET, ip_str, &parsed_ip->ipv4) > 0)
rv = 4;
#ifdef NDPI_DETECTION_SUPPORT_IPV6
} else {
if(inet_pton(AF_INET6, ip_str, &parsed_ip->ipv6) > 0)
rv = 6;
#endif
}
return(rv);
}
/* ****************************************************** */
u_int16_t ntohs_ndpi_bytestream_to_number(const u_int8_t *str,
u_int16_t max_chars_to_read, u_int16_t *bytes_read) {
u_int16_t val = ndpi_bytestream_to_number(str, max_chars_to_read, bytes_read);
return(ntohs(val));
}
/* ****************************************************** */
u_int8_t ndpi_is_proto(ndpi_protocol proto, u_int16_t p) {
return(((proto.app_protocol == p) || (proto.master_protocol == p)) ? 1 : 0);
}
/* ****************************************************** */
u_int16_t ndpi_get_lower_proto(ndpi_protocol proto) {
return((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) ? proto.master_protocol : proto.app_protocol);
}
/* ****************************************************** */
ndpi_protocol ndpi_guess_undetected_protocol(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow, u_int8_t proto,
u_int32_t shost /* host byte order */, u_int16_t sport,
u_int32_t dhost /* host byte order */, u_int16_t dport) {
u_int32_t rc;
struct in_addr addr;
ndpi_protocol ret = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED};
u_int8_t user_defined_proto;
if((proto == IPPROTO_TCP) || (proto == IPPROTO_UDP)) {
rc = ndpi_search_tcp_or_udp_raw(ndpi_str, flow, proto, shost, dhost, sport, dport);
if(rc != NDPI_PROTOCOL_UNKNOWN) {
if(flow && (proto == IPPROTO_UDP) &&
NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc))
;
else {
ret.app_protocol = rc,
ret.master_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto);
if(ret.app_protocol == ret.master_protocol)
ret.master_protocol = NDPI_PROTOCOL_UNKNOWN;
ret.category = ndpi_get_proto_category(ndpi_str, ret);
return(ret);
}
}
rc = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto);
if(rc != NDPI_PROTOCOL_UNKNOWN) {
if(flow && (proto == IPPROTO_UDP) &&
NDPI_COMPARE_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, rc) && is_udp_guessable_protocol(rc))
;
else {
ret.app_protocol = rc;
if(rc == NDPI_PROTOCOL_TLS)
goto check_guessed_skype;
else {
ret.category = ndpi_get_proto_category(ndpi_str, ret);
return(ret);
}
}
}
check_guessed_skype:
addr.s_addr = htonl(shost);
if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE) {
ret.app_protocol = NDPI_PROTOCOL_SKYPE;
} else {
addr.s_addr = htonl(dhost);
if(ndpi_network_ptree_match(ndpi_str, &addr) == NDPI_PROTOCOL_SKYPE)
ret.app_protocol = NDPI_PROTOCOL_SKYPE;
}
} else
ret.app_protocol = ndpi_guess_protocol_id(ndpi_str, flow, proto, sport, dport, &user_defined_proto);
ret.category = ndpi_get_proto_category(ndpi_str, ret);
return(ret);
}
/* ****************************************************** */
char *ndpi_protocol2id(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol proto, char *buf, u_int buf_len) {
if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) {
if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN)
snprintf(buf, buf_len, "%u.%u", proto.master_protocol, proto.app_protocol);
else
snprintf(buf, buf_len, "%u", proto.master_protocol);
} else
snprintf(buf, buf_len, "%u", proto.app_protocol);
return(buf);
}
/* ****************************************************** */
char *ndpi_protocol2name(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol proto, char *buf, u_int buf_len) {
if((proto.master_protocol != NDPI_PROTOCOL_UNKNOWN) && (proto.master_protocol != proto.app_protocol)) {
if(proto.app_protocol != NDPI_PROTOCOL_UNKNOWN)
snprintf(buf, buf_len, "%s.%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol),
ndpi_get_proto_name(ndpi_str, proto.app_protocol));
else
snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.master_protocol));
} else
snprintf(buf, buf_len, "%s", ndpi_get_proto_name(ndpi_str, proto.app_protocol));
return(buf);
}
/* ****************************************************** */
int ndpi_is_custom_category(ndpi_protocol_category_t category) {
switch (category) {
case NDPI_PROTOCOL_CATEGORY_CUSTOM_1:
case NDPI_PROTOCOL_CATEGORY_CUSTOM_2:
case NDPI_PROTOCOL_CATEGORY_CUSTOM_3:
case NDPI_PROTOCOL_CATEGORY_CUSTOM_4:
case NDPI_PROTOCOL_CATEGORY_CUSTOM_5:
return(1);
break;
default:
return(0);
break;
}
}
/* ****************************************************** */
void ndpi_category_set_name(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol_category_t category,
char *name) {
if(!name)
return;
switch (category) {
case NDPI_PROTOCOL_CATEGORY_CUSTOM_1:
snprintf(ndpi_str->custom_category_labels[0], CUSTOM_CATEGORY_LABEL_LEN, "%s", name);
break;
case NDPI_PROTOCOL_CATEGORY_CUSTOM_2:
snprintf(ndpi_str->custom_category_labels[1], CUSTOM_CATEGORY_LABEL_LEN, "%s", name);
break;
case NDPI_PROTOCOL_CATEGORY_CUSTOM_3:
snprintf(ndpi_str->custom_category_labels[2], CUSTOM_CATEGORY_LABEL_LEN, "%s", name);
break;
case NDPI_PROTOCOL_CATEGORY_CUSTOM_4:
snprintf(ndpi_str->custom_category_labels[3], CUSTOM_CATEGORY_LABEL_LEN, "%s", name);
break;
case NDPI_PROTOCOL_CATEGORY_CUSTOM_5:
snprintf(ndpi_str->custom_category_labels[4], CUSTOM_CATEGORY_LABEL_LEN, "%s", name);
break;
default:
break;
}
}
/* ****************************************************** */
const char *ndpi_category_get_name(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol_category_t category) {
if((!ndpi_str) || (category >= NDPI_PROTOCOL_NUM_CATEGORIES)) {
static char b[24];
if(!ndpi_str)
snprintf(b, sizeof(b), "NULL nDPI");
else
snprintf(b, sizeof(b), "Invalid category %d", (int) category);
return(b);
}
if((category >= NDPI_PROTOCOL_CATEGORY_CUSTOM_1) && (category <= NDPI_PROTOCOL_CATEGORY_CUSTOM_5)) {
switch (category) {
case NDPI_PROTOCOL_CATEGORY_CUSTOM_1:
return(ndpi_str->custom_category_labels[0]);
case NDPI_PROTOCOL_CATEGORY_CUSTOM_2:
return(ndpi_str->custom_category_labels[1]);
case NDPI_PROTOCOL_CATEGORY_CUSTOM_3:
return(ndpi_str->custom_category_labels[2]);
case NDPI_PROTOCOL_CATEGORY_CUSTOM_4:
return(ndpi_str->custom_category_labels[3]);
case NDPI_PROTOCOL_CATEGORY_CUSTOM_5:
return(ndpi_str->custom_category_labels[4]);
case NDPI_PROTOCOL_NUM_CATEGORIES:
return("Code should not use this internal constant");
default:
return("Unspecified");
}
} else
return(categories[category]);
}
/* ****************************************************** */
ndpi_protocol_category_t ndpi_get_proto_category(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol proto) {
if(proto.category != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)
return(proto.category);
/* simple rule: sub protocol first, master after */
else if((proto.master_protocol == NDPI_PROTOCOL_UNKNOWN) ||
(ndpi_str->proto_defaults[proto.app_protocol].protoCategory != NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)) {
if(proto.app_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS))
return(ndpi_str->proto_defaults[proto.app_protocol].protoCategory);
} else if(proto.master_protocol < (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS))
return(ndpi_str->proto_defaults[proto.master_protocol].protoCategory);
return(NDPI_PROTOCOL_CATEGORY_UNSPECIFIED);
}
/* ****************************************************** */
char *ndpi_get_proto_name(struct ndpi_detection_module_struct *ndpi_str,
u_int16_t proto_id) {
if((proto_id >= ndpi_str->ndpi_num_supported_protocols) ||
(proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) ||
(ndpi_str->proto_defaults[proto_id].protoName == NULL))
proto_id = NDPI_PROTOCOL_UNKNOWN;
return(ndpi_str->proto_defaults[proto_id].protoName);
}
/* ****************************************************** */
ndpi_protocol_breed_t ndpi_get_proto_breed(struct ndpi_detection_module_struct *ndpi_str,
u_int16_t proto_id) {
if((proto_id >= ndpi_str->ndpi_num_supported_protocols) ||
(proto_id >= (NDPI_MAX_SUPPORTED_PROTOCOLS + NDPI_MAX_NUM_CUSTOM_PROTOCOLS)) ||
(ndpi_str->proto_defaults[proto_id].protoName == NULL))
proto_id = NDPI_PROTOCOL_UNKNOWN;
return(ndpi_str->proto_defaults[proto_id].protoBreed);
}
/* ****************************************************** */
char *ndpi_get_proto_breed_name(struct ndpi_detection_module_struct *ndpi_str,
ndpi_protocol_breed_t breed_id) {
switch (breed_id) {
case NDPI_PROTOCOL_SAFE:
return("Safe");
break;
case NDPI_PROTOCOL_ACCEPTABLE:
return("Acceptable");
break;
case NDPI_PROTOCOL_FUN:
return("Fun");
break;
case NDPI_PROTOCOL_UNSAFE:
return("Unsafe");
break;
case NDPI_PROTOCOL_POTENTIALLY_DANGEROUS:
return("Potentially Dangerous");
break;
case NDPI_PROTOCOL_DANGEROUS:
return("Dangerous");
break;
case NDPI_PROTOCOL_UNRATED:
default:
return("Unrated");
break;
}
}
/* ****************************************************** */
int ndpi_get_protocol_id(struct ndpi_detection_module_struct *ndpi_str, char *proto) {
int i;
for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++)
if(strcasecmp(proto, ndpi_str->proto_defaults[i].protoName) == 0)
return(i);
return(-1);
}
/* ****************************************************** */
int ndpi_get_category_id(struct ndpi_detection_module_struct *ndpi_str, char *cat) {
int i;
for (i = 0; i < NDPI_PROTOCOL_NUM_CATEGORIES; i++) {
const char *name = ndpi_category_get_name(ndpi_str, i);
if(strcasecmp(cat, name) == 0)
return(i);
}
return(-1);
}
/* ****************************************************** */
void ndpi_dump_protocols(struct ndpi_detection_module_struct *ndpi_str) {
int i;
for (i = 0; i < (int) ndpi_str->ndpi_num_supported_protocols; i++)
printf("%3d %-22s %-8s %-12s %s\n", i, ndpi_str->proto_defaults[i].protoName,
ndpi_get_l4_proto_name(ndpi_get_l4_proto_info(ndpi_str, i)),
ndpi_get_proto_breed_name(ndpi_str, ndpi_str->proto_defaults[i].protoBreed),
ndpi_category_get_name(ndpi_str, ndpi_str->proto_defaults[i].protoCategory));
}
/* ****************************************************** */
/*
* Find the first occurrence of find in s, where the search is limited to the
* first slen characters of s.
*/
char *ndpi_strnstr(const char *s, const char *find, size_t slen) {
char c;
size_t len;
if((c = *find++) != '\0') {
len = strnlen(find, slen);
do {
char sc;
do {
if(slen-- < 1 || (sc = *s++) == '\0')
return(NULL);
} while (sc != c);
if(len > slen)
return(NULL);
} while (strncmp(s, find, len) != 0);
s--;
}
return((char *) s);
}
/* ****************************************************** */
/*
* Same as ndpi_strnstr but case-insensitive
*/
char *ndpi_strncasestr(const char *s, const char *find, size_t slen) {
char c;
size_t len;
if((c = *find++) != '\0') {
len = strlen(find);
do {
char sc;
do {
if(slen-- < 1 || (sc = *s++) == '\0')
return(NULL);
} while (sc != c);
if(len > slen)
return(NULL);
} while (strncasecmp(s, find, len) != 0);
s--;
}
return((char *) s);
}
/* ****************************************************** */
int ndpi_match_prefix(const u_int8_t *payload,
size_t payload_len, const char *str, size_t str_len) {
int rc = str_len <= payload_len ? memcmp(payload, str, str_len) == 0 : 0;
return(rc);
}
/* ****************************************************** */
int ndpi_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str, char *string_to_match,
u_int string_to_match_len, ndpi_protocol_match_result *ret_match,
u_int8_t is_host_match) {
AC_TEXT_t ac_input_text;
ndpi_automa *automa = is_host_match ? &ndpi_str->host_automa : &ndpi_str->content_automa;
AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED};
int rc;
if((automa->ac_automa == NULL) || (string_to_match_len == 0))
return(NDPI_PROTOCOL_UNKNOWN);
if(!automa->ac_automa_finalized) {
printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__);
return(0); /* No matches */
}
ac_input_text.astring = string_to_match, ac_input_text.length = string_to_match_len;
rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match);
/*
As ac_automata_search can detect partial matches and continue the search process
in case rc == 0 (i.e. no match), we need to check if there is a partial match
and in this case return it
*/
if((rc == 0) && (match.number != 0))
rc = 1;
/* We need to take into account also rc == 0 that is used for partial matches */
ret_match->protocol_id = match.number, ret_match->protocol_category = match.category,
ret_match->protocol_breed = match.breed;
return(rc ? match.number : 0);
}
/* **************************************** */
static u_int8_t ndpi_is_more_generic_protocol(u_int16_t previous_proto, u_int16_t new_proto) {
/* Sometimes certificates are more generic than previously identified protocols */
if((previous_proto == NDPI_PROTOCOL_UNKNOWN) || (previous_proto == new_proto))
return(0);
switch (previous_proto) {
case NDPI_PROTOCOL_WHATSAPP_CALL:
case NDPI_PROTOCOL_WHATSAPP_FILES:
if(new_proto == NDPI_PROTOCOL_WHATSAPP)
return(1);
}
return(0);
}
/* ****************************************************** */
static u_int16_t ndpi_automa_match_string_subprotocol(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow, char *string_to_match,
u_int string_to_match_len, u_int16_t master_protocol_id,
ndpi_protocol_match_result *ret_match, u_int8_t is_host_match) {
int matching_protocol_id;
struct ndpi_packet_struct *packet = &flow->packet;
matching_protocol_id =
ndpi_match_string_subprotocol(ndpi_str, string_to_match, string_to_match_len, ret_match, is_host_match);
#ifdef DEBUG
{
char m[256];
int len = ndpi_min(sizeof(m), string_to_match_len);
strncpy(m, string_to_match, len);
m[len] = '\0';
NDPI_LOG_DBG2(ndpi_str, "[NDPI] ndpi_match_host_subprotocol(%s): %s\n", m,
ndpi_str->proto_defaults[matching_protocol_id].protoName);
}
#endif
if((matching_protocol_id != NDPI_PROTOCOL_UNKNOWN) &&
(!ndpi_is_more_generic_protocol(packet->detected_protocol_stack[0], matching_protocol_id))) {
/* Move the protocol on slot 0 down one position */
packet->detected_protocol_stack[1] = master_protocol_id,
packet->detected_protocol_stack[0] = matching_protocol_id;
flow->detected_protocol_stack[0] = packet->detected_protocol_stack[0],
flow->detected_protocol_stack[1] = packet->detected_protocol_stack[1];
if(flow->category == NDPI_PROTOCOL_CATEGORY_UNSPECIFIED)
flow->category = ret_match->protocol_category;
return(packet->detected_protocol_stack[0]);
}
#ifdef DEBUG
string_to_match[string_to_match_len] = '\0';
NDPI_LOG_DBG2(ndpi_str, "[NTOP] Unable to find a match for '%s'\n", string_to_match);
#endif
ret_match->protocol_id = NDPI_PROTOCOL_UNKNOWN, ret_match->protocol_category = NDPI_PROTOCOL_CATEGORY_UNSPECIFIED,
ret_match->protocol_breed = NDPI_PROTOCOL_UNRATED;
return(NDPI_PROTOCOL_UNKNOWN);
}
/* ****************************************************** */
u_int16_t ndpi_match_host_subprotocol(struct ndpi_detection_module_struct *ndpi_str, struct ndpi_flow_struct *flow,
char *string_to_match, u_int string_to_match_len,
ndpi_protocol_match_result *ret_match, u_int16_t master_protocol_id) {
u_int16_t rc = ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len,
master_protocol_id, ret_match, 1);
ndpi_protocol_category_t id = ret_match->protocol_category;
if(ndpi_get_custom_category_match(ndpi_str, string_to_match, string_to_match_len, &id) != -1) {
/* if(id != -1) */ {
flow->category = ret_match->protocol_category = id;
rc = master_protocol_id;
}
}
return(rc);
}
/* **************************************** */
int ndpi_match_hostname_protocol(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow,
u_int16_t master_protocol, char *name, u_int name_len) {
ndpi_protocol_match_result ret_match;
u_int16_t subproto, what_len;
char *what;
if((name_len > 2) && (name[0] == '*') && (name[1] == '.'))
what = &name[1], what_len = name_len - 1;
else
what = name, what_len = name_len;
subproto = ndpi_match_host_subprotocol(ndpi_struct, flow, what, what_len, &ret_match, master_protocol);
if(subproto != NDPI_PROTOCOL_UNKNOWN) {
ndpi_set_detected_protocol(ndpi_struct, flow, subproto, master_protocol);
ndpi_int_change_category(ndpi_struct, flow, ret_match.protocol_category);
return(1);
} else
return(0);
}
/* ****************************************************** */
u_int16_t ndpi_match_content_subprotocol(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow,
char *string_to_match, u_int string_to_match_len,
ndpi_protocol_match_result *ret_match,
u_int16_t master_protocol_id) {
return(ndpi_automa_match_string_subprotocol(ndpi_str, flow, string_to_match, string_to_match_len,
master_protocol_id, ret_match, 0));
}
/* ****************************************************** */
int ndpi_match_bigram(struct ndpi_detection_module_struct *ndpi_str,
ndpi_automa *automa, char *bigram_to_match) {
AC_TEXT_t ac_input_text;
AC_REP_t match = {NDPI_PROTOCOL_UNKNOWN, NDPI_PROTOCOL_CATEGORY_UNSPECIFIED, NDPI_PROTOCOL_UNRATED};
int rc;
if((automa->ac_automa == NULL) || (bigram_to_match == NULL))
return(-1);
if(!automa->ac_automa_finalized) {
printf("[%s:%d] [NDPI] Internal error: please call ndpi_finalize_initalization()\n", __FILE__, __LINE__);
return(0); /* No matches */
}
ac_input_text.astring = bigram_to_match, ac_input_text.length = 2;
rc = ac_automata_search(((AC_AUTOMATA_t *) automa->ac_automa), &ac_input_text, &match);
/*
As ac_automata_search can detect partial matches and continue the search process
in case rc == 0 (i.e. no match), we need to check if there is a partial match
and in this case return it
*/
if((rc == 0) && (match.number != 0))
rc = 1;
return(rc ? match.number : 0);
}
/* ****************************************************** */
void ndpi_free_flow(struct ndpi_flow_struct *flow) {
if(flow) {
if(flow->http.url)
ndpi_free(flow->http.url);
if(flow->http.content_type)
ndpi_free(flow->http.content_type);
if(flow->http.user_agent)
ndpi_free(flow->http.user_agent);
if(flow->kerberos_buf.pktbuf)
ndpi_free(flow->kerberos_buf.pktbuf);
if(flow_is_proto(flow, NDPI_PROTOCOL_TLS)) {
if(flow->protos.stun_ssl.ssl.server_names)
ndpi_free(flow->protos.stun_ssl.ssl.server_names);
if(flow->protos.stun_ssl.ssl.alpn)
ndpi_free(flow->protos.stun_ssl.ssl.alpn);
if(flow->protos.stun_ssl.ssl.tls_supported_versions)
ndpi_free(flow->protos.stun_ssl.ssl.tls_supported_versions);
if(flow->protos.stun_ssl.ssl.issuerDN)
ndpi_free(flow->protos.stun_ssl.ssl.issuerDN);
if(flow->protos.stun_ssl.ssl.subjectDN)
ndpi_free(flow->protos.stun_ssl.ssl.subjectDN);
if(flow->l4.tcp.tls.srv_cert_fingerprint_ctx)
ndpi_free(flow->l4.tcp.tls.srv_cert_fingerprint_ctx);
if(flow->protos.stun_ssl.ssl.encrypted_sni.esni)
ndpi_free(flow->protos.stun_ssl.ssl.encrypted_sni.esni);
}
if(flow->l4_proto == IPPROTO_TCP) {
if(flow->l4.tcp.tls.message.buffer)
ndpi_free(flow->l4.tcp.tls.message.buffer);
}
ndpi_free(flow);
}
}
/* ****************************************************** */
char *ndpi_revision() {
return(NDPI_GIT_RELEASE);
}
/* ****************************************************** */
#ifdef WIN32
/* https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows */
int gettimeofday(struct timeval *tp, struct timezone *tzp) {
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
static const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t) file_time.dwLowDateTime);
time += ((uint64_t) file_time.dwHighDateTime) << 32;
tp->tv_sec = (long) ((time - EPOCH) / 10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
return(0);
}
#endif
int NDPI_BITMASK_COMPARE(NDPI_PROTOCOL_BITMASK a, NDPI_PROTOCOL_BITMASK b) {
int i;
for (i = 0; i < NDPI_NUM_FDS_BITS; i++) {
if(a.fds_bits[i] & b.fds_bits[i])
return(1);
}
return(0);
}
#ifdef CODE_UNUSED
int NDPI_BITMASK_IS_EMPTY(NDPI_PROTOCOL_BITMASK a) {
int i;
for (i = 0; i < NDPI_NUM_FDS_BITS; i++)
if(a.fds_bits[i] != 0)
return(0);
return(1);
}
void NDPI_DUMP_BITMASK(NDPI_PROTOCOL_BITMASK a) {
int i;
for (i = 0; i < NDPI_NUM_FDS_BITS; i++)
printf("[%d=%u]", i, a.fds_bits[i]);
printf("\n");
}
#endif
u_int16_t ndpi_get_api_version() {
return(NDPI_API_VERSION);
}
ndpi_proto_defaults_t *ndpi_get_proto_defaults(struct ndpi_detection_module_struct *ndpi_str) {
return(ndpi_str->proto_defaults);
}
u_int ndpi_get_ndpi_num_supported_protocols(struct ndpi_detection_module_struct *ndpi_str) {
return(ndpi_str->ndpi_num_supported_protocols);
}
u_int ndpi_get_ndpi_num_custom_protocols(struct ndpi_detection_module_struct *ndpi_str) {
return(ndpi_str->ndpi_num_custom_protocols);
}
u_int ndpi_get_ndpi_detection_module_size() {
return(sizeof(struct ndpi_detection_module_struct));
}
void ndpi_set_log_level(struct ndpi_detection_module_struct *ndpi_str, u_int l){
ndpi_str->ndpi_log_level = l;
}
/* ******************************************************************** */
/* LRU cache */
struct ndpi_lru_cache *ndpi_lru_cache_init(u_int32_t num_entries) {
struct ndpi_lru_cache *c = (struct ndpi_lru_cache *) ndpi_malloc(sizeof(struct ndpi_lru_cache));
if(!c)
return(NULL);
c->entries = (struct ndpi_lru_cache_entry *) ndpi_calloc(num_entries, sizeof(struct ndpi_lru_cache_entry));
if(!c->entries) {
ndpi_free(c);
return(NULL);
} else
c->num_entries = num_entries;
return(c);
}
void ndpi_lru_free_cache(struct ndpi_lru_cache *c) {
ndpi_free(c->entries);
ndpi_free(c);
}
u_int8_t ndpi_lru_find_cache(struct ndpi_lru_cache *c, u_int32_t key,
u_int16_t *value, u_int8_t clean_key_when_found) {
u_int32_t slot = key % c->num_entries;
if(c->entries[slot].is_full) {
*value = c->entries[slot].value;
if(clean_key_when_found)
c->entries[slot].is_full = 0;
return(1);
} else
return(0);
}
void ndpi_lru_add_to_cache(struct ndpi_lru_cache *c, u_int32_t key, u_int16_t value) {
u_int32_t slot = key % c->num_entries;
c->entries[slot].is_full = 1, c->entries[slot].key = key, c->entries[slot].value = value;
}
/* ******************************************************************** */
/*
This function tells if it's possible to further dissect a given flow
0 - All possible dissection has been completed
1 - Additional dissection is possible
*/
u_int8_t ndpi_extra_dissection_possible(struct ndpi_detection_module_struct *ndpi_str,
struct ndpi_flow_struct *flow) {
u_int16_t proto =
flow->detected_protocol_stack[1] ? flow->detected_protocol_stack[1] : flow->detected_protocol_stack[0];
#if 0
printf("[DEBUG] %s(%u.%u): %u\n", __FUNCTION__,
flow->detected_protocol_stack[0],
flow->detected_protocol_stack[1],
proto);
#endif
switch (proto) {
case NDPI_PROTOCOL_TLS:
if(!flow->l4.tcp.tls.certificate_processed)
return(1); /* TODO: add check for TLS 1.3 */
break;
case NDPI_PROTOCOL_HTTP:
if((flow->host_server_name[0] == '\0') || (flow->http.response_status_code == 0))
return(1);
break;
case NDPI_PROTOCOL_DNS:
if(flow->protos.dns.num_answers == 0)
return(1);
break;
case NDPI_PROTOCOL_FTP_CONTROL:
case NDPI_PROTOCOL_MAIL_POP:
case NDPI_PROTOCOL_MAIL_IMAP:
case NDPI_PROTOCOL_MAIL_SMTP:
if(flow->protos.ftp_imap_pop_smtp.password[0] == '\0')
return(1);
break;
case NDPI_PROTOCOL_SSH:
if((flow->protos.ssh.hassh_client[0] == '\0') || (flow->protos.ssh.hassh_server[0] == '\0'))
return(1);
break;
case NDPI_PROTOCOL_TELNET:
if(!flow->protos.telnet.password_detected)
return(1);
break;
}
return(0);
}
/* ******************************************************************** */
const char *ndpi_get_l4_proto_name(ndpi_l4_proto_info proto) {
switch (proto) {
case ndpi_l4_proto_unknown:
return("");
break;
case ndpi_l4_proto_tcp_only:
return("TCP");
break;
case ndpi_l4_proto_udp_only:
return("UDP");
break;
case ndpi_l4_proto_tcp_and_udp:
return("TCP/UDP");
break;
}
return("");
}
/* ******************************************************************** */
ndpi_l4_proto_info ndpi_get_l4_proto_info(struct ndpi_detection_module_struct *ndpi_struct,
u_int16_t ndpi_proto_id) {
if(ndpi_proto_id < ndpi_struct->ndpi_num_supported_protocols) {
u_int16_t idx = ndpi_struct->proto_defaults[ndpi_proto_id].protoIdx;
NDPI_SELECTION_BITMASK_PROTOCOL_SIZE bm = ndpi_struct->callback_buffer[idx].ndpi_selection_bitmask;
if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP)
return(ndpi_l4_proto_tcp_only);
else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_UDP)
return(ndpi_l4_proto_udp_only);
else if(bm & NDPI_SELECTION_BITMASK_PROTOCOL_INT_TCP_OR_UDP)
return(ndpi_l4_proto_tcp_and_udp);
}
return(ndpi_l4_proto_unknown); /* default */
}
/* ******************************************************************** */
ndpi_ptree_t *ndpi_ptree_create(void) {
ndpi_ptree_t *tree = (ndpi_ptree_t *) ndpi_malloc(sizeof(ndpi_ptree_t));
if(tree) {
tree->v4 = ndpi_New_Patricia(32);
tree->v6 = ndpi_New_Patricia(128);
if((!tree->v4) || (!tree->v6)) {
ndpi_ptree_destroy(tree);
return(NULL);
}
}
return(tree);
}
/* ******************************************************************** */
void ndpi_ptree_destroy(ndpi_ptree_t *tree) {
if(tree) {
if(tree->v4)
ndpi_Destroy_Patricia(tree->v4, free_ptree_data);
if(tree->v6)
ndpi_Destroy_Patricia(tree->v6, free_ptree_data);
ndpi_free(tree);
}
}
/* ******************************************************************** */
int ndpi_ptree_insert(ndpi_ptree_t *tree, const ndpi_ip_addr_t *addr,
u_int8_t bits, uint user_data) {
u_int8_t is_v6 = ndpi_is_ipv6(addr);
patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4;
prefix_t prefix;
patricia_node_t *node;
if(bits > ptree->maxbits)
return(-1);
if(is_v6)
fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits);
else
fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits);
/* Verify that the node does not already exist */
node = ndpi_patricia_search_best(ptree, &prefix);
if(node && (node->prefix->bitlen == bits))
return(-2);
node = ndpi_patricia_lookup(ptree, &prefix);
if(node != NULL) {
node->value.uv.user_value = user_data, node->value.uv.additional_user_value = 0;
return(0);
}
return(-3);
}
/* ******************************************************************** */
int ndpi_ptree_match_addr(ndpi_ptree_t *tree,
const ndpi_ip_addr_t *addr, uint *user_data) {
u_int8_t is_v6 = ndpi_is_ipv6(addr);
patricia_tree_t *ptree = is_v6 ? tree->v6 : tree->v4;
prefix_t prefix;
patricia_node_t *node;
int bits = ptree->maxbits;
if(is_v6)
fill_prefix_v6(&prefix, (const struct in6_addr *) &addr->ipv6, bits, ptree->maxbits);
else
fill_prefix_v4(&prefix, (const struct in_addr *) &addr->ipv4, bits, ptree->maxbits);
node = ndpi_patricia_search_best(ptree, &prefix);
if(node) {
*user_data = node->value.uv.user_value;
return(0);
}
return(-1);
}
/* ******************************************************************** */
void ndpi_md5(const u_char *data, size_t data_len, u_char hash[16]) {
ndpi_MD5_CTX ctx;
ndpi_MD5Init(&ctx);
ndpi_MD5Update(&ctx, data, data_len);
ndpi_MD5Final(hash, &ctx);
}
| ./CrossVul/dataset_final_sorted/CWE-125/c/bad_4214_0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.