/********************************************************************** object.c - $Author$ created at: Thu Jul 15 12:01:24 JST 1993 Copyright (C) 1993-2007 Yukihiro Matsumoto Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan **********************************************************************/ #include "ruby/ruby.h" #include "ruby/st.h" #include "ruby/util.h" #include "debug.h" #include #include #include #include #include VALUE rb_cBasicObject; VALUE rb_mKernel; VALUE rb_cObject; VALUE rb_cModule; VALUE rb_cClass; VALUE rb_cData; VALUE rb_cNilClass; VALUE rb_cTrueClass; VALUE rb_cFalseClass; static ID id_eq, id_eql, id_match, id_inspect, id_init_copy; /* * call-seq: * obj === other => true or false * * Case Equality---For class Object, effectively the same * as calling #==, but typically overridden by descendents * to provide meaningful semantics in case statements. */ VALUE rb_equal(VALUE obj1, VALUE obj2) { VALUE result; if (obj1 == obj2) return Qtrue; result = rb_funcall(obj1, id_eq, 1, obj2); if (RTEST(result)) return Qtrue; return Qfalse; } int rb_eql(VALUE obj1, VALUE obj2) { return RTEST(rb_funcall(obj1, id_eql, 1, obj2)); } /* * call-seq: * obj == other => true or false * obj.equal?(other) => true or false * obj.eql?(other) => true or false * * Equality---At the Object level, == returns * true only if obj and other are the * same object. Typically, this method is overridden in descendent * classes to provide class-specific meaning. * * Unlike ==, the equal? method should never be * overridden by subclasses: it is used to determine object identity * (that is, a.equal?(b) iff a is the same * object as b). * * The eql? method returns true if * obj and anObject have the same value. Used by * Hash to test members for equality. For objects of * class Object, eql? is synonymous with * ==. Subclasses normally continue this tradition, but * there are exceptions. Numeric types, for example, * perform type conversion across ==, but not across * eql?, so: * * 1 == 1.0 #=> true * 1.eql? 1.0 #=> false */ VALUE rb_obj_equal(VALUE obj1, VALUE obj2) { if (obj1 == obj2) return Qtrue; return Qfalse; } /* * call-seq: * !obj => true or false * * Boolean negate. */ VALUE rb_obj_not(VALUE obj) { return RTEST(obj) ? Qfalse : Qtrue; } /* * call-seq: * obj != other => true or false * * Returns true if two objects are not-equal, otherwise false. */ VALUE rb_obj_not_equal(VALUE obj1, VALUE obj2) { VALUE result = rb_funcall(obj1, id_eq, 1, obj2); return RTEST(result) ? Qfalse : Qtrue; } VALUE rb_class_real(VALUE cl) { if (cl == 0) return 0; while ((RBASIC(cl)->flags & FL_SINGLETON) || BUILTIN_TYPE(cl) == T_ICLASS) { cl = RCLASS_SUPER(cl); } return cl; } /* * call-seq: * obj.class => class * * Returns the class of obj, now preferred over * Object#type, as an object's type in Ruby is only * loosely tied to that object's class. This method must always be * called with an explicit receiver, as class is also a * reserved word in Ruby. * * 1.class #=> Fixnum * self.class #=> Object */ VALUE rb_obj_class(VALUE obj) { return rb_class_real(CLASS_OF(obj)); } static void init_copy(VALUE dest, VALUE obj) { if (OBJ_FROZEN(dest)) { rb_raise(rb_eTypeError, "[bug] frozen object (%s) allocated", rb_obj_classname(dest)); } RBASIC(dest)->flags &= ~(T_MASK|FL_EXIVAR); RBASIC(dest)->flags |= RBASIC(obj)->flags & (T_MASK|FL_EXIVAR|FL_TAINT|FL_UNTRUSTED); rb_copy_generic_ivar(dest, obj); rb_gc_copy_finalizer(dest, obj); switch (TYPE(obj)) { case T_OBJECT: if (!(RBASIC(dest)->flags & ROBJECT_EMBED) && ROBJECT_IVPTR(dest)) { xfree(ROBJECT_IVPTR(dest)); ROBJECT(dest)->as.heap.ivptr = 0; ROBJECT(dest)->as.heap.numiv = 0; ROBJECT(dest)->as.heap.iv_index_tbl = 0; } if (RBASIC(obj)->flags & ROBJECT_EMBED) { MEMCPY(ROBJECT(dest)->as.ary, ROBJECT(obj)->as.ary, VALUE, ROBJECT_EMBED_LEN_MAX); RBASIC(dest)->flags |= ROBJECT_EMBED; } else { long len = ROBJECT(obj)->as.heap.numiv; VALUE *ptr = ALLOC_N(VALUE, len); MEMCPY(ptr, ROBJECT(obj)->as.heap.ivptr, VALUE, len); ROBJECT(dest)->as.heap.ivptr = ptr; ROBJECT(dest)->as.heap.numiv = len; ROBJECT(dest)->as.heap.iv_index_tbl = ROBJECT(obj)->as.heap.iv_index_tbl; RBASIC(dest)->flags &= ~ROBJECT_EMBED; } break; case T_CLASS: case T_MODULE: if (RCLASS_IV_TBL(dest)) { st_free_table(RCLASS_IV_TBL(dest)); RCLASS_IV_TBL(dest) = 0; } if (RCLASS_IV_TBL(obj)) { RCLASS_IV_TBL(dest) = st_copy(RCLASS_IV_TBL(obj)); } break; } rb_funcall(dest, id_init_copy, 1, obj); } /* * call-seq: * obj.clone -> an_object * * Produces a shallow copy of obj---the instance variables of * obj are copied, but not the objects they reference. Copies * the frozen and tainted state of obj. See also the discussion * under Object#dup. * * class Klass * attr_accessor :str * end * s1 = Klass.new #=> # * s1.str = "Hello" #=> "Hello" * s2 = s1.clone #=> # * s2.str[1,4] = "i" #=> "i" * s1.inspect #=> "#" * s2.inspect #=> "#" * * This method may have class-specific behavior. If so, that * behavior will be documented under the #+initialize_copy+ method of * the class. */ VALUE rb_obj_clone(VALUE obj) { VALUE clone; if (rb_special_const_p(obj)) { rb_raise(rb_eTypeError, "can't clone %s", rb_obj_classname(obj)); } clone = rb_obj_alloc(rb_obj_class(obj)); RBASIC(clone)->klass = rb_singleton_class_clone(obj); RBASIC(clone)->flags = (RBASIC(obj)->flags | FL_TEST(clone, FL_TAINT) | FL_TEST(clone, FL_UNTRUSTED)) & ~(FL_FREEZE|FL_FINALIZE); init_copy(clone, obj); RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE; return clone; } /* * call-seq: * obj.dup -> an_object * * Produces a shallow copy of obj---the instance variables of * obj are copied, but not the objects they reference. * dup copies the tainted state of obj. See also * the discussion under Object#clone. In general, * clone and dup may have different semantics * in descendent classes. While clone is used to duplicate * an object, including its internal state, dup typically * uses the class of the descendent object to create the new instance. * * This method may have class-specific behavior. If so, that * behavior will be documented under the #+initialize_copy+ method of * the class. */ VALUE rb_obj_dup(VALUE obj) { VALUE dup; if (rb_special_const_p(obj)) { rb_raise(rb_eTypeError, "can't dup %s", rb_obj_classname(obj)); } dup = rb_obj_alloc(rb_obj_class(obj)); init_copy(dup, obj); return dup; } /* :nodoc: */ VALUE rb_obj_init_copy(VALUE obj, VALUE orig) { if (obj == orig) return obj; rb_check_frozen(obj); if (TYPE(obj) != TYPE(orig) || rb_obj_class(obj) != rb_obj_class(orig)) { rb_raise(rb_eTypeError, "initialize_copy should take same class object"); } return obj; } /* * call-seq: * obj.to_s => string * * Returns a string representing obj. The default * to_s prints the object's class and an encoding of the * object id. As a special case, the top-level object that is the * initial execution context of Ruby programs returns ``main.'' */ VALUE rb_any_to_s(VALUE obj) { const char *cname = rb_obj_classname(obj); VALUE str; str = rb_sprintf("#<%s:%p>", cname, (void*)obj); OBJ_INFECT(str, obj); return str; } VALUE rb_inspect(VALUE obj) { return rb_obj_as_string(rb_funcall(obj, id_inspect, 0, 0)); } static int inspect_i(ID id, VALUE value, VALUE str) { VALUE str2; const char *ivname; /* need not to show internal data */ if (CLASS_OF(value) == 0) return ST_CONTINUE; if (!rb_is_instance_id(id)) return ST_CONTINUE; if (RSTRING_PTR(str)[0] == '-') { /* first element */ RSTRING_PTR(str)[0] = '#'; rb_str_cat2(str, " "); } else { rb_str_cat2(str, ", "); } ivname = rb_id2name(id); rb_str_cat2(str, ivname); rb_str_cat2(str, "="); str2 = rb_inspect(value); rb_str_append(str, str2); OBJ_INFECT(str, str2); return ST_CONTINUE; } static VALUE inspect_obj(VALUE obj, VALUE str, int recur) { if (recur) { rb_str_cat2(str, " ..."); } else { rb_ivar_foreach(obj, inspect_i, str); } rb_str_cat2(str, ">"); RSTRING_PTR(str)[0] = '#'; OBJ_INFECT(str, obj); return str; } /* * call-seq: * obj.inspect => string * * Returns a string containing a human-readable representation of * obj. If not overridden, uses the to_s method to * generate the string. * * [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]" * Time.new.inspect #=> "2008-03-08 19:43:39 +0900" */ static VALUE rb_obj_inspect(VALUE obj) { if (TYPE(obj) == T_OBJECT) { int has_ivar = 0; VALUE *ptr = ROBJECT_IVPTR(obj); long len = ROBJECT_NUMIV(obj); long i; for (i = 0; i < len; i++) { if (ptr[i] != Qundef) { has_ivar = 1; break; } } if (has_ivar) { VALUE str; const char *c = rb_obj_classname(obj); str = rb_sprintf("-<%s:%p", c, (void*)obj); return rb_exec_recursive(inspect_obj, obj, str); } } return rb_funcall(obj, rb_intern("to_s"), 0, 0); } /* * call-seq: * obj.instance_of?(class) => true or false * * Returns true if obj is an instance of the given * class. See also Object#kind_of?. */ VALUE rb_obj_is_instance_of(VALUE obj, VALUE c) { switch (TYPE(c)) { case T_MODULE: case T_CLASS: case T_ICLASS: break; default: rb_raise(rb_eTypeError, "class or module required"); } if (rb_obj_class(obj) == c) return Qtrue; return Qfalse; } /* * call-seq: * obj.is_a?(class) => true or false * obj.kind_of?(class) => true or false * * Returns true if class is the class of * obj, or if class is one of the superclasses of * obj or modules included in obj. * * module M; end * class A * include M * end * class B < A; end * class C < B; end * b = B.new * b.instance_of? A #=> false * b.instance_of? B #=> true * b.instance_of? C #=> false * b.instance_of? M #=> false * b.kind_of? A #=> true * b.kind_of? B #=> true * b.kind_of? C #=> false * b.kind_of? M #=> true */ VALUE rb_obj_is_kind_of(VALUE obj, VALUE c) { VALUE cl = CLASS_OF(obj); switch (TYPE(c)) { case T_MODULE: case T_CLASS: case T_ICLASS: break; default: rb_raise(rb_eTypeError, "class or module required"); } while (cl) { if (cl == c || RCLASS_M_TBL(cl) == RCLASS_M_TBL(c)) return Qtrue; cl = RCLASS_SUPER(cl); } return Qfalse; } /* * call-seq: * obj.tap{|x|...} => obj * * Yields x to the block, and then returns x. * The primary purpose of this method is to "tap into" a method chain, * in order to perform operations on intermediate results within the chain. * * (1..10) .tap {|x| puts "original: #{x.inspect}"} * .to_a .tap {|x| puts "array: #{x.inspect}"} * .select {|x| x%2==0} .tap {|x| puts "evens: #{x.inspect}"} * .map { |x| x*x } .tap {|x| puts "squares: #{x.inspect}"} * */ VALUE rb_obj_tap(VALUE obj) { rb_yield(obj); return obj; } /* * Document-method: inherited * * call-seq: * inherited(subclass) * * Callback invoked whenever a subclass of the current class is created. * * Example: * * class Foo * def self.inherited(subclass) * puts "New subclass: #{subclass}" * end * end * * class Bar < Foo * end * * class Baz < Bar * end * * produces: * * New subclass: Bar * New subclass: Baz */ /* * Document-method: singleton_method_added * * call-seq: * singleton_method_added(symbol) * * Invoked as a callback whenever a singleton method is added to the * receiver. * * module Chatty * def Chatty.singleton_method_added(id) * puts "Adding #{id.id2name}" * end * def self.one() end * def two() end * def Chatty.three() end * end * * produces: * * Adding singleton_method_added * Adding one * Adding three * */ /* * Document-method: singleton_method_removed * * call-seq: * singleton_method_removed(symbol) * * Invoked as a callback whenever a singleton method is removed from * the receiver. * * module Chatty * def Chatty.singleton_method_removed(id) * puts "Removing #{id.id2name}" * end * def self.one() end * def two() end * def Chatty.three() end * class <produces: * * Removing three * Removing one */ /* * Document-method: singleton_method_undefined * * call-seq: * singleton_method_undefined(symbol) * * Invoked as a callback whenever a singleton method is undefined in * the receiver. * * module Chatty * def Chatty.singleton_method_undefined(id) * puts "Undefining #{id.id2name}" * end * def Chatty.one() end * class << self * undef_method(:one) * end * end * * produces: * * Undefining one */ /* * Document-method: included * * call-seq: * included( othermod ) * * Callback invoked whenever the receiver is included in another * module or class. This should be used in preference to * Module.append_features if your code wants to perform some * action when a module is included in another. * * module A * def A.included(mod) * puts "#{self} included in #{mod}" * end * end * module Enumerable * include A * end */ /* * Not documented */ static VALUE rb_obj_dummy(void) { return Qnil; } /* * call-seq: * obj.tainted? => true or false * * Returns true if the object is tainted. */ VALUE rb_obj_tainted(VALUE obj) { if (OBJ_TAINTED(obj)) return Qtrue; return Qfalse; } /* * call-seq: * obj.taint -> obj * * Marks obj as tainted---if the $SAFE level is * set appropriately, many method calls which might alter the running * programs environment will refuse to accept tainted strings. */ VALUE rb_obj_taint(VALUE obj) { rb_secure(4); if (!OBJ_TAINTED(obj)) { if (OBJ_FROZEN(obj)) { rb_error_frozen("object"); } OBJ_TAINT(obj); } return obj; } /* * call-seq: * obj.untaint => obj * * Removes the taint from obj. */ VALUE rb_obj_untaint(VALUE obj) { rb_secure(3); if (OBJ_TAINTED(obj)) { if (OBJ_FROZEN(obj)) { rb_error_frozen("object"); } FL_UNSET(obj, FL_TAINT); } return obj; } /* * call-seq: * obj.untrusted? => true or false * * Returns true if the object is untrusted. */ VALUE rb_obj_untrusted(VALUE obj) { if (OBJ_UNTRUSTED(obj)) return Qtrue; return Qfalse; } /* * call-seq: * obj.untrust -> obj * * Marks obj as untrusted. */ VALUE rb_obj_untrust(VALUE obj) { rb_secure(4); if (!OBJ_UNTRUSTED(obj)) { if (OBJ_FROZEN(obj)) { rb_error_frozen("object"); } OBJ_UNTRUST(obj); } return obj; } /* * call-seq: * obj.trust => obj * * Removes the untrusted mark from obj. */ VALUE rb_obj_trust(VALUE obj) { rb_secure(3); if (OBJ_UNTRUSTED(obj)) { if (OBJ_FROZEN(obj)) { rb_error_frozen("object"); } FL_UNSET(obj, FL_UNTRUSTED); } return obj; } void rb_obj_infect(VALUE obj1, VALUE obj2) { OBJ_INFECT(obj1, obj2); } static st_table *immediate_frozen_tbl = 0; /* * call-seq: * obj.freeze => obj * * Prevents further modifications to obj. A * TypeError will be raised if modification is attempted. * There is no way to unfreeze a frozen object. See also * Object#frozen?. * * a = [ "a", "b", "c" ] * a.freeze * a << "z" * * produces: * * prog.rb:3:in `<<': can't modify frozen array (TypeError) * from prog.rb:3 */ VALUE rb_obj_freeze(VALUE obj) { if (!OBJ_FROZEN(obj)) { if (rb_safe_level() >= 4 && !OBJ_UNTRUSTED(obj)) { rb_raise(rb_eSecurityError, "Insecure: can't freeze object"); } OBJ_FREEZE(obj); if (SPECIAL_CONST_P(obj)) { if (!immediate_frozen_tbl) { immediate_frozen_tbl = st_init_numtable(); } st_insert(immediate_frozen_tbl, obj, (st_data_t)Qtrue); } } return obj; } /* * call-seq: * obj.frozen? => true or false * * Returns the freeze status of obj. * * a = [ "a", "b", "c" ] * a.freeze #=> ["a", "b", "c"] * a.frozen? #=> true */ VALUE rb_obj_frozen_p(VALUE obj) { if (OBJ_FROZEN(obj)) return Qtrue; if (SPECIAL_CONST_P(obj)) { if (!immediate_frozen_tbl) return Qfalse; if (st_lookup(immediate_frozen_tbl, obj, 0)) return Qtrue; } return Qfalse; } /* * Document-class: NilClass * * The class of the singleton object nil. */ /* * call-seq: * nil.to_i => 0 * * Always returns zero. * * nil.to_i #=> 0 */ static VALUE nil_to_i(VALUE obj) { return INT2FIX(0); } /* * call-seq: * nil.to_f => 0.0 * * Always returns zero. * * nil.to_f #=> 0.0 */ static VALUE nil_to_f(VALUE obj) { return DOUBLE2NUM(0.0); } /* * call-seq: * nil.to_s => "" * * Always returns the empty string. */ static VALUE nil_to_s(VALUE obj) { return rb_usascii_str_new(0, 0); } /* * Document-method: to_a * * call-seq: * nil.to_a => [] * * Always returns an empty array. * * nil.to_a #=> [] */ static VALUE nil_to_a(VALUE obj) { return rb_ary_new2(0); } /* * call-seq: * nil.inspect => "nil" * * Always returns the string "nil". */ static VALUE nil_inspect(VALUE obj) { return rb_usascii_str_new2("nil"); } /*********************************************************************** * Document-class: TrueClass * * The global value true is the only instance of class * TrueClass and represents a logically true value in * boolean expressions. The class provides operators allowing * true to be used in logical expressions. */ /* * call-seq: * true.to_s => "true" * * The string representation of true is "true". */ static VALUE true_to_s(VALUE obj) { return rb_usascii_str_new2("true"); } /* * call-seq: * true & obj => true or false * * And---Returns false if obj is * nil or false, true otherwise. */ static VALUE true_and(VALUE obj, VALUE obj2) { return RTEST(obj2)?Qtrue:Qfalse; } /* * call-seq: * true | obj => true * * Or---Returns true. As anObject is an argument to * a method call, it is always evaluated; there is no short-circuit * evaluation in this case. * * true | puts("or") * true || puts("logical or") * * produces: * * or */ static VALUE true_or(VALUE obj, VALUE obj2) { return Qtrue; } /* * call-seq: * true ^ obj => !obj * * Exclusive Or---Returns true if obj is * nil or false, false * otherwise. */ static VALUE true_xor(VALUE obj, VALUE obj2) { return RTEST(obj2)?Qfalse:Qtrue; } /* * Document-class: FalseClass * * The global value false is the only instance of class * FalseClass and represents a logically false value in * boolean expressions. The class provides operators allowing * false to participate correctly in logical expressions. * */ /* * call-seq: * false.to_s => "false" * * 'nuf said... */ static VALUE false_to_s(VALUE obj) { return rb_usascii_str_new2("false"); } /* * call-seq: * false & obj => false * nil & obj => false * * And---Returns false. obj is always * evaluated as it is the argument to a method call---there is no * short-circuit evaluation in this case. */ static VALUE false_and(VALUE obj, VALUE obj2) { return Qfalse; } /* * call-seq: * false | obj => true or false * nil | obj => true or false * * Or---Returns false if obj is * nil or false; true otherwise. */ static VALUE false_or(VALUE obj, VALUE obj2) { return RTEST(obj2)?Qtrue:Qfalse; } /* * call-seq: * false ^ obj => true or false * nil ^ obj => true or false * * Exclusive Or---If obj is nil or * false, returns false; otherwise, returns * true. * */ static VALUE false_xor(VALUE obj, VALUE obj2) { return RTEST(obj2)?Qtrue:Qfalse; } /* * call_seq: * nil.nil? => true * * Only the object nil responds true to nil?. */ static VALUE rb_true(VALUE obj) { return Qtrue; } /* * call_seq: * nil.nil? => true * .nil? => false * * Only the object nil responds true to nil?. */ static VALUE rb_false(VALUE obj) { return Qfalse; } /* * call-seq: * obj =~ other => nil * * Pattern Match---Overridden by descendents (notably * Regexp and String) to provide meaningful * pattern-match semantics. */ static VALUE rb_obj_match(VALUE obj1, VALUE obj2) { return Qnil; } /* * call-seq: * obj !~ other => nil * * Returns true if two objects does not match, using =~ method. */ static VALUE rb_obj_not_match(VALUE obj1, VALUE obj2) { VALUE result = rb_funcall(obj1, id_match, 1, obj2); return RTEST(result) ? Qfalse : Qtrue; } /*********************************************************************** * * Document-class: Module * * A Module is a collection of methods and constants. The * methods in a module may be instance methods or module methods. * Instance methods appear as methods in a class when the module is * included, module methods do not. Conversely, module methods may be * called without creating an encapsulating object, while instance * methods may not. (See Module#module_function) * * In the descriptions that follow, the parameter syml refers * to a symbol, which is either a quoted string or a * Symbol (such as :name). * * module Mod * include Math * CONST = 1 * def meth * # ... * end * end * Mod.class #=> Module * Mod.constants #=> [:CONST, :PI, :E] * Mod.instance_methods #=> [:meth] * */ /* * call-seq: * mod.to_s => string * * Return a string representing this module or class. For basic * classes and modules, this is the name. For singletons, we * show information on the thing we're attached to as well. */ static VALUE rb_mod_to_s(VALUE klass) { if (FL_TEST(klass, FL_SINGLETON)) { VALUE s = rb_usascii_str_new2("#<"); VALUE v = rb_iv_get(klass, "__attached__"); rb_str_cat2(s, "Class:"); switch (TYPE(v)) { case T_CLASS: case T_MODULE: rb_str_append(s, rb_inspect(v)); break; default: rb_str_append(s, rb_any_to_s(v)); break; } rb_str_cat2(s, ">"); return s; } return rb_str_dup(rb_class_name(klass)); } /* * call-seq: * mod.freeze * * Prevents further modifications to mod. */ static VALUE rb_mod_freeze(VALUE mod) { rb_class_name(mod); return rb_obj_freeze(mod); } /* * call-seq: * mod === obj => true or false * * Case Equality---Returns true if anObject is an * instance of mod or one of mod's descendents. Of * limited use for modules, but can be used in case * statements to classify objects by class. */ static VALUE rb_mod_eqq(VALUE mod, VALUE arg) { return rb_obj_is_kind_of(arg, mod); } /* * call-seq: * mod <= other => true, false, or nil * * Returns true if mod is a subclass of other or * is the same as other. Returns * nil if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A arg */ while (arg) { if (RCLASS_M_TBL(arg) == RCLASS_M_TBL(start)) return Qfalse; arg = RCLASS_SUPER(arg); } return Qnil; } /* * call-seq: * mod < other => true, false, or nil * * Returns true if mod is a subclass of other. Returns * nil if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class A= other => true, false, or nil * * Returns true if mod is an ancestor of other, or the * two modules are the same. Returns * nil if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class AA"). * */ static VALUE rb_mod_ge(VALUE mod, VALUE arg) { switch (TYPE(arg)) { case T_MODULE: case T_CLASS: break; default: rb_raise(rb_eTypeError, "compared with non class/module"); } return rb_class_inherited_p(arg, mod); } /* * call-seq: * mod > other => true, false, or nil * * Returns true if mod is an ancestor of other. Returns * nil if there's no relationship between the two. * (Think of the relationship in terms of the class definition: * "class AA"). * */ static VALUE rb_mod_gt(VALUE mod, VALUE arg) { if (mod == arg) return Qfalse; return rb_mod_ge(mod, arg); } /* * call-seq: * mod <=> other_mod => -1, 0, +1, or nil * * Comparison---Returns -1 if mod includes other_mod, 0 if * mod is the same as other_mod, and +1 if mod is * included by other_mod or if mod has no relationship with * other_mod. Returns nil if other_mod is * not a module. */ static VALUE rb_mod_cmp(VALUE mod, VALUE arg) { VALUE cmp; if (mod == arg) return INT2FIX(0); switch (TYPE(arg)) { case T_MODULE: case T_CLASS: break; default: return Qnil; } cmp = rb_class_inherited_p(mod, arg); if (NIL_P(cmp)) return Qnil; if (cmp) { return INT2FIX(-1); } return INT2FIX(1); } static VALUE rb_module_s_alloc(VALUE klass) { VALUE mod = rb_module_new(); RBASIC(mod)->klass = klass; return mod; } static VALUE rb_class_s_alloc(VALUE klass) { return rb_class_boot(0); } /* * call-seq: * Module.new => mod * Module.new {|mod| block } => mod * * Creates a new anonymous module. If a block is given, it is passed * the module object, and the block is evaluated in the context of this * module using module_eval. * * Fred = Module.new do * def meth1 * "hello" * end * def meth2 * "bye" * end * end * a = "my string" * a.extend(Fred) #=> "my string" * a.meth1 #=> "hello" * a.meth2 #=> "bye" */ static VALUE rb_mod_initialize(VALUE module) { extern VALUE rb_mod_module_exec(int argc, VALUE *argv, VALUE mod); if (rb_block_given_p()) { rb_mod_module_exec(1, &module, module); } return Qnil; } /* * call-seq: * Class.new(super_class=Object) => a_class * * Creates a new anonymous (unnamed) class with the given superclass * (or Object if no parameter is given). You can give a * class a name by assigning the class object to a constant. * */ static VALUE rb_class_initialize(int argc, VALUE *argv, VALUE klass) { VALUE super; if (RCLASS_SUPER(klass) != 0) { rb_raise(rb_eTypeError, "already initialized class"); } if (argc == 0) { super = rb_cObject; } else { rb_scan_args(argc, argv, "01", &super); rb_check_inheritable(super); } RCLASS_SUPER(klass) = super; rb_make_metaclass(klass, RBASIC(super)->klass); rb_class_inherited(super, klass); rb_mod_initialize(klass); return klass; } /* * call-seq: * class.allocate() => obj * * Allocates space for a new object of class's class and does not * call initialize on the new instance. The returned object must be an * instance of class. * * klass = Class.new do * def initialize(*args) * @initialized = true * end * * def initialized? * @initialized || false * end * end * * klass.allocate.initialized? #=> false * */ VALUE rb_obj_alloc(VALUE klass) { VALUE obj; if (RCLASS_SUPER(klass) == 0 && klass != rb_cBasicObject) { rb_raise(rb_eTypeError, "can't instantiate uninitialized class"); } if (FL_TEST(klass, FL_SINGLETON)) { rb_raise(rb_eTypeError, "can't create instance of singleton class"); } obj = rb_funcall(klass, ID_ALLOCATOR, 0, 0); if (rb_obj_class(obj) != rb_class_real(klass)) { rb_raise(rb_eTypeError, "wrong instance allocation"); } return obj; } static VALUE rb_class_allocate_instance(VALUE klass) { NEWOBJ(obj, struct RObject); OBJSETUP(obj, klass, T_OBJECT); return (VALUE)obj; } /* * call-seq: * class.new(args, ...) => obj * * Calls allocate to create a new object of * class's class, then invokes that object's * initialize method, passing it args. * This is the method that ends up getting called whenever * an object is constructed using .new. * */ VALUE rb_class_new_instance(int argc, VALUE *argv, VALUE klass) { VALUE obj; obj = rb_obj_alloc(klass); rb_obj_call_init(obj, argc, argv); return obj; } /* * call-seq: * class.superclass -> a_super_class or nil * * Returns the superclass of class, or nil. * * File.superclass #=> IO * IO.superclass #=> Object * Object.superclass #=> BasicObject * class Foo; end * class Bar < Foo; end * Bar.superclass #=> Foo * * returns nil when the given class hasn't a parent class: * * BasicObject.superclass #=> nil * */ static VALUE rb_class_superclass(VALUE klass) { VALUE super = RCLASS_SUPER(klass); if (!super) { if (klass == rb_cBasicObject) return Qnil; rb_raise(rb_eTypeError, "uninitialized class"); } while (TYPE(super) == T_ICLASS) { super = RCLASS_SUPER(super); } if (!super) { return Qnil; } return super; } /* * call-seq: * attr_reader(symbol, ...) => nil * attr(symbol, ...) => nil * * Creates instance variables and corresponding methods that return the * value of each instance variable. Equivalent to calling * ``attr:name'' on each name in turn. */ static VALUE rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i nil * * Creates an accessor method to allow assignment to the attribute * aSymbol.id2name. */ static VALUE rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i nil * * Defines a named attribute for this module, where the name is * symbol.id2name, creating an instance variable * (@name) and a corresponding access method to read it. * Also creates a method called name= to set the attribute. * * module Mod * attr_accessor(:one, :two) * end * Mod.instance_methods.sort #=> [:one, :one=, :two, :two=] */ static VALUE rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i obj * * Returns the value of the named constant in mod. * * Math.const_get(:PI) #=> 3.14159265358979 * * If the constant is not defined or is defined by the ancestors and * +inherit+ is false, +NameError+ will be raised. */ static VALUE rb_mod_const_get(int argc, VALUE *argv, VALUE mod) { VALUE name, recur; ID id; if (argc == 1) { name = argv[0]; recur = Qtrue; } else { rb_scan_args(argc, argv, "11", &name, &recur); } id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id); } /* * call-seq: * mod.const_set(sym, obj) => obj * * Sets the named constant to the given object, returning that object. * Creates a new constant if no constant with the given name previously * existed. * * Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714 * Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968 */ static VALUE rb_mod_const_set(VALUE mod, VALUE name, VALUE value) { ID id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } rb_const_set(mod, id, value); return value; } /* * call-seq: * mod.const_defined?(sym, inherit=true) => true or false * * Returns true if a constant with the given name is * defined by mod, or its ancestors if +inherit+ is not false. * * Math.const_defined? "PI" #=> true * IO.const_defined? "SYNC" #=> true * IO.const_defined? "SYNC", false #=> false */ static VALUE rb_mod_const_defined(int argc, VALUE *argv, VALUE mod) { VALUE name, recur; ID id; if (argc == 1) { name = argv[0]; recur = Qtrue; } else { rb_scan_args(argc, argv, "11", &name, &recur); } id = rb_to_id(name); if (!rb_is_const_id(id)) { rb_name_error(id, "wrong constant name %s", rb_id2name(id)); } return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id); } /* * call-seq: * obj.methods => array * * Returns a list of the names of methods publicly accessible in * obj. This will include all the methods accessible in * obj's ancestors. * * class Klass * def kMethod() * end * end * k = Klass.new * k.methods[0..9] #=> ["kMethod", "freeze", "nil?", "is_a?", * # "class", "instance_variable_set", * # "methods", "extend", "__send__", "instance_eval"] * k.methods.length #=> 42 */ static VALUE rb_obj_methods(int argc, VALUE *argv, VALUE obj) { retry: if (argc == 0) { VALUE args[1]; args[0] = Qtrue; return rb_class_instance_methods(1, args, CLASS_OF(obj)); } else { VALUE recur; rb_scan_args(argc, argv, "1", &recur); if (RTEST(recur)) { argc = 0; goto retry; } return rb_obj_singleton_methods(argc, argv, obj); } } /* * call-seq: * obj.protected_methods(all=true) => array * * Returns the list of protected methods accessible to obj. If * the all parameter is set to false, only those methods * in the receiver will be listed. */ static VALUE rb_obj_protected_methods(int argc, VALUE *argv, VALUE obj) { if (argc == 0) { /* hack to stop warning */ VALUE args[1]; args[0] = Qtrue; return rb_class_protected_instance_methods(1, args, CLASS_OF(obj)); } return rb_class_protected_instance_methods(argc, argv, CLASS_OF(obj)); } /* * call-seq: * obj.private_methods(all=true) => array * * Returns the list of private methods accessible to obj. If * the all parameter is set to false, only those methods * in the receiver will be listed. */ static VALUE rb_obj_private_methods(int argc, VALUE *argv, VALUE obj) { if (argc == 0) { /* hack to stop warning */ VALUE args[1]; args[0] = Qtrue; return rb_class_private_instance_methods(1, args, CLASS_OF(obj)); } return rb_class_private_instance_methods(argc, argv, CLASS_OF(obj)); } /* * call-seq: * obj.public_methods(all=true) => array * * Returns the list of public methods accessible to obj. If * the all parameter is set to false, only those methods * in the receiver will be listed. */ static VALUE rb_obj_public_methods(int argc, VALUE *argv, VALUE obj) { if (argc == 0) { /* hack to stop warning */ VALUE args[1]; args[0] = Qtrue; return rb_class_public_instance_methods(1, args, CLASS_OF(obj)); } return rb_class_public_instance_methods(argc, argv, CLASS_OF(obj)); } /* * call-seq: * obj.instance_variable_get(symbol) => obj * * Returns the value of the given instance variable, or nil if the * instance variable is not set. The @ part of the * variable name should be included for regular instance * variables. Throws a NameError exception if the * supplied symbol is not valid as an instance variable name. * * class Fred * def initialize(p1, p2) * @a, @b = p1, p2 * end * end * fred = Fred.new('cat', 99) * fred.instance_variable_get(:@a) #=> "cat" * fred.instance_variable_get("@b") #=> 99 */ static VALUE rb_obj_ivar_get(VALUE obj, VALUE iv) { ID id = rb_to_id(iv); if (!rb_is_instance_id(id)) { rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id)); } return rb_ivar_get(obj, id); } /* * call-seq: * obj.instance_variable_set(symbol, obj) => obj * * Sets the instance variable names by symbol to * object, thereby frustrating the efforts of the class's * author to attempt to provide proper encapsulation. The variable * did not have to exist prior to this call. * * class Fred * def initialize(p1, p2) * @a, @b = p1, p2 * end * end * fred = Fred.new('cat', 99) * fred.instance_variable_set(:@a, 'dog') #=> "dog" * fred.instance_variable_set(:@c, 'cat') #=> "cat" * fred.inspect #=> "#" */ static VALUE rb_obj_ivar_set(VALUE obj, VALUE iv, VALUE val) { ID id = rb_to_id(iv); if (!rb_is_instance_id(id)) { rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id)); } return rb_ivar_set(obj, id, val); } /* * call-seq: * obj.instance_variable_defined?(symbol) => true or false * * Returns true if the given instance variable is * defined in obj. * * class Fred * def initialize(p1, p2) * @a, @b = p1, p2 * end * end * fred = Fred.new('cat', 99) * fred.instance_variable_defined?(:@a) #=> true * fred.instance_variable_defined?("@b") #=> true * fred.instance_variable_defined?("@c") #=> false */ static VALUE rb_obj_ivar_defined(VALUE obj, VALUE iv) { ID id = rb_to_id(iv); if (!rb_is_instance_id(id)) { rb_name_error(id, "`%s' is not allowed as an instance variable name", rb_id2name(id)); } return rb_ivar_defined(obj, id); } /* * call-seq: * mod.class_variable_get(symbol) => obj * * Returns the value of the given class variable (or throws a * NameError exception). The @@ part of the * variable name should be included for regular class variables * * class Fred * @@foo = 99 * end * Fred.class_variable_get(:@@foo) #=> 99 */ static VALUE rb_mod_cvar_get(VALUE obj, VALUE iv) { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } return rb_cvar_get(obj, id); } /* * call-seq: * obj.class_variable_set(symbol, obj) => obj * * Sets the class variable names by symbol to * object. * * class Fred * @@foo = 99 * def foo * @@foo * end * end * Fred.class_variable_set(:@@foo, 101) #=> 101 * Fred.new.foo #=> 101 */ static VALUE rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val) { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } rb_cvar_set(obj, id, val); return val; } /* * call-seq: * obj.class_variable_defined?(symbol) => true or false * * Returns true if the given class variable is defined * in obj. * * class Fred * @@foo = 99 * end * Fred.class_variable_defined?(:@@foo) #=> true * Fred.class_variable_defined?(:@@bar) #=> false */ static VALUE rb_mod_cvar_defined(VALUE obj, VALUE iv) { ID id = rb_to_id(iv); if (!rb_is_class_id(id)) { rb_name_error(id, "`%s' is not allowed as a class variable name", rb_id2name(id)); } return rb_cvar_defined(obj, id); } static VALUE convert_type(VALUE val, const char *tname, const char *method, int raise) { ID m; m = rb_intern(method); if (!rb_respond_to(val, m)) { if (raise) { rb_raise(rb_eTypeError, "can't convert %s into %s", NIL_P(val) ? "nil" : val == Qtrue ? "true" : val == Qfalse ? "false" : rb_obj_classname(val), tname); } else { return Qnil; } } return rb_funcall(val, m, 0); } VALUE rb_convert_type(VALUE val, int type, const char *tname, const char *method) { VALUE v; if (TYPE(val) == type) return val; v = convert_type(val, tname, method, Qtrue); if (TYPE(v) != type) { const char *cname = rb_obj_classname(val); rb_raise(rb_eTypeError, "can't convert %s to %s (%s#%s gives %s)", cname, tname, cname, method, rb_obj_classname(v)); } return v; } VALUE rb_check_convert_type(VALUE val, int type, const char *tname, const char *method) { VALUE v; /* always convert T_DATA */ if (TYPE(val) == type && type != T_DATA) return val; v = convert_type(val, tname, method, Qfalse); if (NIL_P(v)) return Qnil; if (TYPE(v) != type) { const char *cname = rb_obj_classname(val); rb_raise(rb_eTypeError, "can't convert %s to %s (%s#%s gives %s)", cname, tname, cname, method, rb_obj_classname(v)); } return v; } static VALUE rb_to_integer(VALUE val, const char *method) { VALUE v; if (FIXNUM_P(val)) return val; v = convert_type(val, "Integer", method, Qtrue); if (!rb_obj_is_kind_of(v, rb_cInteger)) { const char *cname = rb_obj_classname(val); rb_raise(rb_eTypeError, "can't convert %s to Integer (%s#%s gives %s)", cname, cname, method, rb_obj_classname(v)); } return v; } VALUE rb_check_to_integer(VALUE val, const char *method) { VALUE v; if (FIXNUM_P(val)) return val; v = convert_type(val, "Integer", method, Qfalse); if (!rb_obj_is_kind_of(v, rb_cInteger)) { return Qnil; } return v; } VALUE rb_to_int(VALUE val) { return rb_to_integer(val, "to_int"); } VALUE rb_Integer(VALUE val) { VALUE tmp; switch (TYPE(val)) { case T_FLOAT: if (RFLOAT_VALUE(val) <= (double)FIXNUM_MAX && RFLOAT_VALUE(val) >= (double)FIXNUM_MIN) { break; } return rb_dbl2big(RFLOAT_VALUE(val)); case T_FIXNUM: case T_BIGNUM: return val; case T_STRING: return rb_str_to_inum(val, 0, Qtrue); case T_NIL: rb_raise(rb_eTypeError, "can't convert nil into Integer"); break; default: break; } tmp = convert_type(val, "Integer", "to_int", Qfalse); if (NIL_P(tmp)) { return rb_to_integer(val, "to_i"); } return tmp; } /* * call-seq: * Integer(arg) => integer * * Converts arg to a Fixnum or Bignum. * Numeric types are converted directly (with floating point numbers * being truncated). If arg is a String, leading * radix indicators (0, 0b, and * 0x) are honored. Others are converted using * to_int and to_i. This behavior is * different from that of String#to_i. * * Integer(123.999) #=> 123 * Integer("0x1a") #=> 26 * Integer(Time.new) #=> 1204973019 */ static VALUE rb_f_integer(VALUE obj, VALUE arg) { return rb_Integer(arg); } double rb_cstr_to_dbl(const char *p, int badcheck) { const char *q; char *end; double d; const char *ellipsis = ""; int w; #define OutOfRange() (((w = end - p) > 20) ? (w = 20, ellipsis = "...") : (ellipsis = "")) if (!p) return 0.0; q = p; while (ISSPACE(*p)) p++; d = strtod(p, &end); if (errno == ERANGE) { OutOfRange(); rb_warning("Float %.*s%s out of range", w, p, ellipsis); errno = 0; } if (p == end) { if (badcheck) { bad: rb_invalid_str(q, "Float()"); } return d; } if (*end) { char buf[DBL_DIG * 4 + 10]; char *n = buf; char *e = buf + sizeof(buf) - 1; char prev = 0; while (p < end && n < e) prev = *n++ = *p++; while (*p) { if (*p == '_') { /* remove underscores between digits */ if (badcheck) { if (n == buf || !ISDIGIT(prev)) goto bad; ++p; if (!ISDIGIT(*p)) goto bad; } else { while (*++p == '_'); continue; } } prev = *p++; if (n < e) *n++ = prev; } *n = '\0'; p = buf; d = strtod(p, &end); if (errno == ERANGE) { OutOfRange(); rb_warning("Float %.*s%s out of range", w, p, ellipsis); errno = 0; } if (badcheck) { if (!end || p == end) goto bad; while (*end && ISSPACE(*end)) end++; if (*end) goto bad; } } if (errno == ERANGE) { errno = 0; OutOfRange(); rb_raise(rb_eArgError, "Float %.*s%s out of range", w, q, ellipsis); } return d; } double rb_str_to_dbl(VALUE str, int badcheck) { char *s; long len; StringValue(str); s = RSTRING_PTR(str); len = RSTRING_LEN(str); if (s) { if (s[len]) { /* no sentinel somehow */ char *p = ALLOCA_N(char, len+1); MEMCPY(p, s, char, len); p[len] = '\0'; s = p; } if (badcheck && len != strlen(s)) { rb_raise(rb_eArgError, "string for Float contains null byte"); } } return rb_cstr_to_dbl(s, badcheck); } VALUE rb_Float(VALUE val) { switch (TYPE(val)) { case T_FIXNUM: return DOUBLE2NUM((double)FIX2LONG(val)); case T_FLOAT: return val; case T_BIGNUM: return DOUBLE2NUM(rb_big2dbl(val)); case T_STRING: return DOUBLE2NUM(rb_str_to_dbl(val, Qtrue)); case T_NIL: rb_raise(rb_eTypeError, "can't convert nil into Float"); break; default: return rb_convert_type(val, T_FLOAT, "Float", "to_f"); } } /* * call-seq: * Float(arg) => float * * Returns arg converted to a float. Numeric types are converted * directly, the rest are converted using arg.to_f. As of Ruby * 1.8, converting nil generates a TypeError. * * Float(1) #=> 1.0 * Float("123.456") #=> 123.456 */ static VALUE rb_f_float(VALUE obj, VALUE arg) { return rb_Float(arg); } double rb_num2dbl(VALUE val) { switch (TYPE(val)) { case T_FLOAT: return RFLOAT_VALUE(val); case T_STRING: rb_raise(rb_eTypeError, "no implicit conversion to float from string"); break; case T_NIL: rb_raise(rb_eTypeError, "no implicit conversion to float from nil"); break; default: break; } return RFLOAT_VALUE(rb_Float(val)); } char* rb_str2cstr(VALUE str, long *len) { StringValue(str); if (len) *len = RSTRING_LEN(str); else if (RTEST(ruby_verbose) && RSTRING_LEN(str) != strlen(RSTRING_PTR(str))) { rb_warn("string contains \\0 character"); } return RSTRING_PTR(str); } VALUE rb_String(VALUE val) { return rb_convert_type(val, T_STRING, "String", "to_s"); } /* * call-seq: * String(arg) => string * * Converts arg to a String by calling its * to_s method. * * String(self) #=> "main" * String(self.class) #=> "Object" * String(123456) #=> "123456" */ static VALUE rb_f_string(VALUE obj, VALUE arg) { return rb_String(arg); } VALUE rb_Array(VALUE val) { VALUE tmp = rb_check_array_type(val); if (NIL_P(tmp)) { tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_a"); if (NIL_P(tmp)) { return rb_ary_new3(1, val); } } return tmp; } /* * call-seq: * Array(arg) => array * * Returns arg as an Array. First tries to call * arg.to_ary, then arg.to_a. * * Array(1..5) #=> [1, 2, 3, 4, 5] */ static VALUE rb_f_array(VALUE obj, VALUE arg) { return rb_Array(arg); } static VALUE boot_defclass(const char *name, VALUE super) { extern st_table *rb_class_tbl; VALUE obj = rb_class_boot(super); ID id = rb_intern(name); rb_name_class(obj, id); st_add_direct(rb_class_tbl, id, obj); rb_const_set((rb_cObject ? rb_cObject : obj), id, obj); return obj; } /* * Document-class: Class * * Classes in Ruby are first-class objects---each is an instance of * class Class. * * When a new class is created (typically using class Name ... * end), an object of type Class is created and * assigned to a global constant (Name in this case). When * Name.new is called to create a new object, the * new method in Class is run by default. * This can be demonstrated by overriding new in * Class: * * class Class * alias oldNew new * def new(*args) * print "Creating a new ", self.name, "\n" * oldNew(*args) * end * end * * * class Name * end * * * n = Name.new * * produces: * * Creating a new Name * * Classes, modules, and objects are interrelated. In the diagram * that follows, the vertical arrows represent inheritance, and the * parentheses meta-classes. All metaclasses are instances * of the class `Class'. * * +-----------------+ * | | * BasicObject-->(BasicObject) | * ^ ^ | * | | | * Object---->(Object) | * ^ ^ ^ ^ | * | | | | | * | | +-----+ +---------+ | * | | | | | * | +-----------+ | | * | | | | | * +------+ | Module--->(Module) | * | | ^ ^ | * OtherClass-->(OtherClass) | | | * | | | * Class---->(Class) | * ^ | * | | * +----------------+ */ /* * BasicObject is the parent class of all classes in Ruby. * It's an explicit blank class. Object, the root of Ruby's * class hierarchy is a direct subclass of BasicObject. Its * methods are therefore available to all objects unless explicitly * overridden. * * Object mixes in the Kernel module, making * the built-in kernel functions globally accessible. Although the * instance methods of Object are defined by the * Kernel module, we have chosen to document them here for * clarity. * * In the descriptions of Object's methods, the parameter symbol refers * to a symbol, which is either a quoted string or a * Symbol (such as :name). */ void Init_Object(void) { #undef rb_intern #define rb_intern(str) rb_intern_const(str) VALUE metaclass; rb_cBasicObject = boot_defclass("BasicObject", 0); rb_cObject = boot_defclass("Object", rb_cBasicObject); rb_cModule = boot_defclass("Module", rb_cObject); rb_cClass = boot_defclass("Class", rb_cModule); metaclass = rb_make_metaclass(rb_cBasicObject, rb_cClass); metaclass = rb_make_metaclass(rb_cObject, metaclass); metaclass = rb_make_metaclass(rb_cModule, metaclass); metaclass = rb_make_metaclass(rb_cClass, metaclass); rb_define_private_method(rb_cBasicObject, "initialize", rb_obj_dummy, 0); rb_define_alloc_func(rb_cBasicObject, rb_class_allocate_instance); rb_define_method(rb_cBasicObject, "==", rb_obj_equal, 1); rb_define_method(rb_cBasicObject, "equal?", rb_obj_equal, 1); rb_define_method(rb_cBasicObject, "!", rb_obj_not, 0); rb_define_method(rb_cBasicObject, "!=", rb_obj_not_equal, 1); rb_define_private_method(rb_cBasicObject, "singleton_method_added", rb_obj_dummy, 1); rb_define_private_method(rb_cBasicObject, "singleton_method_removed", rb_obj_dummy, 1); rb_define_private_method(rb_cBasicObject, "singleton_method_undefined", rb_obj_dummy, 1); rb_mKernel = rb_define_module("Kernel"); rb_include_module(rb_cObject, rb_mKernel); rb_define_private_method(rb_cClass, "inherited", rb_obj_dummy, 1); rb_define_private_method(rb_cModule, "included", rb_obj_dummy, 1); rb_define_private_method(rb_cModule, "extended", rb_obj_dummy, 1); rb_define_private_method(rb_cModule, "method_added", rb_obj_dummy, 1); rb_define_private_method(rb_cModule, "method_removed", rb_obj_dummy, 1); rb_define_private_method(rb_cModule, "method_undefined", rb_obj_dummy, 1); rb_define_method(rb_mKernel, "nil?", rb_false, 0); rb_define_method(rb_mKernel, "===", rb_equal, 1); rb_define_method(rb_mKernel, "=~", rb_obj_match, 1); rb_define_method(rb_mKernel, "!~", rb_obj_not_match, 1); rb_define_method(rb_mKernel, "eql?", rb_obj_equal, 1); rb_define_method(rb_mKernel, "class", rb_obj_class, 0); rb_define_method(rb_mKernel, "clone", rb_obj_clone, 0); rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0); rb_define_method(rb_mKernel, "initialize_copy", rb_obj_init_copy, 1); rb_define_method(rb_mKernel, "taint", rb_obj_taint, 0); rb_define_method(rb_mKernel, "tainted?", rb_obj_tainted, 0); rb_define_method(rb_mKernel, "untaint", rb_obj_untaint, 0); rb_define_method(rb_mKernel, "untrust", rb_obj_untrust, 0); rb_define_method(rb_mKernel, "untrusted?", rb_obj_untrusted, 0); rb_define_method(rb_mKernel, "trust", rb_obj_trust, 0); rb_define_method(rb_mKernel, "freeze", rb_obj_freeze, 0); rb_define_method(rb_mKernel, "frozen?", rb_obj_frozen_p, 0); rb_define_method(rb_mKernel, "to_s", rb_any_to_s, 0); rb_define_method(rb_mKernel, "inspect", rb_obj_inspect, 0); rb_define_method(rb_mKernel, "methods", rb_obj_methods, -1); rb_define_method(rb_mKernel, "singleton_methods", rb_obj_singleton_methods, -1); /* in class.c */ rb_define_method(rb_mKernel, "protected_methods", rb_obj_protected_methods, -1); rb_define_method(rb_mKernel, "private_methods", rb_obj_private_methods, -1); rb_define_method(rb_mKernel, "public_methods", rb_obj_public_methods, -1); rb_define_method(rb_mKernel, "instance_variables", rb_obj_instance_variables, 0); /* in variable.c */ rb_define_method(rb_mKernel, "instance_variable_get", rb_obj_ivar_get, 1); rb_define_method(rb_mKernel, "instance_variable_set", rb_obj_ivar_set, 2); rb_define_method(rb_mKernel, "instance_variable_defined?", rb_obj_ivar_defined, 1); rb_define_private_method(rb_mKernel, "remove_instance_variable", rb_obj_remove_instance_variable, 1); /* in variable.c */ rb_define_method(rb_mKernel, "instance_of?", rb_obj_is_instance_of, 1); rb_define_method(rb_mKernel, "kind_of?", rb_obj_is_kind_of, 1); rb_define_method(rb_mKernel, "is_a?", rb_obj_is_kind_of, 1); rb_define_method(rb_mKernel, "tap", rb_obj_tap, 0); rb_define_global_function("sprintf", rb_f_sprintf, -1); /* in sprintf.c */ rb_define_global_function("format", rb_f_sprintf, -1); /* in sprintf.c */ rb_define_global_function("Integer", rb_f_integer, 1); rb_define_global_function("Float", rb_f_float, 1); rb_define_global_function("String", rb_f_string, 1); rb_define_global_function("Array", rb_f_array, 1); rb_cNilClass = rb_define_class("NilClass", rb_cObject); rb_define_method(rb_cNilClass, "to_i", nil_to_i, 0); rb_define_method(rb_cNilClass, "to_f", nil_to_f, 0); rb_define_method(rb_cNilClass, "to_s", nil_to_s, 0); rb_define_method(rb_cNilClass, "to_a", nil_to_a, 0); rb_define_method(rb_cNilClass, "inspect", nil_inspect, 0); rb_define_method(rb_cNilClass, "&", false_and, 1); rb_define_method(rb_cNilClass, "|", false_or, 1); rb_define_method(rb_cNilClass, "^", false_xor, 1); rb_define_method(rb_cNilClass, "nil?", rb_true, 0); rb_undef_alloc_func(rb_cNilClass); rb_undef_method(CLASS_OF(rb_cNilClass), "new"); rb_define_global_const("NIL", Qnil); rb_define_method(rb_cModule, "freeze", rb_mod_freeze, 0); rb_define_method(rb_cModule, "===", rb_mod_eqq, 1); rb_define_method(rb_cModule, "==", rb_obj_equal, 1); rb_define_method(rb_cModule, "<=>", rb_mod_cmp, 1); rb_define_method(rb_cModule, "<", rb_mod_lt, 1); rb_define_method(rb_cModule, "<=", rb_class_inherited_p, 1); rb_define_method(rb_cModule, ">", rb_mod_gt, 1); rb_define_method(rb_cModule, ">=", rb_mod_ge, 1); rb_define_method(rb_cModule, "initialize_copy", rb_mod_init_copy, 1); /* in class.c */ rb_define_method(rb_cModule, "to_s", rb_mod_to_s, 0); rb_define_method(rb_cModule, "included_modules", rb_mod_included_modules, 0); /* in class.c */ rb_define_method(rb_cModule, "include?", rb_mod_include_p, 1); /* in class.c */ rb_define_method(rb_cModule, "name", rb_mod_name, 0); /* in variable.c */ rb_define_method(rb_cModule, "ancestors", rb_mod_ancestors, 0); /* in class.c */ rb_define_private_method(rb_cModule, "attr", rb_mod_attr, -1); rb_define_private_method(rb_cModule, "attr_reader", rb_mod_attr_reader, -1); rb_define_private_method(rb_cModule, "attr_writer", rb_mod_attr_writer, -1); rb_define_private_method(rb_cModule, "attr_accessor", rb_mod_attr_accessor, -1); rb_define_alloc_func(rb_cModule, rb_module_s_alloc); rb_define_method(rb_cModule, "initialize", rb_mod_initialize, 0); rb_define_method(rb_cModule, "instance_methods", rb_class_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "public_instance_methods", rb_class_public_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "protected_instance_methods", rb_class_protected_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "private_instance_methods", rb_class_private_instance_methods, -1); /* in class.c */ rb_define_method(rb_cModule, "constants", rb_mod_constants, -1); /* in variable.c */ rb_define_method(rb_cModule, "const_get", rb_mod_const_get, -1); rb_define_method(rb_cModule, "const_set", rb_mod_const_set, 2); rb_define_method(rb_cModule, "const_defined?", rb_mod_const_defined, -1); rb_define_private_method(rb_cModule, "remove_const", rb_mod_remove_const, 1); /* in variable.c */ rb_define_method(rb_cModule, "const_missing", rb_mod_const_missing, 1); /* in variable.c */ rb_define_method(rb_cModule, "class_variables", rb_mod_class_variables, 0); /* in variable.c */ rb_define_method(rb_cModule, "remove_class_variable", rb_mod_remove_cvar, 1); /* in variable.c */ rb_define_method(rb_cModule, "class_variable_get", rb_mod_cvar_get, 1); rb_define_method(rb_cModule, "class_variable_set", rb_mod_cvar_set, 2); rb_define_method(rb_cModule, "class_variable_defined?", rb_mod_cvar_defined, 1); rb_define_method(rb_cClass, "allocate", rb_obj_alloc, 0); rb_define_method(rb_cClass, "new", rb_class_new_instance, -1); rb_define_method(rb_cClass, "initialize", rb_class_initialize, -1); rb_define_method(rb_cClass, "initialize_copy", rb_class_init_copy, 1); /* in class.c */ rb_define_method(rb_cClass, "superclass", rb_class_superclass, 0); rb_define_alloc_func(rb_cClass, rb_class_s_alloc); rb_undef_method(rb_cClass, "extend_object"); rb_undef_method(rb_cClass, "append_features"); rb_cData = rb_define_class("Data", rb_cObject); rb_undef_alloc_func(rb_cData); rb_cTrueClass = rb_define_class("TrueClass", rb_cObject); rb_define_method(rb_cTrueClass, "to_s", true_to_s, 0); rb_define_method(rb_cTrueClass, "&", true_and, 1); rb_define_method(rb_cTrueClass, "|", true_or, 1); rb_define_method(rb_cTrueClass, "^", true_xor, 1); rb_undef_alloc_func(rb_cTrueClass); rb_undef_method(CLASS_OF(rb_cTrueClass), "new"); rb_define_global_const("TRUE", Qtrue); rb_cFalseClass = rb_define_class("FalseClass", rb_cObject); rb_define_method(rb_cFalseClass, "to_s", false_to_s, 0); rb_define_method(rb_cFalseClass, "&", false_and, 1); rb_define_method(rb_cFalseClass, "|", false_or, 1); rb_define_method(rb_cFalseClass, "^", false_xor, 1); rb_undef_alloc_func(rb_cFalseClass); rb_undef_method(CLASS_OF(rb_cFalseClass), "new"); rb_define_global_const("FALSE", Qfalse); id_eq = rb_intern("=="); id_eql = rb_intern("eql?"); id_match = rb_intern("=~"); id_inspect = rb_intern("inspect"); id_init_copy = rb_intern("initialize_copy"); } 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756
/*
 * BSD 3-Clause License
 *
 * Copyright (c) 2005-2008, Jelmer Vernooij <jelmer@samba.org>
 * Copyright (c) 2006-2018, Stefan Metzmacher <metze@samba.org>
 * Copyright (c) 2013-2018, Andreas Schneider <asn@samba.org>
 * Copyright (c) 2014-2017, Michael Adam <obnox@samba.org>
 * Copyright (c) 2016-2018, Anoop C S <anoopcs@redhat.com>
 * 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 author 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 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.
 */

/*
   Socket wrapper library. Passes all socket communication over
   unix domain sockets if the environment variable SOCKET_WRAPPER_DIR
   is set.
*/

#include "config.h"

#include <sys/types.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#ifdef HAVE_SYS_FILIO_H
#include <sys/filio.h>
#endif
#ifdef HAVE_SYS_SIGNALFD_H
#include <sys/signalfd.h>
#endif
#ifdef HAVE_SYS_EVENTFD_H
#include <sys/eventfd.h>
#endif
#ifdef HAVE_SYS_TIMERFD_H
#include <sys/timerfd.h>
#endif
#include <sys/uio.h>
#include <errno.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#ifdef HAVE_NETINET_TCP_FSM_H
#include <netinet/tcp_fsm.h>
#endif
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>
#include <stdarg.h>
#include <stdbool.h>
#include <unistd.h>
#ifdef HAVE_GNU_LIB_NAMES_H
#include <gnu/lib-names.h>
#endif
#ifdef HAVE_RPC_RPC_H
#include <rpc/rpc.h>
#endif
#include <pthread.h>

enum swrap_dbglvl_e {
	SWRAP_LOG_ERROR = 0,
	SWRAP_LOG_WARN,
	SWRAP_LOG_DEBUG,
	SWRAP_LOG_TRACE
};

/* GCC have printf type attribute check. */
#ifdef HAVE_FUNCTION_ATTRIBUTE_FORMAT
#define PRINTF_ATTRIBUTE(a,b) __attribute__ ((__format__ (__printf__, a, b)))
#else
#define PRINTF_ATTRIBUTE(a,b)
#endif /* HAVE_FUNCTION_ATTRIBUTE_FORMAT */

#ifdef HAVE_CONSTRUCTOR_ATTRIBUTE
#define CONSTRUCTOR_ATTRIBUTE __attribute__ ((constructor))
#else
#define CONSTRUCTOR_ATTRIBUTE
#endif /* HAVE_CONSTRUCTOR_ATTRIBUTE */

#ifdef HAVE_DESTRUCTOR_ATTRIBUTE
#define DESTRUCTOR_ATTRIBUTE __attribute__ ((destructor))
#else
#define DESTRUCTOR_ATTRIBUTE
#endif

#ifndef FALL_THROUGH
# ifdef HAVE_FALLTHROUGH_ATTRIBUTE
#  define FALL_THROUGH __attribute__ ((fallthrough))
# else /* HAVE_FALLTHROUGH_ATTRIBUTE */
#  define FALL_THROUGH ((void)0)
# endif /* HAVE_FALLTHROUGH_ATTRIBUTE */
#endif /* FALL_THROUGH */

#ifdef HAVE_ADDRESS_SANITIZER_ATTRIBUTE
#define DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE __attribute__((no_sanitize_address))
#else
#define DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE
#endif

#ifdef HAVE_GCC_THREAD_LOCAL_STORAGE
# define SWRAP_THREAD __thread
#else
# define SWRAP_THREAD
#endif

#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif

#ifndef ZERO_STRUCT
#define ZERO_STRUCT(x) memset((char *)&(x), 0, sizeof(x))
#endif

#ifndef ZERO_STRUCTP
#define ZERO_STRUCTP(x) do { \
		if ((x) != NULL) \
			memset((char *)(x), 0, sizeof(*(x))); \
	} while(0)
#endif

#ifndef SAFE_FREE
#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); (x)=NULL;} } while(0)
#endif

#ifndef discard_const
#define discard_const(ptr) ((void *)((uintptr_t)(ptr)))
#endif

#ifndef discard_const_p
#define discard_const_p(type, ptr) ((type *)discard_const(ptr))
#endif

#define UNUSED(x) (void)(x)

#ifdef IPV6_PKTINFO
# ifndef IPV6_RECVPKTINFO
#  define IPV6_RECVPKTINFO IPV6_PKTINFO
# endif /* IPV6_RECVPKTINFO */
#endif /* IPV6_PKTINFO */

/*
 * On BSD IP_PKTINFO has a different name because during
 * the time when they implemented it, there was no RFC.
 * The name for IPv6 is the same as on Linux.
 */
#ifndef IP_PKTINFO
# ifdef IP_RECVDSTADDR
#  define IP_PKTINFO IP_RECVDSTADDR
# endif
#endif

/* Add new global locks here please */
# define SWRAP_LOCK_ALL \
	swrap_mutex_lock(&libc_symbol_binding_mutex); \

# define SWRAP_UNLOCK_ALL \
	swrap_mutex_unlock(&libc_symbol_binding_mutex); \

#define SOCKET_INFO_CONTAINER(si) \
	(struct socket_info_container *)(si)

#define SWRAP_LOCK_SI(si) do { \
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si); \
	swrap_mutex_lock(&sic->meta.mutex); \
} while(0)

#define SWRAP_UNLOCK_SI(si) do { \
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si); \
	swrap_mutex_unlock(&sic->meta.mutex); \
} while(0)

#if defined(HAVE_GETTIMEOFDAY_TZ) || defined(HAVE_GETTIMEOFDAY_TZ_VOID)
#define swrapGetTimeOfDay(tval) gettimeofday(tval,NULL)
#else
#define swrapGetTimeOfDay(tval)	gettimeofday(tval)
#endif

/* we need to use a very terse format here as IRIX 6.4 silently
   truncates names to 16 chars, so if we use a longer name then we
   can't tell which port a packet came from with recvfrom()

   with this format we have 8 chars left for the directory name
*/
#define SOCKET_FORMAT "%c%02X%04X"
#define SOCKET_TYPE_CHAR_TCP		'T'
#define SOCKET_TYPE_CHAR_UDP		'U'
#define SOCKET_TYPE_CHAR_TCP_V6		'X'
#define SOCKET_TYPE_CHAR_UDP_V6		'Y'

/*
 * Set the packet MTU to 1500 bytes for stream sockets to make it it easier to
 * format PCAP capture files (as the caller will simply continue from here).
 */
#define SOCKET_WRAPPER_MTU_DEFAULT 1500
#define SOCKET_WRAPPER_MTU_MIN     512
#define SOCKET_WRAPPER_MTU_MAX     32768

#define SOCKET_MAX_SOCKETS 1024

/*
 * Maximum number of socket_info structures that can
 * be used. Can be overriden by the environment variable
 * SOCKET_WRAPPER_MAX_SOCKETS.
 */
#define SOCKET_WRAPPER_MAX_SOCKETS_DEFAULT 65535

#define SOCKET_WRAPPER_MAX_SOCKETS_LIMIT 262140

/* This limit is to avoid broadcast sendto() needing to stat too many
 * files.  It may be raised (with a performance cost) to up to 254
 * without changing the format above */
#define MAX_WRAPPED_INTERFACES 64

struct swrap_address {
	socklen_t sa_socklen;
	union {
		struct sockaddr s;
		struct sockaddr_in in;
#ifdef HAVE_IPV6
		struct sockaddr_in6 in6;
#endif
		struct sockaddr_un un;
		struct sockaddr_storage ss;
	} sa;
};

int first_free;

struct socket_info
{
	int family;
	int type;
	int protocol;
	int bound;
	int bcast;
	int is_server;
	int connected;
	int defer_connect;
	int pktinfo;
	int tcp_nodelay;
	int listening;

	/* The unix path so we can unlink it on close() */
	struct sockaddr_un un_addr;

	struct swrap_address bindname;
	struct swrap_address myname;
	struct swrap_address peername;

	struct {
		unsigned long pck_snd;
		unsigned long pck_rcv;
	} io;
};

struct socket_info_meta
{
	unsigned int refcount;
	int next_free;
	pthread_mutex_t mutex;
};

struct socket_info_container
{
	struct socket_info info;
	struct socket_info_meta meta;
};

static struct socket_info_container *sockets;

static size_t socket_info_max = 0;

/*
 * Allocate the socket array always on the limit value. We want it to be
 * at least bigger than the default so if we reach the limit we can
 * still deal with duplicate fds pointing to the same socket_info.
 */
static size_t socket_fds_max = SOCKET_WRAPPER_MAX_SOCKETS_LIMIT;

/* Hash table to map fds to corresponding socket_info index */
static int *socket_fds_idx;

/* Mutex to synchronize access to global libc.symbols */
static pthread_mutex_t libc_symbol_binding_mutex = PTHREAD_MUTEX_INITIALIZER;

/* Mutex for syncronizing port selection during swrap_auto_bind() */
static pthread_mutex_t autobind_start_mutex;

/* Mutex to guard the initialization of array of socket_info structures */
static pthread_mutex_t sockets_mutex;

/* Mutex to guard the socket reset in swrap_close() and swrap_remove_stale() */
static pthread_mutex_t socket_reset_mutex;

/* Mutex to synchronize access to first free index in socket_info array */
static pthread_mutex_t first_free_mutex;

/* Mutex to synchronize access to packet capture dump file */
static pthread_mutex_t pcap_dump_mutex;

/* Mutex for synchronizing mtu value fetch*/
static pthread_mutex_t mtu_update_mutex;

/* Function prototypes */

bool socket_wrapper_enabled(void);

void swrap_constructor(void) CONSTRUCTOR_ATTRIBUTE;
void swrap_destructor(void) DESTRUCTOR_ATTRIBUTE;

#ifndef HAVE_GETPROGNAME
static const char *getprogname(void)
{
#if defined(HAVE_PROGRAM_INVOCATION_SHORT_NAME)
	return program_invocation_short_name;
#elif defined(HAVE_GETEXECNAME)
	return getexecname();
#else
	return NULL;
#endif /* HAVE_PROGRAM_INVOCATION_SHORT_NAME */
}
#endif /* HAVE_GETPROGNAME */

static void swrap_log(enum swrap_dbglvl_e dbglvl, const char *func, const char *format, ...) PRINTF_ATTRIBUTE(3, 4);
# define SWRAP_LOG(dbglvl, ...) swrap_log((dbglvl), __func__, __VA_ARGS__)

static void swrap_log(enum swrap_dbglvl_e dbglvl,
		      const char *func,
		      const char *format, ...)
{
	char buffer[1024];
	va_list va;
	const char *d;
	unsigned int lvl = 0;
	const char *prefix = "SWRAP";
	const char *progname = getprogname();

	d = getenv("SOCKET_WRAPPER_DEBUGLEVEL");
	if (d != NULL) {
		lvl = atoi(d);
	}

	if (lvl < dbglvl) {
		return;
	}

	va_start(va, format);
	vsnprintf(buffer, sizeof(buffer), format, va);
	va_end(va);

	switch (dbglvl) {
		case SWRAP_LOG_ERROR:
			prefix = "SWRAP_ERROR";
			break;
		case SWRAP_LOG_WARN:
			prefix = "SWRAP_WARN";
			break;
		case SWRAP_LOG_DEBUG:
			prefix = "SWRAP_DEBUG";
			break;
		case SWRAP_LOG_TRACE:
			prefix = "SWRAP_TRACE";
			break;
	}

	if (progname == NULL) {
		progname = "<unknown>";
	}

	fprintf(stderr,
		"%s[%s (%u)] - %s: %s\n",
		prefix,
		progname,
		(unsigned int)getpid(),
		func,
		buffer);
}

/*********************************************************
 * SWRAP LOADING LIBC FUNCTIONS
 *********************************************************/

#include <dlfcn.h>

#ifdef HAVE_ACCEPT4
typedef int (*__libc_accept4)(int sockfd,
			      struct sockaddr *addr,
			      socklen_t *addrlen,
			      int flags);
#else
typedef int (*__libc_accept)(int sockfd,
			     struct sockaddr *addr,
			     socklen_t *addrlen);
#endif
typedef int (*__libc_bind)(int sockfd,
			   const struct sockaddr *addr,
			   socklen_t addrlen);
typedef int (*__libc_close)(int fd);
typedef int (*__libc_connect)(int sockfd,
			      const struct sockaddr *addr,
			      socklen_t addrlen);
typedef int (*__libc_dup)(int fd);
typedef int (*__libc_dup2)(int oldfd, int newfd);
typedef int (*__libc_fcntl)(int fd, int cmd, ...);
typedef FILE *(*__libc_fopen)(const char *name, const char *mode);
#ifdef HAVE_FOPEN64
typedef FILE *(*__libc_fopen64)(const char *name, const char *mode);
#endif
#ifdef HAVE_EVENTFD
typedef int (*__libc_eventfd)(int count, int flags);
#endif
typedef int (*__libc_getpeername)(int sockfd,
				  struct sockaddr *addr,
				  socklen_t *addrlen);
typedef int (*__libc_getsockname)(int sockfd,
				  struct sockaddr *addr,
				  socklen_t *addrlen);
typedef int (*__libc_getsockopt)(int sockfd,
			       int level,
			       int optname,
			       void *optval,
			       socklen_t *optlen);
typedef int (*__libc_ioctl)(int d, unsigned long int request, ...);
typedef int (*__libc_listen)(int sockfd, int backlog);
typedef int (*__libc_open)(const char *pathname, int flags, ...);
#ifdef HAVE_OPEN64
typedef int (*__libc_open64)(const char *pathname, int flags, ...);
#endif /* HAVE_OPEN64 */
typedef int (*__libc_openat)(int dirfd, const char *path, int flags, ...);
typedef int (*__libc_pipe)(int pipefd[2]);
typedef int (*__libc_read)(int fd, void *buf, size_t count);
typedef ssize_t (*__libc_readv)(int fd, const struct iovec *iov, int iovcnt);
typedef int (*__libc_recv)(int sockfd, void *buf, size_t len, int flags);
typedef int (*__libc_recvfrom)(int sockfd,
			     void *buf,
			     size_t len,
			     int flags,
			     struct sockaddr *src_addr,
			     socklen_t *addrlen);
typedef int (*__libc_recvmsg)(int sockfd, const struct msghdr *msg, int flags);
typedef int (*__libc_send)(int sockfd, const void *buf, size_t len, int flags);
typedef int (*__libc_sendmsg)(int sockfd, const struct msghdr *msg, int flags);
typedef int (*__libc_sendto)(int sockfd,
			   const void *buf,
			   size_t len,
			   int flags,
			   const  struct sockaddr *dst_addr,
			   socklen_t addrlen);
typedef int (*__libc_setsockopt)(int sockfd,
			       int level,
			       int optname,
			       const void *optval,
			       socklen_t optlen);
#ifdef HAVE_SIGNALFD
typedef int (*__libc_signalfd)(int fd, const sigset_t *mask, int flags);
#endif
typedef int (*__libc_socket)(int domain, int type, int protocol);
typedef int (*__libc_socketpair)(int domain, int type, int protocol, int sv[2]);
#ifdef HAVE_TIMERFD_CREATE
typedef int (*__libc_timerfd_create)(int clockid, int flags);
#endif
typedef ssize_t (*__libc_write)(int fd, const void *buf, size_t count);
typedef ssize_t (*__libc_writev)(int fd, const struct iovec *iov, int iovcnt);

#define SWRAP_SYMBOL_ENTRY(i) \
	union { \
		__libc_##i f; \
		void *obj; \
	} _libc_##i

struct swrap_libc_symbols {
#ifdef HAVE_ACCEPT4
	SWRAP_SYMBOL_ENTRY(accept4);
#else
	SWRAP_SYMBOL_ENTRY(accept);
#endif
	SWRAP_SYMBOL_ENTRY(bind);
	SWRAP_SYMBOL_ENTRY(close);
	SWRAP_SYMBOL_ENTRY(connect);
	SWRAP_SYMBOL_ENTRY(dup);
	SWRAP_SYMBOL_ENTRY(dup2);
	SWRAP_SYMBOL_ENTRY(fcntl);
	SWRAP_SYMBOL_ENTRY(fopen);
#ifdef HAVE_FOPEN64
	SWRAP_SYMBOL_ENTRY(fopen64);
#endif
#ifdef HAVE_EVENTFD
	SWRAP_SYMBOL_ENTRY(eventfd);
#endif
	SWRAP_SYMBOL_ENTRY(getpeername);
	SWRAP_SYMBOL_ENTRY(getsockname);
	SWRAP_SYMBOL_ENTRY(getsockopt);
	SWRAP_SYMBOL_ENTRY(ioctl);
	SWRAP_SYMBOL_ENTRY(listen);
	SWRAP_SYMBOL_ENTRY(open);
#ifdef HAVE_OPEN64
	SWRAP_SYMBOL_ENTRY(open64);
#endif
	SWRAP_SYMBOL_ENTRY(openat);
	SWRAP_SYMBOL_ENTRY(pipe);
	SWRAP_SYMBOL_ENTRY(read);
	SWRAP_SYMBOL_ENTRY(readv);
	SWRAP_SYMBOL_ENTRY(recv);
	SWRAP_SYMBOL_ENTRY(recvfrom);
	SWRAP_SYMBOL_ENTRY(recvmsg);
	SWRAP_SYMBOL_ENTRY(send);
	SWRAP_SYMBOL_ENTRY(sendmsg);
	SWRAP_SYMBOL_ENTRY(sendto);
	SWRAP_SYMBOL_ENTRY(setsockopt);
#ifdef HAVE_SIGNALFD
	SWRAP_SYMBOL_ENTRY(signalfd);
#endif
	SWRAP_SYMBOL_ENTRY(socket);
	SWRAP_SYMBOL_ENTRY(socketpair);
#ifdef HAVE_TIMERFD_CREATE
	SWRAP_SYMBOL_ENTRY(timerfd_create);
#endif
	SWRAP_SYMBOL_ENTRY(write);
	SWRAP_SYMBOL_ENTRY(writev);
};

struct swrap {
	struct {
		void *handle;
		void *socket_handle;
		struct swrap_libc_symbols symbols;
	} libc;
};

static struct swrap swrap;

/* prototypes */
static char *socket_wrapper_dir(void);

#define LIBC_NAME "libc.so"

enum swrap_lib {
    SWRAP_LIBC,
    SWRAP_LIBNSL,
    SWRAP_LIBSOCKET,
};

static const char *swrap_str_lib(enum swrap_lib lib)
{
	switch (lib) {
	case SWRAP_LIBC:
		return "libc";
	case SWRAP_LIBNSL:
		return "libnsl";
	case SWRAP_LIBSOCKET:
		return "libsocket";
	}

	/* Compiler would warn us about unhandled enum value if we get here */
	return "unknown";
}

static void *swrap_load_lib_handle(enum swrap_lib lib)
{
	int flags = RTLD_LAZY;
	void *handle = NULL;
	int i;

#ifdef RTLD_DEEPBIND
	const char *env_preload = getenv("LD_PRELOAD");
	const char *env_deepbind = getenv("SOCKET_WRAPPER_DISABLE_DEEPBIND");
	bool enable_deepbind = true;

	/* Don't do a deepbind if we run with libasan */
	if (env_preload != NULL && strlen(env_preload) < 1024) {
		const char *p = strstr(env_preload, "libasan.so");
		if (p != NULL) {
			enable_deepbind = false;
		}
	}

	if (env_deepbind != NULL && strlen(env_deepbind) >= 1) {
		enable_deepbind = false;
	}

	if (enable_deepbind) {
		flags |= RTLD_DEEPBIND;
	}
#endif

	switch (lib) {
	case SWRAP_LIBNSL:
	case SWRAP_LIBSOCKET:
#ifdef HAVE_LIBSOCKET
		handle = swrap.libc.socket_handle;
		if (handle == NULL) {
			for (i = 10; i >= 0; i--) {
				char soname[256] = {0};

				snprintf(soname, sizeof(soname), "libsocket.so.%d", i);
				handle = dlopen(soname, flags);
				if (handle != NULL) {
					break;
				}
			}

			swrap.libc.socket_handle = handle;
		}
		break;
#endif
	case SWRAP_LIBC:
		handle = swrap.libc.handle;
#ifdef LIBC_SO
		if (handle == NULL) {
			handle = dlopen(LIBC_SO, flags);

			swrap.libc.handle = handle;
		}
#endif
		if (handle == NULL) {
			for (i = 10; i >= 0; i--) {
				char soname[256] = {0};

				snprintf(soname, sizeof(soname), "libc.so.%d", i);
				handle = dlopen(soname, flags);
				if (handle != NULL) {
					break;
				}
			}

			swrap.libc.handle = handle;
		}
		break;
	}

	if (handle == NULL) {
#ifdef RTLD_NEXT
		handle = swrap.libc.handle = swrap.libc.socket_handle = RTLD_NEXT;
#else
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to dlopen library: %s",
			  dlerror());
		exit(-1);
#endif
	}

	return handle;
}

static void *_swrap_bind_symbol(enum swrap_lib lib, const char *fn_name)
{
	void *handle;
	void *func;

	handle = swrap_load_lib_handle(lib);

	func = dlsym(handle, fn_name);
	if (func == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to find %s: %s",
			  fn_name,
			  dlerror());
		exit(-1);
	}

	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "Loaded %s from %s",
		  fn_name,
		  swrap_str_lib(lib));

	return func;
}

static void swrap_mutex_lock(pthread_mutex_t *mutex)
{
	int ret;

	ret = pthread_mutex_lock(mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR, "Couldn't lock pthread mutex - %s",
			  strerror(ret));
	}
}

static void swrap_mutex_unlock(pthread_mutex_t *mutex)
{
	int ret;

	ret = pthread_mutex_unlock(mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR, "Couldn't unlock pthread mutex - %s",
			  strerror(ret));
	}
}

/*
 * These macros have a thread race condition on purpose!
 *
 * This is an optimization to avoid locking each time we check if the symbol is
 * bound.
 */
#define swrap_bind_symbol_libc(sym_name) \
	if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
		swrap_mutex_lock(&libc_symbol_binding_mutex); \
		if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
			swrap.libc.symbols._libc_##sym_name.obj = \
				_swrap_bind_symbol(SWRAP_LIBC, #sym_name); \
		} \
		swrap_mutex_unlock(&libc_symbol_binding_mutex); \
	}

#define swrap_bind_symbol_libsocket(sym_name) \
	if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
		swrap_mutex_lock(&libc_symbol_binding_mutex); \
		if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
			swrap.libc.symbols._libc_##sym_name.obj = \
				_swrap_bind_symbol(SWRAP_LIBSOCKET, #sym_name); \
		} \
		swrap_mutex_unlock(&libc_symbol_binding_mutex); \
	}

#define swrap_bind_symbol_libnsl(sym_name) \
	if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
		swrap_mutex_lock(&libc_symbol_binding_mutex); \
		if (swrap.libc.symbols._libc_##sym_name.obj == NULL) { \
			swrap.libc.symbols._libc_##sym_name.obj = \
				_swrap_bind_symbol(SWRAP_LIBNSL, #sym_name); \
		} \
		swrap_mutex_unlock(&libc_symbol_binding_mutex); \
	}

/****************************************************************************
 *                               IMPORTANT
 ****************************************************************************
 *
 * Functions especially from libc need to be loaded individually, you can't
 * load all at once or gdb will segfault at startup. The same applies to
 * valgrind and has probably something todo with with the linker.  So we need
 * load each function at the point it is called the first time.
 *
 ****************************************************************************/

#ifdef HAVE_ACCEPT4
static int libc_accept4(int sockfd,
			struct sockaddr *addr,
			socklen_t *addrlen,
			int flags)
{
	swrap_bind_symbol_libsocket(accept4);

	return swrap.libc.symbols._libc_accept4.f(sockfd, addr, addrlen, flags);
}

#else /* HAVE_ACCEPT4 */

static int libc_accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
{
	swrap_bind_symbol_libsocket(accept);

	return swrap.libc.symbols._libc_accept.f(sockfd, addr, addrlen);
}
#endif /* HAVE_ACCEPT4 */

static int libc_bind(int sockfd,
		     const struct sockaddr *addr,
		     socklen_t addrlen)
{
	swrap_bind_symbol_libsocket(bind);

	return swrap.libc.symbols._libc_bind.f(sockfd, addr, addrlen);
}

static int libc_close(int fd)
{
	swrap_bind_symbol_libc(close);

	return swrap.libc.symbols._libc_close.f(fd);
}

static int libc_connect(int sockfd,
			const struct sockaddr *addr,
			socklen_t addrlen)
{
	swrap_bind_symbol_libsocket(connect);

	return swrap.libc.symbols._libc_connect.f(sockfd, addr, addrlen);
}

static int libc_dup(int fd)
{
	swrap_bind_symbol_libc(dup);

	return swrap.libc.symbols._libc_dup.f(fd);
}

static int libc_dup2(int oldfd, int newfd)
{
	swrap_bind_symbol_libc(dup2);

	return swrap.libc.symbols._libc_dup2.f(oldfd, newfd);
}

#ifdef HAVE_EVENTFD
static int libc_eventfd(int count, int flags)
{
	swrap_bind_symbol_libc(eventfd);

	return swrap.libc.symbols._libc_eventfd.f(count, flags);
}
#endif

DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE
static int libc_vfcntl(int fd, int cmd, va_list ap)
{
	void *arg;
	int rc;

	swrap_bind_symbol_libc(fcntl);

	arg = va_arg(ap, void *);

	rc = swrap.libc.symbols._libc_fcntl.f(fd, cmd, arg);

	return rc;
}

static int libc_getpeername(int sockfd,
			    struct sockaddr *addr,
			    socklen_t *addrlen)
{
	swrap_bind_symbol_libsocket(getpeername);

	return swrap.libc.symbols._libc_getpeername.f(sockfd, addr, addrlen);
}

static int libc_getsockname(int sockfd,
			    struct sockaddr *addr,
			    socklen_t *addrlen)
{
	swrap_bind_symbol_libsocket(getsockname);

	return swrap.libc.symbols._libc_getsockname.f(sockfd, addr, addrlen);
}

static int libc_getsockopt(int sockfd,
			   int level,
			   int optname,
			   void *optval,
			   socklen_t *optlen)
{
	swrap_bind_symbol_libsocket(getsockopt);

	return swrap.libc.symbols._libc_getsockopt.f(sockfd,
						     level,
						     optname,
						     optval,
						     optlen);
}

DO_NOT_SANITIZE_ADDRESS_ATTRIBUTE
static int libc_vioctl(int d, unsigned long int request, va_list ap)
{
	void *arg;
	int rc;

	swrap_bind_symbol_libc(ioctl);

	arg = va_arg(ap, void *);

	rc = swrap.libc.symbols._libc_ioctl.f(d, request, arg);

	return rc;
}

static int libc_listen(int sockfd, int backlog)
{
	swrap_bind_symbol_libsocket(listen);

	return swrap.libc.symbols._libc_listen.f(sockfd, backlog);
}

static FILE *libc_fopen(const char *name, const char *mode)
{
	swrap_bind_symbol_libc(fopen);

	return swrap.libc.symbols._libc_fopen.f(name, mode);
}

#ifdef HAVE_FOPEN64
static FILE *libc_fopen64(const char *name, const char *mode)
{
	swrap_bind_symbol_libc(fopen64);

	return swrap.libc.symbols._libc_fopen64.f(name, mode);
}
#endif /* HAVE_FOPEN64 */

static int libc_vopen(const char *pathname, int flags, va_list ap)
{
	int mode = 0;
	int fd;

	swrap_bind_symbol_libc(open);

	if (flags & O_CREAT) {
		mode = va_arg(ap, int);
	}
	fd = swrap.libc.symbols._libc_open.f(pathname, flags, (mode_t)mode);

	return fd;
}

static int libc_open(const char *pathname, int flags, ...)
{
	va_list ap;
	int fd;

	va_start(ap, flags);
	fd = libc_vopen(pathname, flags, ap);
	va_end(ap);

	return fd;
}

#ifdef HAVE_OPEN64
static int libc_vopen64(const char *pathname, int flags, va_list ap)
{
	int mode = 0;
	int fd;

	swrap_bind_symbol_libc(open64);

	if (flags & O_CREAT) {
		mode = va_arg(ap, int);
	}
	fd = swrap.libc.symbols._libc_open64.f(pathname, flags, (mode_t)mode);

	return fd;
}
#endif /* HAVE_OPEN64 */

static int libc_vopenat(int dirfd, const char *path, int flags, va_list ap)
{
	int mode = 0;
	int fd;

	swrap_bind_symbol_libc(openat);

	if (flags & O_CREAT) {
		mode = va_arg(ap, int);
	}
	fd = swrap.libc.symbols._libc_openat.f(dirfd,
					       path,
					       flags,
					       (mode_t)mode);

	return fd;
}

#if 0
static int libc_openat(int dirfd, const char *path, int flags, ...)
{
	va_list ap;
	int fd;

	va_start(ap, flags);
	fd = libc_vopenat(dirfd, path, flags, ap);
	va_end(ap);

	return fd;
}
#endif

static int libc_pipe(int pipefd[2])
{
	swrap_bind_symbol_libsocket(pipe);

	return swrap.libc.symbols._libc_pipe.f(pipefd);
}

static int libc_read(int fd, void *buf, size_t count)
{
	swrap_bind_symbol_libc(read);

	return swrap.libc.symbols._libc_read.f(fd, buf, count);
}

static ssize_t libc_readv(int fd, const struct iovec *iov, int iovcnt)
{
	swrap_bind_symbol_libsocket(readv);

	return swrap.libc.symbols._libc_readv.f(fd, iov, iovcnt);
}

static int libc_recv(int sockfd, void *buf, size_t len, int flags)
{
	swrap_bind_symbol_libsocket(recv);

	return swrap.libc.symbols._libc_recv.f(sockfd, buf, len, flags);
}

static int libc_recvfrom(int sockfd,
			 void *buf,
			 size_t len,
			 int flags,
			 struct sockaddr *src_addr,
			 socklen_t *addrlen)
{
	swrap_bind_symbol_libsocket(recvfrom);

	return swrap.libc.symbols._libc_recvfrom.f(sockfd,
						   buf,
						   len,
						   flags,
						   src_addr,
						   addrlen);
}

static int libc_recvmsg(int sockfd, struct msghdr *msg, int flags)
{
	swrap_bind_symbol_libsocket(recvmsg);

	return swrap.libc.symbols._libc_recvmsg.f(sockfd, msg, flags);
}

static int libc_send(int sockfd, const void *buf, size_t len, int flags)
{
	swrap_bind_symbol_libsocket(send);

	return swrap.libc.symbols._libc_send.f(sockfd, buf, len, flags);
}

static int libc_sendmsg(int sockfd, const struct msghdr *msg, int flags)
{
	swrap_bind_symbol_libsocket(sendmsg);

	return swrap.libc.symbols._libc_sendmsg.f(sockfd, msg, flags);
}

static int libc_sendto(int sockfd,
		       const void *buf,
		       size_t len,
		       int flags,
		       const  struct sockaddr *dst_addr,
		       socklen_t addrlen)
{
	swrap_bind_symbol_libsocket(sendto);

	return swrap.libc.symbols._libc_sendto.f(sockfd,
						 buf,
						 len,
						 flags,
						 dst_addr,
						 addrlen);
}

static int libc_setsockopt(int sockfd,
			   int level,
			   int optname,
			   const void *optval,
			   socklen_t optlen)
{
	swrap_bind_symbol_libsocket(setsockopt);

	return swrap.libc.symbols._libc_setsockopt.f(sockfd,
						     level,
						     optname,
						     optval,
						     optlen);
}

#ifdef HAVE_SIGNALFD
static int libc_signalfd(int fd, const sigset_t *mask, int flags)
{
	swrap_bind_symbol_libsocket(signalfd);

	return swrap.libc.symbols._libc_signalfd.f(fd, mask, flags);
}
#endif

static int libc_socket(int domain, int type, int protocol)
{
	swrap_bind_symbol_libsocket(socket);

	return swrap.libc.symbols._libc_socket.f(domain, type, protocol);
}

static int libc_socketpair(int domain, int type, int protocol, int sv[2])
{
	swrap_bind_symbol_libsocket(socketpair);

	return swrap.libc.symbols._libc_socketpair.f(domain, type, protocol, sv);
}

#ifdef HAVE_TIMERFD_CREATE
static int libc_timerfd_create(int clockid, int flags)
{
	swrap_bind_symbol_libc(timerfd_create);

	return swrap.libc.symbols._libc_timerfd_create.f(clockid, flags);
}
#endif

static ssize_t libc_write(int fd, const void *buf, size_t count)
{
	swrap_bind_symbol_libc(write);

	return swrap.libc.symbols._libc_write.f(fd, buf, count);
}

static ssize_t libc_writev(int fd, const struct iovec *iov, int iovcnt)
{
	swrap_bind_symbol_libsocket(writev);

	return swrap.libc.symbols._libc_writev.f(fd, iov, iovcnt);
}

/* DO NOT call this function during library initialization! */
static void swrap_bind_symbol_all(void)
{
#ifdef HAVE_ACCEPT4
	swrap_bind_symbol_libsocket(accept4);
#else
	swrap_bind_symbol_libsocket(accept);
#endif
	swrap_bind_symbol_libsocket(bind);
	swrap_bind_symbol_libc(close);
	swrap_bind_symbol_libsocket(connect);
	swrap_bind_symbol_libc(dup);
	swrap_bind_symbol_libc(dup2);
	swrap_bind_symbol_libc(fcntl);
	swrap_bind_symbol_libc(fopen);
#ifdef HAVE_FOPEN64
	swrap_bind_symbol_libc(fopen64);
#endif
#ifdef HAVE_EVENTFD
	swrap_bind_symbol_libc(eventfd);
#endif
	swrap_bind_symbol_libsocket(getpeername);
	swrap_bind_symbol_libsocket(getsockname);
	swrap_bind_symbol_libsocket(getsockopt);
	swrap_bind_symbol_libc(ioctl);
	swrap_bind_symbol_libsocket(listen);
	swrap_bind_symbol_libc(open);
#ifdef HAVE_OPEN64
	swrap_bind_symbol_libc(open64);
#endif
	swrap_bind_symbol_libc(openat);
	swrap_bind_symbol_libsocket(pipe);
	swrap_bind_symbol_libc(read);
	swrap_bind_symbol_libsocket(readv);
	swrap_bind_symbol_libsocket(recv);
	swrap_bind_symbol_libsocket(recvfrom);
	swrap_bind_symbol_libsocket(recvmsg);
	swrap_bind_symbol_libsocket(send);
	swrap_bind_symbol_libsocket(sendmsg);
	swrap_bind_symbol_libsocket(sendto);
	swrap_bind_symbol_libsocket(setsockopt);
#ifdef HAVE_SIGNALFD
	swrap_bind_symbol_libsocket(signalfd);
#endif
	swrap_bind_symbol_libsocket(socket);
	swrap_bind_symbol_libsocket(socketpair);
#ifdef HAVE_TIMERFD_CREATE
	swrap_bind_symbol_libc(timerfd_create);
#endif
	swrap_bind_symbol_libc(write);
	swrap_bind_symbol_libsocket(writev);
}

/*********************************************************
 * SWRAP HELPER FUNCTIONS
 *********************************************************/

/*
 * We return 127.0.0.0 (default) or 10.53.57.0.
 *
 * This can be controlled by:
 * SOCKET_WRAPPER_IPV4_NETWORK=127.0.0.0 (default)
 * or
 * SOCKET_WRAPPER_IPV4_NETWORK=10.53.57.0
 */
static in_addr_t swrap_ipv4_net(void)
{
	static int initialized;
	static in_addr_t hv;
	const char *net_str = NULL;
	struct in_addr nv;
	int ret;

	if (initialized) {
		return hv;
	}
	initialized = 1;

	net_str = getenv("SOCKET_WRAPPER_IPV4_NETWORK");
	if (net_str == NULL) {
		net_str = "127.0.0.0";
	}

	ret = inet_pton(AF_INET, net_str, &nv);
	if (ret <= 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "INVALID IPv4 Network [%s]",
			  net_str);
		abort();
	}

	hv = ntohl(nv.s_addr);

	switch (hv) {
	case 0x7f000000:
		/* 127.0.0.0 */
		break;
	case 0x0a353900:
		/* 10.53.57.0 */
		break;
	default:
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "INVALID IPv4 Network [%s][0x%x] should be "
			  "127.0.0.0 or 10.53.57.0",
			  net_str, (unsigned)hv);
		abort();
	}

	return hv;
}

/*
 * This returns 127.255.255.255 or 10.255.255.255
 */
static in_addr_t swrap_ipv4_bcast(void)
{
	in_addr_t hv;

	hv = swrap_ipv4_net();
	hv |= IN_CLASSA_HOST;

	return hv;
}

/*
 * This returns 127.0.0.${iface} or 10.53.57.${iface}
 */
static in_addr_t swrap_ipv4_iface(unsigned int iface)
{
	in_addr_t hv;

	if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "swrap_ipv4_iface(%u) invalid!",
			  iface);
		abort();
		return -1;
	}

	hv = swrap_ipv4_net();
	hv |= iface;

	return hv;
}

#ifdef HAVE_IPV6
/*
 * FD00::5357:5FXX
 */
static const struct in6_addr *swrap_ipv6(void)
{
	static struct in6_addr v;
	static int initialized;
	int ret;

	if (initialized) {
		return &v;
	}
	initialized = 1;

	ret = inet_pton(AF_INET6, "FD00::5357:5F00", &v);
	if (ret <= 0) {
		abort();
	}

	return &v;
}
#endif

static void set_port(int family, int prt, struct swrap_address *addr)
{
	switch (family) {
	case AF_INET:
		addr->sa.in.sin_port = htons(prt);
		break;
#ifdef HAVE_IPV6
	case AF_INET6:
		addr->sa.in6.sin6_port = htons(prt);
		break;
#endif
	}
}

static size_t socket_length(int family)
{
	switch (family) {
	case AF_INET:
		return sizeof(struct sockaddr_in);
#ifdef HAVE_IPV6
	case AF_INET6:
		return sizeof(struct sockaddr_in6);
#endif
	}
	return 0;
}

static struct socket_info *swrap_get_socket_info(int si_index)
{
	return (struct socket_info *)(&(sockets[si_index].info));
}

static int swrap_get_refcount(struct socket_info *si)
{
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si);
	return sic->meta.refcount;
}

static void swrap_inc_refcount(struct socket_info *si)
{
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si);

	sic->meta.refcount += 1;
}

static void swrap_dec_refcount(struct socket_info *si)
{
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si);

	sic->meta.refcount -= 1;
}

static int swrap_get_next_free(struct socket_info *si)
{
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si);

	return sic->meta.next_free;
}

static void swrap_set_next_free(struct socket_info *si, int next_free)
{
	struct socket_info_container *sic = SOCKET_INFO_CONTAINER(si);

	sic->meta.next_free = next_free;
}

static int swrap_un_path(struct sockaddr_un *un,
			 const char *swrap_dir,
			 char type,
			 unsigned int iface,
			 unsigned int prt)
{
	int ret;

	ret = snprintf(un->sun_path,
		       sizeof(un->sun_path),
		       "%s/"SOCKET_FORMAT,
		       swrap_dir,
		       type,
		       iface,
		       prt);
	if ((size_t)ret >= sizeof(un->sun_path)) {
		return ENAMETOOLONG;
	}

	return 0;
}

static int swrap_un_path_EINVAL(struct sockaddr_un *un,
				const char *swrap_dir)
{
	int ret;

	ret = snprintf(un->sun_path,
		       sizeof(un->sun_path),
		       "%s/EINVAL",
		       swrap_dir);

	if ((size_t)ret >= sizeof(un->sun_path)) {
		return ENAMETOOLONG;
	}

	return 0;
}

static bool swrap_dir_usable(const char *swrap_dir)
{
	struct sockaddr_un un;
	int ret;

	ret = swrap_un_path(&un, swrap_dir, SOCKET_TYPE_CHAR_TCP, 0, 0);
	if (ret == 0) {
		return true;
	}

	ret = swrap_un_path_EINVAL(&un, swrap_dir);
	if (ret == 0) {
		return true;
	}

	return false;
}

static char *socket_wrapper_dir(void)
{
	char *swrap_dir = NULL;
	char *s = getenv("SOCKET_WRAPPER_DIR");
	char *t;
	bool ok;

	if (s == NULL) {
		SWRAP_LOG(SWRAP_LOG_WARN, "SOCKET_WRAPPER_DIR not set");
		return NULL;
	}

	swrap_dir = realpath(s, NULL);
	if (swrap_dir == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Unable to resolve socket_wrapper dir path: %s",
			  strerror(errno));
		abort();
	}

	ok = swrap_dir_usable(swrap_dir);
	if (ok) {
		goto done;
	}

	free(swrap_dir);

	ok = swrap_dir_usable(s);
	if (!ok) {
		SWRAP_LOG(SWRAP_LOG_ERROR, "SOCKET_WRAPPER_DIR is too long");
		abort();
	}

	t = getenv("SOCKET_WRAPPER_DIR_ALLOW_ORIG");
	if (t == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "realpath(SOCKET_WRAPPER_DIR) too long and "
			  "SOCKET_WRAPPER_DIR_ALLOW_ORIG not set");
		abort();

	}

	swrap_dir = strdup(s);
	if (swrap_dir == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Unable to duplicate socket_wrapper dir path");
		abort();
	}

	SWRAP_LOG(SWRAP_LOG_WARN,
		  "realpath(SOCKET_WRAPPER_DIR) too long, "
		  "using original SOCKET_WRAPPER_DIR\n");

done:
	SWRAP_LOG(SWRAP_LOG_TRACE, "socket_wrapper_dir: %s", swrap_dir);
	return swrap_dir;
}

static unsigned int socket_wrapper_mtu(void)
{
	static unsigned int max_mtu = 0;
	unsigned int tmp;
	const char *s;
	char *endp;

	swrap_mutex_lock(&mtu_update_mutex);

	if (max_mtu != 0) {
		goto done;
	}

	max_mtu = SOCKET_WRAPPER_MTU_DEFAULT;

	s = getenv("SOCKET_WRAPPER_MTU");
	if (s == NULL) {
		goto done;
	}

	tmp = strtol(s, &endp, 10);
	if (s == endp) {
		goto done;
	}

	if (tmp < SOCKET_WRAPPER_MTU_MIN || tmp > SOCKET_WRAPPER_MTU_MAX) {
		goto done;
	}
	max_mtu = tmp;

done:
	swrap_mutex_unlock(&mtu_update_mutex);
	return max_mtu;
}

static int socket_wrapper_init_mutex(pthread_mutex_t *m)
{
	pthread_mutexattr_t ma;
	int ret;

	ret = pthread_mutexattr_init(&ma);
	if (ret != 0) {
		return ret;
	}

	ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK);
	if (ret != 0) {
		goto done;
	}

	ret = pthread_mutex_init(m, &ma);

done:
	pthread_mutexattr_destroy(&ma);

	return ret;
}

static size_t socket_wrapper_max_sockets(void)
{
	const char *s;
	size_t tmp;
	char *endp;

	if (socket_info_max != 0) {
		return socket_info_max;
	}

	socket_info_max = SOCKET_WRAPPER_MAX_SOCKETS_DEFAULT;

	s = getenv("SOCKET_WRAPPER_MAX_SOCKETS");
	if (s == NULL || s[0] == '\0') {
		goto done;
	}

	tmp = strtoul(s, &endp, 10);
	if (s == endp) {
		goto done;
	}
	if (tmp == 0) {
		tmp = SOCKET_WRAPPER_MAX_SOCKETS_DEFAULT;
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Invalid number of sockets specified, "
			  "using default (%zu)",
			  tmp);
	}

	if (tmp > SOCKET_WRAPPER_MAX_SOCKETS_LIMIT) {
		tmp = SOCKET_WRAPPER_MAX_SOCKETS_LIMIT;
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Invalid number of sockets specified, "
			  "using maximum (%zu).",
			  tmp);
	}

	socket_info_max = tmp;

done:
	return socket_info_max;
}

static void socket_wrapper_init_fds_idx(void)
{
	int *tmp = NULL;
	size_t i;

	if (socket_fds_idx != NULL) {
		return;
	}

	tmp = (int *)calloc(socket_fds_max, sizeof(int));
	if (tmp == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to allocate socket fds index array: %s",
			  strerror(errno));
		exit(-1);
	}

	for (i = 0; i < socket_fds_max; i++) {
		tmp[i] = -1;
	}

	socket_fds_idx = tmp;
}

static void socket_wrapper_init_sockets(void)
{
	size_t max_sockets;
	size_t i;
	int ret;

	swrap_mutex_lock(&sockets_mutex);

	if (sockets != NULL) {
		swrap_mutex_unlock(&sockets_mutex);
		return;
	}

	/*
	 * Intialize the static cache early before
	 * any thread is able to start.
	 */
	(void)swrap_ipv4_net();

	socket_wrapper_init_fds_idx();

	/* Needs to be called inside the sockets_mutex lock here. */
	max_sockets = socket_wrapper_max_sockets();

	sockets = (struct socket_info_container *)calloc(max_sockets,
					sizeof(struct socket_info_container));

	if (sockets == NULL) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to allocate sockets array: %s",
			  strerror(errno));
		swrap_mutex_unlock(&sockets_mutex);
		exit(-1);
	}

	swrap_mutex_lock(&first_free_mutex);

	first_free = 0;

	for (i = 0; i < max_sockets; i++) {
		swrap_set_next_free(&sockets[i].info, i+1);
		ret = socket_wrapper_init_mutex(&sockets[i].meta.mutex);
		if (ret != 0) {
			SWRAP_LOG(SWRAP_LOG_ERROR,
				  "Failed to initialize pthread mutex");
			goto done;
		}
	}

	/* mark the end of the free list */
	swrap_set_next_free(&sockets[max_sockets-1].info, -1);

	ret = socket_wrapper_init_mutex(&autobind_start_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		goto done;
	}

	ret = socket_wrapper_init_mutex(&pcap_dump_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		goto done;
	}

	ret = socket_wrapper_init_mutex(&mtu_update_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		goto done;
	}

done:
	swrap_mutex_unlock(&first_free_mutex);
	swrap_mutex_unlock(&sockets_mutex);
	if (ret != 0) {
		exit(-1);
	}
}

bool socket_wrapper_enabled(void)
{
	char *s = socket_wrapper_dir();

	if (s == NULL) {
		return false;
	}

	SAFE_FREE(s);

	socket_wrapper_init_sockets();

	return true;
}

static unsigned int socket_wrapper_default_iface(void)
{
	const char *s = getenv("SOCKET_WRAPPER_DEFAULT_IFACE");
	if (s) {
		unsigned int iface;
		if (sscanf(s, "%u", &iface) == 1) {
			if (iface >= 1 && iface <= MAX_WRAPPED_INTERFACES) {
				return iface;
			}
		}
	}

	return 1;/* 127.0.0.1 */
}

static void set_socket_info_index(int fd, int idx)
{
	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "fd=%d idx=%d",
		  fd, idx);
	socket_fds_idx[fd] = idx;
	/* This builtin issues a full memory barrier. */
	__sync_synchronize();
}

static void reset_socket_info_index(int fd)
{
	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "fd=%d idx=%d",
		  fd, -1);
	set_socket_info_index(fd, -1);
}

static int find_socket_info_index(int fd)
{
	if (fd < 0) {
		return -1;
	}

	if (socket_fds_idx == NULL) {
		return -1;
	}

	if ((size_t)fd >= socket_fds_max) {
		/*
		 * Do not add a log here as some applications do stupid things
		 * like:
		 *
		 *     for (fd = 0; fd <= getdtablesize(); fd++) {
		 *         close(fd)
		 *     };
		 *
		 * This would produce millions of lines of debug messages.
		 */
#if 0
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Looking for a socket info for the fd %d is over the "
			  "max socket index limit of %zu.",
			  fd,
			  socket_fds_max);
#endif
		return -1;
	}

	/* This builtin issues a full memory barrier. */
	__sync_synchronize();
	return socket_fds_idx[fd];
}

static int swrap_add_socket_info(struct socket_info *si_input)
{
	struct socket_info *si = NULL;
	int si_index = -1;

	if (si_input == NULL) {
		errno = EINVAL;
		return -1;
	}

	swrap_mutex_lock(&first_free_mutex);
	if (first_free == -1) {
		errno = ENFILE;
		goto out;
	}

	si_index = first_free;
	si = swrap_get_socket_info(si_index);

	SWRAP_LOCK_SI(si);

	first_free = swrap_get_next_free(si);
	*si = *si_input;
	swrap_inc_refcount(si);

	SWRAP_UNLOCK_SI(si);

out:
	swrap_mutex_unlock(&first_free_mutex);

	return si_index;
}

static int swrap_create_socket(struct socket_info *si, int fd)
{
	int idx;

	if ((size_t)fd >= socket_fds_max) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "The max socket index limit of %zu has been reached, "
			  "trying to add %d",
			  socket_fds_max,
			  fd);
		return -1;
	}

	idx = swrap_add_socket_info(si);
	if (idx == -1) {
		return -1;
	}

	set_socket_info_index(fd, idx);

	return idx;
}

static int convert_un_in(const struct sockaddr_un *un, struct sockaddr *in, socklen_t *len)
{
	unsigned int iface;
	unsigned int prt;
	const char *p;
	char type;

	p = strrchr(un->sun_path, '/');
	if (p) p++; else p = un->sun_path;

	if (sscanf(p, SOCKET_FORMAT, &type, &iface, &prt) != 3) {
		errno = EINVAL;
		return -1;
	}

	SWRAP_LOG(SWRAP_LOG_TRACE, "type %c iface %u port %u",
			type, iface, prt);

	if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
		errno = EINVAL;
		return -1;
	}

	if (prt > 0xFFFF) {
		errno = EINVAL;
		return -1;
	}

	switch(type) {
	case SOCKET_TYPE_CHAR_TCP:
	case SOCKET_TYPE_CHAR_UDP: {
		struct sockaddr_in *in2 = (struct sockaddr_in *)(void *)in;

		if ((*len) < sizeof(*in2)) {
		    errno = EINVAL;
		    return -1;
		}

		memset(in2, 0, sizeof(*in2));
		in2->sin_family = AF_INET;
		in2->sin_addr.s_addr = htonl(swrap_ipv4_iface(iface));
		in2->sin_port = htons(prt);

		*len = sizeof(*in2);
		break;
	}
#ifdef HAVE_IPV6
	case SOCKET_TYPE_CHAR_TCP_V6:
	case SOCKET_TYPE_CHAR_UDP_V6: {
		struct sockaddr_in6 *in2 = (struct sockaddr_in6 *)(void *)in;

		if ((*len) < sizeof(*in2)) {
			errno = EINVAL;
			return -1;
		}

		memset(in2, 0, sizeof(*in2));
		in2->sin6_family = AF_INET6;
		in2->sin6_addr = *swrap_ipv6();
		in2->sin6_addr.s6_addr[15] = iface;
		in2->sin6_port = htons(prt);

		*len = sizeof(*in2);
		break;
	}
#endif
	default:
		errno = EINVAL;
		return -1;
	}

	return 0;
}

static int convert_in_un_remote(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
				int *bcast)
{
	char type = '\0';
	unsigned int prt;
	unsigned int iface;
	int is_bcast = 0;
	char *swrap_dir = NULL;

	if (bcast) *bcast = 0;

	switch (inaddr->sa_family) {
	case AF_INET: {
		const struct sockaddr_in *in =
		    (const struct sockaddr_in *)(const void *)inaddr;
		unsigned int addr = ntohl(in->sin_addr.s_addr);
		char u_type = '\0';
		char b_type = '\0';
		char a_type = '\0';
		const unsigned int sw_net_addr = swrap_ipv4_net();
		const unsigned int sw_bcast_addr = swrap_ipv4_bcast();

		switch (si->type) {
		case SOCK_STREAM:
			u_type = SOCKET_TYPE_CHAR_TCP;
			break;
		case SOCK_DGRAM:
			u_type = SOCKET_TYPE_CHAR_UDP;
			a_type = SOCKET_TYPE_CHAR_UDP;
			b_type = SOCKET_TYPE_CHAR_UDP;
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}

		prt = ntohs(in->sin_port);
		if (a_type && addr == 0xFFFFFFFF) {
			/* 255.255.255.255 only udp */
			is_bcast = 2;
			type = a_type;
			iface = socket_wrapper_default_iface();
		} else if (b_type && addr == sw_bcast_addr) {
			/*
			 * 127.255.255.255
			 * or
			 * 10.255.255.255
			 * only udp
			 */
			is_bcast = 1;
			type = b_type;
			iface = socket_wrapper_default_iface();
		} else if ((addr & 0xFFFFFF00) == sw_net_addr) {
			/* 127.0.0.X or 10.53.57.X */
			is_bcast = 0;
			type = u_type;
			iface = (addr & 0x000000FF);
		} else {
			errno = ENETUNREACH;
			return -1;
		}
		if (bcast) *bcast = is_bcast;
		break;
	}
#ifdef HAVE_IPV6
	case AF_INET6: {
		const struct sockaddr_in6 *in =
		    (const struct sockaddr_in6 *)(const void *)inaddr;
		struct in6_addr cmp1, cmp2;

		switch (si->type) {
		case SOCK_STREAM:
			type = SOCKET_TYPE_CHAR_TCP_V6;
			break;
		case SOCK_DGRAM:
			type = SOCKET_TYPE_CHAR_UDP_V6;
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}

		/* XXX no multicast/broadcast */

		prt = ntohs(in->sin6_port);

		cmp1 = *swrap_ipv6();
		cmp2 = in->sin6_addr;
		cmp2.s6_addr[15] = 0;
		if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) {
			iface = in->sin6_addr.s6_addr[15];
		} else {
			errno = ENETUNREACH;
			return -1;
		}

		break;
	}
#endif
	default:
		SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family!");
		errno = ENETUNREACH;
		return -1;
	}

	if (prt == 0) {
		SWRAP_LOG(SWRAP_LOG_WARN, "Port not set");
		errno = EINVAL;
		return -1;
	}

	swrap_dir = socket_wrapper_dir();
	if (swrap_dir == NULL) {
		errno = EINVAL;
		return -1;
	}

	if (is_bcast) {
		swrap_un_path_EINVAL(un, swrap_dir);
		SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);
		SAFE_FREE(swrap_dir);
		/* the caller need to do more processing */
		return 0;
	}

	swrap_un_path(un, swrap_dir, type, iface, prt);
	SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);

	SAFE_FREE(swrap_dir);

	return 0;
}

static int convert_in_un_alloc(struct socket_info *si, const struct sockaddr *inaddr, struct sockaddr_un *un,
			       int *bcast)
{
	char type = '\0';
	unsigned int prt;
	unsigned int iface;
	struct stat st;
	int is_bcast = 0;
	char *swrap_dir = NULL;

	if (bcast) *bcast = 0;

	switch (si->family) {
	case AF_INET: {
		const struct sockaddr_in *in =
		    (const struct sockaddr_in *)(const void *)inaddr;
		unsigned int addr = ntohl(in->sin_addr.s_addr);
		char u_type = '\0';
		char d_type = '\0';
		char b_type = '\0';
		char a_type = '\0';
		const unsigned int sw_net_addr = swrap_ipv4_net();
		const unsigned int sw_bcast_addr = swrap_ipv4_bcast();

		prt = ntohs(in->sin_port);

		switch (si->type) {
		case SOCK_STREAM:
			u_type = SOCKET_TYPE_CHAR_TCP;
			d_type = SOCKET_TYPE_CHAR_TCP;
			break;
		case SOCK_DGRAM:
			u_type = SOCKET_TYPE_CHAR_UDP;
			d_type = SOCKET_TYPE_CHAR_UDP;
			a_type = SOCKET_TYPE_CHAR_UDP;
			b_type = SOCKET_TYPE_CHAR_UDP;
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}

		if (addr == 0) {
			/* 0.0.0.0 */
			is_bcast = 0;
			type = d_type;
			iface = socket_wrapper_default_iface();
		} else if (a_type && addr == 0xFFFFFFFF) {
			/* 255.255.255.255 only udp */
			is_bcast = 2;
			type = a_type;
			iface = socket_wrapper_default_iface();
		} else if (b_type && addr == sw_bcast_addr) {
			/* 127.255.255.255 only udp */
			is_bcast = 1;
			type = b_type;
			iface = socket_wrapper_default_iface();
		} else if ((addr & 0xFFFFFF00) == sw_net_addr) {
			/* 127.0.0.X */
			is_bcast = 0;
			type = u_type;
			iface = (addr & 0x000000FF);
		} else {
			errno = EADDRNOTAVAIL;
			return -1;
		}

		/* Store the bind address for connect() */
		if (si->bindname.sa_socklen == 0) {
			struct sockaddr_in bind_in;
			socklen_t blen = sizeof(struct sockaddr_in);

			ZERO_STRUCT(bind_in);
			bind_in.sin_family = in->sin_family;
			bind_in.sin_port = in->sin_port;
			bind_in.sin_addr.s_addr = htonl(swrap_ipv4_iface(iface));
			si->bindname.sa_socklen = blen;
			memcpy(&si->bindname.sa.in, &bind_in, blen);
		}

		break;
	}
#ifdef HAVE_IPV6
	case AF_INET6: {
		const struct sockaddr_in6 *in =
		    (const struct sockaddr_in6 *)(const void *)inaddr;
		struct in6_addr cmp1, cmp2;

		switch (si->type) {
		case SOCK_STREAM:
			type = SOCKET_TYPE_CHAR_TCP_V6;
			break;
		case SOCK_DGRAM:
			type = SOCKET_TYPE_CHAR_UDP_V6;
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}

		/* XXX no multicast/broadcast */

		prt = ntohs(in->sin6_port);

		cmp1 = *swrap_ipv6();
		cmp2 = in->sin6_addr;
		cmp2.s6_addr[15] = 0;
		if (IN6_IS_ADDR_UNSPECIFIED(&in->sin6_addr)) {
			iface = socket_wrapper_default_iface();
		} else if (IN6_ARE_ADDR_EQUAL(&cmp1, &cmp2)) {
			iface = in->sin6_addr.s6_addr[15];
		} else {
			errno = EADDRNOTAVAIL;
			return -1;
		}

		/* Store the bind address for connect() */
		if (si->bindname.sa_socklen == 0) {
			struct sockaddr_in6 bind_in;
			socklen_t blen = sizeof(struct sockaddr_in6);

			ZERO_STRUCT(bind_in);
			bind_in.sin6_family = in->sin6_family;
			bind_in.sin6_port = in->sin6_port;

			bind_in.sin6_addr = *swrap_ipv6();
			bind_in.sin6_addr.s6_addr[15] = iface;

			memcpy(&si->bindname.sa.in6, &bind_in, blen);
			si->bindname.sa_socklen = blen;
		}

		break;
	}
#endif
	default:
		SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family");
		errno = EADDRNOTAVAIL;
		return -1;
	}


	if (bcast) *bcast = is_bcast;

	if (iface == 0 || iface > MAX_WRAPPED_INTERFACES) {
		errno = EINVAL;
		return -1;
	}

	swrap_dir = socket_wrapper_dir();
	if (swrap_dir == NULL) {
		errno = EINVAL;
		return -1;
	}

	if (prt == 0) {
		/* handle auto-allocation of ephemeral ports */
		for (prt = 5001; prt < 10000; prt++) {
			swrap_un_path(un, swrap_dir, type, iface, prt);
			if (stat(un->sun_path, &st) == 0) continue;

			set_port(si->family, prt, &si->myname);
			set_port(si->family, prt, &si->bindname);

			break;
		}

		if (prt == 10000) {
			errno = ENFILE;
			SAFE_FREE(swrap_dir);
			return -1;
		}
	}

	swrap_un_path(un, swrap_dir, type, iface, prt);
	SWRAP_LOG(SWRAP_LOG_DEBUG, "un path [%s]", un->sun_path);

	SAFE_FREE(swrap_dir);

	return 0;
}

static struct socket_info *find_socket_info(int fd)
{
	int idx = find_socket_info_index(fd);

	if (idx == -1) {
		return NULL;
	}

	return swrap_get_socket_info(idx);
}

#if 0 /* FIXME */
static bool check_addr_port_in_use(const struct sockaddr *sa, socklen_t len)
{
	struct socket_info_fd *f;
	const struct socket_info *last_s = NULL;

	/* first catch invalid input */
	switch (sa->sa_family) {
	case AF_INET:
		if (len < sizeof(struct sockaddr_in)) {
			return false;
		}
		break;
#ifdef HAVE_IPV6
	case AF_INET6:
		if (len < sizeof(struct sockaddr_in6)) {
			return false;
		}
		break;
#endif
	default:
		return false;
		break;
	}

	for (f = socket_fds; f; f = f->next) {
		struct socket_info *s = swrap_get_socket_info(f->si_index);

		if (s == last_s) {
			continue;
		}
		last_s = s;

		if (s->myname == NULL) {
			continue;
		}
		if (s->myname->sa_family != sa->sa_family) {
			continue;
		}
		switch (s->myname->sa_family) {
		case AF_INET: {
			struct sockaddr_in *sin1, *sin2;

			sin1 = (struct sockaddr_in *)s->myname;
			sin2 = (struct sockaddr_in *)sa;

			if (sin1->sin_addr.s_addr == htonl(INADDR_ANY)) {
				continue;
			}
			if (sin1->sin_port != sin2->sin_port) {
				continue;
			}
			if (sin1->sin_addr.s_addr != sin2->sin_addr.s_addr) {
				continue;
			}

			/* found */
			return true;
			break;
		}
#ifdef HAVE_IPV6
		case AF_INET6: {
			struct sockaddr_in6 *sin1, *sin2;

			sin1 = (struct sockaddr_in6 *)s->myname;
			sin2 = (struct sockaddr_in6 *)sa;

			if (sin1->sin6_port != sin2->sin6_port) {
				continue;
			}
			if (!IN6_ARE_ADDR_EQUAL(&sin1->sin6_addr,
						&sin2->sin6_addr))
			{
				continue;
			}

			/* found */
			return true;
			break;
		}
#endif
		default:
			continue;
			break;

		}
	}

	return false;
}
#endif

static void swrap_remove_stale(int fd)
{
	struct socket_info *si;
	int si_index;

	SWRAP_LOG(SWRAP_LOG_TRACE, "remove stale wrapper for %d", fd);

	swrap_mutex_lock(&socket_reset_mutex);

	si_index = find_socket_info_index(fd);
	if (si_index == -1) {
		swrap_mutex_unlock(&socket_reset_mutex);
		return;
	}

	reset_socket_info_index(fd);

	si = swrap_get_socket_info(si_index);

	swrap_mutex_lock(&first_free_mutex);
	SWRAP_LOCK_SI(si);

	swrap_dec_refcount(si);

	if (swrap_get_refcount(si) > 0) {
		goto out;
	}

	if (si->un_addr.sun_path[0] != '\0') {
		unlink(si->un_addr.sun_path);
	}

	swrap_set_next_free(si, first_free);
	first_free = si_index;

out:
	SWRAP_UNLOCK_SI(si);
	swrap_mutex_unlock(&first_free_mutex);
	swrap_mutex_unlock(&socket_reset_mutex);
}

static int sockaddr_convert_to_un(struct socket_info *si,
				  const struct sockaddr *in_addr,
				  socklen_t in_len,
				  struct sockaddr_un *out_addr,
				  int alloc_sock,
				  int *bcast)
{
	struct sockaddr *out = (struct sockaddr *)(void *)out_addr;

	(void) in_len; /* unused */

	if (out_addr == NULL) {
		return 0;
	}

	out->sa_family = AF_UNIX;
#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
	out->sa_len = sizeof(*out_addr);
#endif

	switch (in_addr->sa_family) {
	case AF_UNSPEC: {
		const struct sockaddr_in *sin;
		if (si->family != AF_INET) {
			break;
		}
		if (in_len < sizeof(struct sockaddr_in)) {
			break;
		}
		sin = (const struct sockaddr_in *)(const void *)in_addr;
		if(sin->sin_addr.s_addr != htonl(INADDR_ANY)) {
			break;
		}

		/*
		 * Note: in the special case of AF_UNSPEC and INADDR_ANY,
		 * AF_UNSPEC is mapped to AF_INET and must be treated here.
		 */

		FALL_THROUGH;
	}
	case AF_INET:
#ifdef HAVE_IPV6
	case AF_INET6:
#endif
		switch (si->type) {
		case SOCK_STREAM:
		case SOCK_DGRAM:
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}
		if (alloc_sock) {
			return convert_in_un_alloc(si, in_addr, out_addr, bcast);
		} else {
			return convert_in_un_remote(si, in_addr, out_addr, bcast);
		}
	default:
		break;
	}

	errno = EAFNOSUPPORT;
	SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family");
	return -1;
}

static int sockaddr_convert_from_un(const struct socket_info *si,
				    const struct sockaddr_un *in_addr,
				    socklen_t un_addrlen,
				    int family,
				    struct sockaddr *out_addr,
				    socklen_t *out_addrlen)
{
	int ret;

	if (out_addr == NULL || out_addrlen == NULL)
		return 0;

	if (un_addrlen == 0) {
		*out_addrlen = 0;
		return 0;
	}

	switch (family) {
	case AF_INET:
#ifdef HAVE_IPV6
	case AF_INET6:
#endif
		switch (si->type) {
		case SOCK_STREAM:
		case SOCK_DGRAM:
			break;
		default:
			SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown socket type!");
			errno = ESOCKTNOSUPPORT;
			return -1;
		}
		ret = convert_un_in(in_addr, out_addr, out_addrlen);
#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
		out_addr->sa_len = *out_addrlen;
#endif
		return ret;
	default:
		break;
	}

	SWRAP_LOG(SWRAP_LOG_ERROR, "Unknown address family");
	errno = EAFNOSUPPORT;
	return -1;
}

enum swrap_packet_type {
	SWRAP_CONNECT_SEND,
	SWRAP_CONNECT_UNREACH,
	SWRAP_CONNECT_RECV,
	SWRAP_CONNECT_ACK,
	SWRAP_ACCEPT_SEND,
	SWRAP_ACCEPT_RECV,
	SWRAP_ACCEPT_ACK,
	SWRAP_RECVFROM,
	SWRAP_SENDTO,
	SWRAP_SENDTO_UNREACH,
	SWRAP_PENDING_RST,
	SWRAP_RECV,
	SWRAP_RECV_RST,
	SWRAP_SEND,
	SWRAP_SEND_RST,
	SWRAP_CLOSE_SEND,
	SWRAP_CLOSE_RECV,
	SWRAP_CLOSE_ACK,
};

struct swrap_file_hdr {
	uint32_t	magic;
	uint16_t	version_major;
	uint16_t	version_minor;
	int32_t		timezone;
	uint32_t	sigfigs;
	uint32_t	frame_max_len;
#define SWRAP_FRAME_LENGTH_MAX 0xFFFF
	uint32_t	link_type;
};
#define SWRAP_FILE_HDR_SIZE 24

struct swrap_packet_frame {
	uint32_t seconds;
	uint32_t micro_seconds;
	uint32_t recorded_length;
	uint32_t full_length;
};
#define SWRAP_PACKET_FRAME_SIZE 16

union swrap_packet_ip {
	struct {
		uint8_t		ver_hdrlen;
		uint8_t		tos;
		uint16_t	packet_length;
		uint16_t	identification;
		uint8_t		flags;
		uint8_t		fragment;
		uint8_t		ttl;
		uint8_t		protocol;
		uint16_t	hdr_checksum;
		uint32_t	src_addr;
		uint32_t	dest_addr;
	} v4;
#define SWRAP_PACKET_IP_V4_SIZE 20
	struct {
		uint8_t		ver_prio;
		uint8_t		flow_label_high;
		uint16_t	flow_label_low;
		uint16_t	payload_length;
		uint8_t		next_header;
		uint8_t		hop_limit;
		uint8_t		src_addr[16];
		uint8_t		dest_addr[16];
	} v6;
#define SWRAP_PACKET_IP_V6_SIZE 40
};
#define SWRAP_PACKET_IP_SIZE 40

union swrap_packet_payload {
	struct {
		uint16_t	source_port;
		uint16_t	dest_port;
		uint32_t	seq_num;
		uint32_t	ack_num;
		uint8_t		hdr_length;
		uint8_t		control;
		uint16_t	window;
		uint16_t	checksum;
		uint16_t	urg;
	} tcp;
#define SWRAP_PACKET_PAYLOAD_TCP_SIZE 20
	struct {
		uint16_t	source_port;
		uint16_t	dest_port;
		uint16_t	length;
		uint16_t	checksum;
	} udp;
#define SWRAP_PACKET_PAYLOAD_UDP_SIZE 8
	struct {
		uint8_t		type;
		uint8_t		code;
		uint16_t	checksum;
		uint32_t	unused;
	} icmp4;
#define SWRAP_PACKET_PAYLOAD_ICMP4_SIZE 8
	struct {
		uint8_t		type;
		uint8_t		code;
		uint16_t	checksum;
		uint32_t	unused;
	} icmp6;
#define SWRAP_PACKET_PAYLOAD_ICMP6_SIZE 8
};
#define SWRAP_PACKET_PAYLOAD_SIZE 20

#define SWRAP_PACKET_MIN_ALLOC \
	(SWRAP_PACKET_FRAME_SIZE + \
	 SWRAP_PACKET_IP_SIZE + \
	 SWRAP_PACKET_PAYLOAD_SIZE)

static const char *swrap_pcap_init_file(void)
{
	static int initialized = 0;
	static const char *s = NULL;
	static const struct swrap_file_hdr h;
	static const struct swrap_packet_frame f;
	static const union swrap_packet_ip i;
	static const union swrap_packet_payload p;

	if (initialized == 1) {
		return s;
	}
	initialized = 1;

	/*
	 * TODO: don't use the structs use plain buffer offsets
	 *       and PUSH_U8(), PUSH_U16() and PUSH_U32()
	 *
	 * for now make sure we disable PCAP support
	 * if the struct has alignment!
	 */
	if (sizeof(h) != SWRAP_FILE_HDR_SIZE) {
		return NULL;
	}
	if (sizeof(f) != SWRAP_PACKET_FRAME_SIZE) {
		return NULL;
	}
	if (sizeof(i) != SWRAP_PACKET_IP_SIZE) {
		return NULL;
	}
	if (sizeof(i.v4) != SWRAP_PACKET_IP_V4_SIZE) {
		return NULL;
	}
	if (sizeof(i.v6) != SWRAP_PACKET_IP_V6_SIZE) {
		return NULL;
	}
	if (sizeof(p) != SWRAP_PACKET_PAYLOAD_SIZE) {
		return NULL;
	}
	if (sizeof(p.tcp) != SWRAP_PACKET_PAYLOAD_TCP_SIZE) {
		return NULL;
	}
	if (sizeof(p.udp) != SWRAP_PACKET_PAYLOAD_UDP_SIZE) {
		return NULL;
	}
	if (sizeof(p.icmp4) != SWRAP_PACKET_PAYLOAD_ICMP4_SIZE) {
		return NULL;
	}
	if (sizeof(p.icmp6) != SWRAP_PACKET_PAYLOAD_ICMP6_SIZE) {
		return NULL;
	}

	s = getenv("SOCKET_WRAPPER_PCAP_FILE");
	if (s == NULL) {
		return NULL;
	}
	if (strncmp(s, "./", 2) == 0) {
		s += 2;
	}
	SWRAP_LOG(SWRAP_LOG_TRACE, "SOCKET_WRAPPER_PCAP_FILE: %s", s);
	return s;
}

static uint8_t *swrap_pcap_packet_init(struct timeval *tval,
				       const struct sockaddr *src,
				       const struct sockaddr *dest,
				       int socket_type,
				       const uint8_t *payload,
				       size_t payload_len,
				       unsigned long tcp_seqno,
				       unsigned long tcp_ack,
				       unsigned char tcp_ctl,
				       int unreachable,
				       size_t *_packet_len)
{
	uint8_t *base = NULL;
	uint8_t *buf = NULL;
	union {
		uint8_t *ptr;
		struct swrap_packet_frame *frame;
	} f;
	union {
		uint8_t *ptr;
		union swrap_packet_ip *ip;
	} i;
	union swrap_packet_payload *pay;
	size_t packet_len;
	size_t alloc_len;
	size_t nonwire_len = sizeof(struct swrap_packet_frame);
	size_t wire_hdr_len = 0;
	size_t wire_len = 0;
	size_t ip_hdr_len = 0;
	size_t icmp_hdr_len = 0;
	size_t icmp_truncate_len = 0;
	uint8_t protocol = 0, icmp_protocol = 0;
	const struct sockaddr_in *src_in = NULL;
	const struct sockaddr_in *dest_in = NULL;
#ifdef HAVE_IPV6
	const struct sockaddr_in6 *src_in6 = NULL;
	const struct sockaddr_in6 *dest_in6 = NULL;
#endif
	uint16_t src_port;
	uint16_t dest_port;

	switch (src->sa_family) {
	case AF_INET:
		src_in = (const struct sockaddr_in *)(const void *)src;
		dest_in = (const struct sockaddr_in *)(const void *)dest;
		src_port = src_in->sin_port;
		dest_port = dest_in->sin_port;
		ip_hdr_len = sizeof(i.ip->v4);
		break;
#ifdef HAVE_IPV6
	case AF_INET6:
		src_in6 = (const struct sockaddr_in6 *)(const void *)src;
		dest_in6 = (const struct sockaddr_in6 *)(const void *)dest;
		src_port = src_in6->sin6_port;
		dest_port = dest_in6->sin6_port;
		ip_hdr_len = sizeof(i.ip->v6);
		break;
#endif
	default:
		return NULL;
	}

	switch (socket_type) {
	case SOCK_STREAM:
		protocol = 0x06; /* TCP */
		wire_hdr_len = ip_hdr_len + sizeof(pay->tcp);
		wire_len = wire_hdr_len + payload_len;
		break;

	case SOCK_DGRAM:
		protocol = 0x11; /* UDP */
		wire_hdr_len = ip_hdr_len + sizeof(pay->udp);
		wire_len = wire_hdr_len + payload_len;
		break;

	default:
		return NULL;
	}

	if (unreachable) {
		icmp_protocol = protocol;
		switch (src->sa_family) {
		case AF_INET:
			protocol = 0x01; /* ICMPv4 */
			icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp4);
			break;
#ifdef HAVE_IPV6
		case AF_INET6:
			protocol = 0x3A; /* ICMPv6 */
			icmp_hdr_len = ip_hdr_len + sizeof(pay->icmp6);
			break;
#endif
		}
		if (wire_len > 64 ) {
			icmp_truncate_len = wire_len - 64;
		}
		wire_len += icmp_hdr_len;
	}

	packet_len = nonwire_len + wire_len;
	alloc_len = packet_len;
	if (alloc_len < SWRAP_PACKET_MIN_ALLOC) {
		alloc_len = SWRAP_PACKET_MIN_ALLOC;
	}

	base = (uint8_t *)calloc(1, alloc_len);
	if (base == NULL) {
		return NULL;
	}

	buf = base;
	f.ptr = buf;

	f.frame->seconds		= tval->tv_sec;
	f.frame->micro_seconds	= tval->tv_usec;
	f.frame->recorded_length	= wire_len - icmp_truncate_len;
	f.frame->full_length	= wire_len - icmp_truncate_len;

	buf += SWRAP_PACKET_FRAME_SIZE;

	i.ptr = buf;
	switch (src->sa_family) {
	case AF_INET:
		if (src_in == NULL || dest_in == NULL) {
			SAFE_FREE(base);
			return NULL;
		}

		i.ip->v4.ver_hdrlen	= 0x45; /* version 4 and 5 * 32 bit words */
		i.ip->v4.tos		= 0x00;
		i.ip->v4.packet_length	= htons(wire_len - icmp_truncate_len);
		i.ip->v4.identification	= htons(0xFFFF);
		i.ip->v4.flags		= 0x40; /* BIT 1 set - means don't fragment */
		i.ip->v4.fragment	= htons(0x0000);
		i.ip->v4.ttl		= 0xFF;
		i.ip->v4.protocol	= protocol;
		i.ip->v4.hdr_checksum	= htons(0x0000);
		i.ip->v4.src_addr	= src_in->sin_addr.s_addr;
		i.ip->v4.dest_addr	= dest_in->sin_addr.s_addr;
		buf += SWRAP_PACKET_IP_V4_SIZE;
		break;
#ifdef HAVE_IPV6
	case AF_INET6:
		if (src_in6 == NULL || dest_in6 == NULL) {
			SAFE_FREE(base);
			return NULL;
		}

		i.ip->v6.ver_prio		= 0x60; /* version 4 and 5 * 32 bit words */
		i.ip->v6.flow_label_high	= 0x00;
		i.ip->v6.flow_label_low	= 0x0000;
		i.ip->v6.payload_length	= htons(wire_len - icmp_truncate_len); /* TODO */
		i.ip->v6.next_header	= protocol;
		memcpy(i.ip->v6.src_addr, src_in6->sin6_addr.s6_addr, 16);
		memcpy(i.ip->v6.dest_addr, dest_in6->sin6_addr.s6_addr, 16);
		buf += SWRAP_PACKET_IP_V6_SIZE;
		break;
#endif
	}

	if (unreachable) {
		pay = (union swrap_packet_payload *)(void *)buf;
		switch (src->sa_family) {
		case AF_INET:
			pay->icmp4.type		= 0x03; /* destination unreachable */
			pay->icmp4.code		= 0x01; /* host unreachable */
			pay->icmp4.checksum	= htons(0x0000);
			pay->icmp4.unused	= htonl(0x00000000);

			buf += SWRAP_PACKET_PAYLOAD_ICMP4_SIZE;

			/* set the ip header in the ICMP payload */
			i.ptr = buf;
			i.ip->v4.ver_hdrlen	= 0x45; /* version 4 and 5 * 32 bit words */
			i.ip->v4.tos		= 0x00;
			i.ip->v4.packet_length	= htons(wire_len - icmp_hdr_len);
			i.ip->v4.identification	= htons(0xFFFF);
			i.ip->v4.flags		= 0x40; /* BIT 1 set - means don't fragment */
			i.ip->v4.fragment	= htons(0x0000);
			i.ip->v4.ttl		= 0xFF;
			i.ip->v4.protocol	= icmp_protocol;
			i.ip->v4.hdr_checksum	= htons(0x0000);
			i.ip->v4.src_addr	= dest_in->sin_addr.s_addr;
			i.ip->v4.dest_addr	= src_in->sin_addr.s_addr;

			buf += SWRAP_PACKET_IP_V4_SIZE;

			src_port = dest_in->sin_port;
			dest_port = src_in->sin_port;
			break;
#ifdef HAVE_IPV6
		case AF_INET6:
			pay->icmp6.type		= 0x01; /* destination unreachable */
			pay->icmp6.code		= 0x03; /* address unreachable */
			pay->icmp6.checksum	= htons(0x0000);
			pay->icmp6.unused	= htonl(0x00000000);
			buf += SWRAP_PACKET_PAYLOAD_ICMP6_SIZE;

			/* set the ip header in the ICMP payload */
			i.ptr = buf;
			i.ip->v6.ver_prio		= 0x60; /* version 4 and 5 * 32 bit words */
			i.ip->v6.flow_label_high	= 0x00;
			i.ip->v6.flow_label_low	= 0x0000;
			i.ip->v6.payload_length	= htons(wire_len - icmp_truncate_len); /* TODO */
			i.ip->v6.next_header	= protocol;
			memcpy(i.ip->v6.src_addr, dest_in6->sin6_addr.s6_addr, 16);
			memcpy(i.ip->v6.dest_addr, src_in6->sin6_addr.s6_addr, 16);

			buf += SWRAP_PACKET_IP_V6_SIZE;

			src_port = dest_in6->sin6_port;
			dest_port = src_in6->sin6_port;
			break;
#endif
		}
	}

	pay = (union swrap_packet_payload *)(void *)buf;

	switch (socket_type) {
	case SOCK_STREAM:
		pay->tcp.source_port	= src_port;
		pay->tcp.dest_port	= dest_port;
		pay->tcp.seq_num	= htonl(tcp_seqno);
		pay->tcp.ack_num	= htonl(tcp_ack);
		pay->tcp.hdr_length	= 0x50; /* 5 * 32 bit words */
		pay->tcp.control	= tcp_ctl;
		pay->tcp.window		= htons(0x7FFF);
		pay->tcp.checksum	= htons(0x0000);
		pay->tcp.urg		= htons(0x0000);
		buf += SWRAP_PACKET_PAYLOAD_TCP_SIZE;

		break;

	case SOCK_DGRAM:
		pay->udp.source_port	= src_port;
		pay->udp.dest_port	= dest_port;
		pay->udp.length		= htons(8 + payload_len);
		pay->udp.checksum	= htons(0x0000);
		buf += SWRAP_PACKET_PAYLOAD_UDP_SIZE;

		break;
	}

	if (payload && payload_len > 0) {
		memcpy(buf, payload, payload_len);
	}

	*_packet_len = packet_len - icmp_truncate_len;
	return base;
}

static int swrap_pcap_get_fd(const char *fname)
{
	static int fd = -1;

	if (fd != -1) {
		return fd;
	}

	fd = libc_open(fname, O_WRONLY|O_CREAT|O_EXCL|O_APPEND, 0644);
	if (fd != -1) {
		struct swrap_file_hdr file_hdr;
		file_hdr.magic		= 0xA1B2C3D4;
		file_hdr.version_major	= 0x0002;
		file_hdr.version_minor	= 0x0004;
		file_hdr.timezone	= 0x00000000;
		file_hdr.sigfigs	= 0x00000000;
		file_hdr.frame_max_len	= SWRAP_FRAME_LENGTH_MAX;
		file_hdr.link_type	= 0x0065; /* 101 RAW IP */

		if (write(fd, &file_hdr, sizeof(file_hdr)) != sizeof(file_hdr)) {
			close(fd);
			fd = -1;
		}
		return fd;
	}

	fd = libc_open(fname, O_WRONLY|O_APPEND, 0644);

	return fd;
}

static uint8_t *swrap_pcap_marshall_packet(struct socket_info *si,
					   const struct sockaddr *addr,
					   enum swrap_packet_type type,
					   const void *buf, size_t len,
					   size_t *packet_len)
{
	const struct sockaddr *src_addr;
	const struct sockaddr *dest_addr;
	unsigned long tcp_seqno = 0;
	unsigned long tcp_ack = 0;
	unsigned char tcp_ctl = 0;
	int unreachable = 0;

	struct timeval tv;

	switch (si->family) {
	case AF_INET:
		break;
#ifdef HAVE_IPV6
	case AF_INET6:
		break;
#endif
	default:
		return NULL;
	}

	switch (type) {
	case SWRAP_CONNECT_SEND:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		src_addr  = &si->myname.sa.s;
		dest_addr = addr;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x02; /* SYN */

		si->io.pck_snd += 1;

		break;

	case SWRAP_CONNECT_RECV:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		dest_addr = &si->myname.sa.s;
		src_addr = addr;

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x12; /** SYN,ACK */

		si->io.pck_rcv += 1;

		break;

	case SWRAP_CONNECT_UNREACH:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		dest_addr = &si->myname.sa.s;
		src_addr  = addr;

		/* Unreachable: resend the data of SWRAP_CONNECT_SEND */
		tcp_seqno = si->io.pck_snd - 1;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x02; /* SYN */
		unreachable = 1;

		break;

	case SWRAP_CONNECT_ACK:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		src_addr  = &si->myname.sa.s;
		dest_addr = addr;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x10; /* ACK */

		break;

	case SWRAP_ACCEPT_SEND:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		dest_addr = &si->myname.sa.s;
		src_addr = addr;

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x02; /* SYN */

		si->io.pck_rcv += 1;

		break;

	case SWRAP_ACCEPT_RECV:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		src_addr = &si->myname.sa.s;
		dest_addr = addr;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x12; /* SYN,ACK */

		si->io.pck_snd += 1;

		break;

	case SWRAP_ACCEPT_ACK:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		dest_addr = &si->myname.sa.s;
		src_addr = addr;

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x10; /* ACK */

		break;

	case SWRAP_SEND:
		src_addr  = &si->myname.sa.s;
		dest_addr = &si->peername.sa.s;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x18; /* PSH,ACK */

		si->io.pck_snd += len;

		break;

	case SWRAP_SEND_RST:
		dest_addr = &si->myname.sa.s;
		src_addr  = &si->peername.sa.s;

		if (si->type == SOCK_DGRAM) {
			return swrap_pcap_marshall_packet(si,
							  &si->peername.sa.s,
							  SWRAP_SENDTO_UNREACH,
							  buf,
							  len,
							  packet_len);
		}

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x14; /** RST,ACK */

		break;

	case SWRAP_PENDING_RST:
		dest_addr = &si->myname.sa.s;
		src_addr  = &si->peername.sa.s;

		if (si->type == SOCK_DGRAM) {
			return NULL;
		}

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x14; /* RST,ACK */

		break;

	case SWRAP_RECV:
		dest_addr = &si->myname.sa.s;
		src_addr  = &si->peername.sa.s;

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x18; /* PSH,ACK */

		si->io.pck_rcv += len;

		break;

	case SWRAP_RECV_RST:
		dest_addr = &si->myname.sa.s;
		src_addr  = &si->peername.sa.s;

		if (si->type == SOCK_DGRAM) {
			return NULL;
		}

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x14; /* RST,ACK */

		break;

	case SWRAP_SENDTO:
		src_addr = &si->myname.sa.s;
		dest_addr = addr;

		si->io.pck_snd += len;

		break;

	case SWRAP_SENDTO_UNREACH:
		dest_addr = &si->myname.sa.s;
		src_addr = addr;

		unreachable = 1;

		break;

	case SWRAP_RECVFROM:
		dest_addr = &si->myname.sa.s;
		src_addr = addr;

		si->io.pck_rcv += len;

		break;

	case SWRAP_CLOSE_SEND:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		src_addr  = &si->myname.sa.s;
		dest_addr = &si->peername.sa.s;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x11; /* FIN, ACK */

		si->io.pck_snd += 1;

		break;

	case SWRAP_CLOSE_RECV:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		dest_addr = &si->myname.sa.s;
		src_addr  = &si->peername.sa.s;

		tcp_seqno = si->io.pck_rcv;
		tcp_ack = si->io.pck_snd;
		tcp_ctl = 0x11; /* FIN,ACK */

		si->io.pck_rcv += 1;

		break;

	case SWRAP_CLOSE_ACK:
		if (si->type != SOCK_STREAM) {
			return NULL;
		}

		src_addr  = &si->myname.sa.s;
		dest_addr = &si->peername.sa.s;

		tcp_seqno = si->io.pck_snd;
		tcp_ack = si->io.pck_rcv;
		tcp_ctl = 0x10; /* ACK */

		break;
	default:
		return NULL;
	}

	swrapGetTimeOfDay(&tv);

	return swrap_pcap_packet_init(&tv,
				      src_addr,
				      dest_addr,
				      si->type,
				      (const uint8_t *)buf,
				      len,
				      tcp_seqno,
				      tcp_ack,
				      tcp_ctl,
				      unreachable,
				      packet_len);
}

static void swrap_pcap_dump_packet(struct socket_info *si,
				   const struct sockaddr *addr,
				   enum swrap_packet_type type,
				   const void *buf, size_t len)
{
	const char *file_name;
	uint8_t *packet;
	size_t packet_len = 0;
	int fd;

	swrap_mutex_lock(&pcap_dump_mutex);

	file_name = swrap_pcap_init_file();
	if (!file_name) {
		goto done;
	}

	packet = swrap_pcap_marshall_packet(si,
					    addr,
					    type,
					    buf,
					    len,
					    &packet_len);
	if (packet == NULL) {
		goto done;
	}

	fd = swrap_pcap_get_fd(file_name);
	if (fd != -1) {
		if (write(fd, packet, packet_len) != (ssize_t)packet_len) {
			free(packet);
			goto done;
		}
	}

	free(packet);

done:
	swrap_mutex_unlock(&pcap_dump_mutex);
}

/****************************************************************************
 *   SIGNALFD
 ***************************************************************************/

#ifdef HAVE_SIGNALFD
static int swrap_signalfd(int fd, const sigset_t *mask, int flags)
{
	int rc;

	rc = libc_signalfd(fd, mask, flags);
	if (rc != -1) {
		swrap_remove_stale(fd);
	}

	return rc;
}

int signalfd(int fd, const sigset_t *mask, int flags)
{
	return swrap_signalfd(fd, mask, flags);
}
#endif

/****************************************************************************
 *   SOCKET
 ***************************************************************************/

static int swrap_socket(int family, int type, int protocol)
{
	struct socket_info *si = NULL;
	struct socket_info _si = { 0 };
	int fd;
	int ret;
	int real_type = type;

	/*
	 * Remove possible addition flags passed to socket() so
	 * do not fail checking the type.
	 * See https://lwn.net/Articles/281965/
	 */
#ifdef SOCK_CLOEXEC
	real_type &= ~SOCK_CLOEXEC;
#endif
#ifdef SOCK_NONBLOCK
	real_type &= ~SOCK_NONBLOCK;
#endif

	if (!socket_wrapper_enabled()) {
		return libc_socket(family, type, protocol);
	}

	switch (family) {
	case AF_INET:
#ifdef HAVE_IPV6
	case AF_INET6:
#endif
		break;
#ifdef AF_NETLINK
	case AF_NETLINK:
#endif /* AF_NETLINK */
#ifdef AF_PACKET
	case AF_PACKET:
#endif /* AF_PACKET */
	case AF_UNIX:
		fd = libc_socket(family, type, protocol);
		if (fd != -1) {
			/* Check if we have a stale fd and remove it */
			swrap_remove_stale(fd);
			SWRAP_LOG(SWRAP_LOG_TRACE,
				  "Unix socket fd=%d",
				  fd);
		}
		return fd;
	default:
		errno = EAFNOSUPPORT;
		return -1;
	}

	switch (real_type) {
	case SOCK_STREAM:
		break;
	case SOCK_DGRAM:
		break;
	default:
		errno = EPROTONOSUPPORT;
		return -1;
	}

	switch (protocol) {
	case 0:
		break;
	case 6:
		if (real_type == SOCK_STREAM) {
			break;
		}
		FALL_THROUGH;
	case 17:
		if (real_type == SOCK_DGRAM) {
			break;
		}
		FALL_THROUGH;
	default:
		errno = EPROTONOSUPPORT;
		return -1;
	}

	/*
	 * We must call libc_socket with type, from the caller, not the version
	 * we removed SOCK_CLOEXEC and SOCK_NONBLOCK from
	 */
	fd = libc_socket(AF_UNIX, type, 0);

	if (fd == -1) {
		return -1;
	}

	/* Check if we have a stale fd and remove it */
	swrap_remove_stale(fd);

	si = &_si;
	si->family = family;

	/* however, the rest of the socket_wrapper code expects just
	 * the type, not the flags */
	si->type = real_type;
	si->protocol = protocol;

	/*
	 * Setup myname so getsockname() can succeed to find out the socket
	 * type.
	 */
	switch(si->family) {
	case AF_INET: {
		struct sockaddr_in sin = {
			.sin_family = AF_INET,
		};

		si->myname.sa_socklen = sizeof(struct sockaddr_in);
		memcpy(&si->myname.sa.in, &sin, si->myname.sa_socklen);
		break;
	}
#ifdef HAVE_IPV6
	case AF_INET6: {
		struct sockaddr_in6 sin6 = {
			.sin6_family = AF_INET6,
		};

		si->myname.sa_socklen = sizeof(struct sockaddr_in6);
		memcpy(&si->myname.sa.in6, &sin6, si->myname.sa_socklen);
		break;
	}
#endif
	default:
		errno = EINVAL;
		return -1;
	}

	ret = swrap_create_socket(si, fd);
	if (ret == -1) {
		return -1;
	}

	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "Created %s socket for protocol %s, fd=%d",
		  family == AF_INET ? "IPv4" : "IPv6",
		  real_type == SOCK_DGRAM ? "UDP" : "TCP",
		  fd);

	return fd;
}

int socket(int family, int type, int protocol)
{
	return swrap_socket(family, type, protocol);
}

/****************************************************************************
 *   SOCKETPAIR
 ***************************************************************************/

static int swrap_socketpair(int family, int type, int protocol, int sv[2])
{
	int rc;

	rc = libc_socketpair(family, type, protocol, sv);
	if (rc != -1) {
		swrap_remove_stale(sv[0]);
		swrap_remove_stale(sv[1]);
	}

	return rc;
}

int socketpair(int family, int type, int protocol, int sv[2])
{
	return swrap_socketpair(family, type, protocol, sv);
}

/****************************************************************************
 *   SOCKETPAIR
 ***************************************************************************/

#ifdef HAVE_TIMERFD_CREATE
static int swrap_timerfd_create(int clockid, int flags)
{
	int fd;

	fd = libc_timerfd_create(clockid, flags);
	if (fd != -1) {
		swrap_remove_stale(fd);
	}

	return fd;
}

int timerfd_create(int clockid, int flags)
{
	return swrap_timerfd_create(clockid, flags);
}
#endif

/****************************************************************************
 *   PIPE
 ***************************************************************************/

static int swrap_pipe(int pipefd[2])
{
	int rc;

	rc = libc_pipe(pipefd);
	if (rc != -1) {
		swrap_remove_stale(pipefd[0]);
		swrap_remove_stale(pipefd[1]);
	}

	return rc;
}

int pipe(int pipefd[2])
{
	return swrap_pipe(pipefd);
}

/****************************************************************************
 *   ACCEPT
 ***************************************************************************/

static int swrap_accept(int s,
			struct sockaddr *addr,
			socklen_t *addrlen,
			int flags)
{
	struct socket_info *parent_si, *child_si;
	struct socket_info new_si = { 0 };
	int fd;
	int idx;
	struct swrap_address un_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	struct swrap_address un_my_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	struct swrap_address in_addr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	struct swrap_address in_my_addr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	int ret;

	parent_si = find_socket_info(s);
	if (!parent_si) {
#ifdef HAVE_ACCEPT4
		return libc_accept4(s, addr, addrlen, flags);
#else
		UNUSED(flags);
		return libc_accept(s, addr, addrlen);
#endif
	}


	/*
	 * prevent parent_si from being altered / closed
	 * while we read it
	 */
	SWRAP_LOCK_SI(parent_si);

	/*
	 * assume out sockaddr have the same size as the in parent
	 * socket family
	 */
	in_addr.sa_socklen = socket_length(parent_si->family);
	if (in_addr.sa_socklen <= 0) {
		SWRAP_UNLOCK_SI(parent_si);
		errno = EINVAL;
		return -1;
	}

	SWRAP_UNLOCK_SI(parent_si);

#ifdef HAVE_ACCEPT4
	ret = libc_accept4(s, &un_addr.sa.s, &un_addr.sa_socklen, flags);
#else
	UNUSED(flags);
	ret = libc_accept(s, &un_addr.sa.s, &un_addr.sa_socklen);
#endif
	if (ret == -1) {
		if (errno == ENOTSOCK) {
			/* Remove stale fds */
			swrap_remove_stale(s);
		}
		return ret;
	}

	fd = ret;

	/* Check if we have a stale fd and remove it */
	swrap_remove_stale(fd);

	SWRAP_LOCK_SI(parent_si);

	ret = sockaddr_convert_from_un(parent_si,
				       &un_addr.sa.un,
				       un_addr.sa_socklen,
				       parent_si->family,
				       &in_addr.sa.s,
				       &in_addr.sa_socklen);
	if (ret == -1) {
		SWRAP_UNLOCK_SI(parent_si);
		close(fd);
		return ret;
	}

	child_si = &new_si;

	child_si->family = parent_si->family;
	child_si->type = parent_si->type;
	child_si->protocol = parent_si->protocol;
	child_si->bound = 1;
	child_si->is_server = 1;
	child_si->connected = 1;

	SWRAP_UNLOCK_SI(parent_si);

	child_si->peername = (struct swrap_address) {
		.sa_socklen = in_addr.sa_socklen,
	};
	memcpy(&child_si->peername.sa.ss, &in_addr.sa.ss, in_addr.sa_socklen);

	if (addr != NULL && addrlen != NULL) {
		size_t copy_len = MIN(*addrlen, in_addr.sa_socklen);
		if (copy_len > 0) {
			memcpy(addr, &in_addr.sa.ss, copy_len);
		}
		*addrlen = in_addr.sa_socklen;
	}

	ret = libc_getsockname(fd,
			       &un_my_addr.sa.s,
			       &un_my_addr.sa_socklen);
	if (ret == -1) {
		close(fd);
		return ret;
	}

	ret = sockaddr_convert_from_un(child_si,
				       &un_my_addr.sa.un,
				       un_my_addr.sa_socklen,
				       child_si->family,
				       &in_my_addr.sa.s,
				       &in_my_addr.sa_socklen);
	if (ret == -1) {
		close(fd);
		return ret;
	}

	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "accept() path=%s, fd=%d",
		  un_my_addr.sa.un.sun_path, s);

	child_si->myname = (struct swrap_address) {
		.sa_socklen = in_my_addr.sa_socklen,
	};
	memcpy(&child_si->myname.sa.ss, &in_my_addr.sa.ss, in_my_addr.sa_socklen);

	idx = swrap_create_socket(&new_si, fd);
	if (idx == -1) {
		close (fd);
		return -1;
	}

	if (addr != NULL) {
		struct socket_info *si = swrap_get_socket_info(idx);

		SWRAP_LOCK_SI(si);
		swrap_pcap_dump_packet(si, addr, SWRAP_ACCEPT_SEND, NULL, 0);
		swrap_pcap_dump_packet(si, addr, SWRAP_ACCEPT_RECV, NULL, 0);
		swrap_pcap_dump_packet(si, addr, SWRAP_ACCEPT_ACK, NULL, 0);
		SWRAP_UNLOCK_SI(si);
	}

	return fd;
}

#ifdef HAVE_ACCEPT4
int accept4(int s, struct sockaddr *addr, socklen_t *addrlen, int flags)
{
	return swrap_accept(s, addr, (socklen_t *)addrlen, flags);
}
#endif

#ifdef HAVE_ACCEPT_PSOCKLEN_T
int accept(int s, struct sockaddr *addr, Psocklen_t addrlen)
#else
int accept(int s, struct sockaddr *addr, socklen_t *addrlen)
#endif
{
	return swrap_accept(s, addr, (socklen_t *)addrlen, 0);
}

static int autobind_start_init;
static int autobind_start;

/* using sendto() or connect() on an unbound socket would give the
   recipient no way to reply, as unlike UDP and TCP, a unix domain
   socket can't auto-assign ephemeral port numbers, so we need to
   assign it here.
   Note: this might change the family from ipv6 to ipv4
*/
static int swrap_auto_bind(int fd, struct socket_info *si, int family)
{
	struct swrap_address un_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	int i;
	char type;
	int ret;
	int port;
	struct stat st;
	char *swrap_dir = NULL;

	swrap_mutex_lock(&autobind_start_mutex);

	if (autobind_start_init != 1) {
		autobind_start_init = 1;
		autobind_start = getpid();
		autobind_start %= 50000;
		autobind_start += 10000;
	}

	un_addr.sa.un.sun_family = AF_UNIX;

	switch (family) {
	case AF_INET: {
		struct sockaddr_in in;

		switch (si->type) {
		case SOCK_STREAM:
			type = SOCKET_TYPE_CHAR_TCP;
			break;
		case SOCK_DGRAM:
			type = SOCKET_TYPE_CHAR_UDP;
			break;
		default:
			errno = ESOCKTNOSUPPORT;
			ret = -1;
			goto done;
		}

		memset(&in, 0, sizeof(in));
		in.sin_family = AF_INET;
		in.sin_addr.s_addr = htonl(swrap_ipv4_iface(
					   socket_wrapper_default_iface()));

		si->myname = (struct swrap_address) {
			.sa_socklen = sizeof(in),
		};
		memcpy(&si->myname.sa.in, &in, si->myname.sa_socklen);
		break;
	}
#ifdef HAVE_IPV6
	case AF_INET6: {
		struct sockaddr_in6 in6;

		if (si->family != family) {
			errno = ENETUNREACH;
			ret = -1;
			goto done;
		}

		switch (si->type) {
		case SOCK_STREAM:
			type = SOCKET_TYPE_CHAR_TCP_V6;
			break;
		case SOCK_DGRAM:
			type = SOCKET_TYPE_CHAR_UDP_V6;
			break;
		default:
			errno = ESOCKTNOSUPPORT;
			ret = -1;
			goto done;
		}

		memset(&in6, 0, sizeof(in6));
		in6.sin6_family = AF_INET6;
		in6.sin6_addr = *swrap_ipv6();
		in6.sin6_addr.s6_addr[15] = socket_wrapper_default_iface();

		si->myname = (struct swrap_address) {
			.sa_socklen = sizeof(in6),
		};
		memcpy(&si->myname.sa.in6, &in6, si->myname.sa_socklen);
		break;
	}
#endif
	default:
		errno = ESOCKTNOSUPPORT;
		ret = -1;
		goto done;
	}

	if (autobind_start > 60000) {
		autobind_start = 10000;
	}

	swrap_dir = socket_wrapper_dir();
	if (swrap_dir == NULL) {
		errno = EINVAL;
		ret = -1;
		goto done;
	}

	for (i = 0; i < SOCKET_MAX_SOCKETS; i++) {
		port = autobind_start + i;
		swrap_un_path(&un_addr.sa.un,
			      swrap_dir,
			      type,
			      socket_wrapper_default_iface(),
			      port);
		if (stat(un_addr.sa.un.sun_path, &st) == 0) continue;

		ret = libc_bind(fd, &un_addr.sa.s, un_addr.sa_socklen);
		if (ret == -1) {
			goto done;
		}

		si->un_addr = un_addr.sa.un;

		si->bound = 1;
		autobind_start = port + 1;
		break;
	}
	if (i == SOCKET_MAX_SOCKETS) {
		SWRAP_LOG(SWRAP_LOG_ERROR, "Too many open unix sockets (%u) for "
					   "interface "SOCKET_FORMAT,
					   SOCKET_MAX_SOCKETS,
					   type,
					   socket_wrapper_default_iface(),
					   0);
		errno = ENFILE;
		ret = -1;
		goto done;
	}

	si->family = family;
	set_port(si->family, port, &si->myname);

	ret = 0;

done:
	SAFE_FREE(swrap_dir);
	swrap_mutex_unlock(&autobind_start_mutex);
	return ret;
}

/****************************************************************************
 *   CONNECT
 ***************************************************************************/

static int swrap_connect(int s, const struct sockaddr *serv_addr,
			 socklen_t addrlen)
{
	int ret;
	struct swrap_address un_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	struct socket_info *si = find_socket_info(s);
	int bcast = 0;

	if (!si) {
		return libc_connect(s, serv_addr, addrlen);
	}

	SWRAP_LOCK_SI(si);

	if (si->bound == 0) {
		ret = swrap_auto_bind(s, si, serv_addr->sa_family);
		if (ret == -1) {
			goto done;
		}
	}

	if (si->family != serv_addr->sa_family) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "called for fd=%d (family=%d) called with invalid family=%d",
			  s, si->family, serv_addr->sa_family);
		errno = EINVAL;
		ret = -1;
		goto done;
	}

	ret = sockaddr_convert_to_un(si, serv_addr,
				     addrlen, &un_addr.sa.un, 0, &bcast);
	if (ret == -1) {
		goto done;
	}

	if (bcast) {
		errno = ENETUNREACH;
		ret = -1;
		goto done;
	}

	if (si->type == SOCK_DGRAM) {
		si->defer_connect = 1;
		ret = 0;
	} else {
		swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_SEND, NULL, 0);

		ret = libc_connect(s,
				   &un_addr.sa.s,
				   un_addr.sa_socklen);
	}

	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "connect() path=%s, fd=%d",
		  un_addr.sa.un.sun_path, s);


	/* to give better errors */
	if (ret == -1 && errno == ENOENT) {
		errno = EHOSTUNREACH;
	}

	if (ret == 0) {
		si->peername = (struct swrap_address) {
			.sa_socklen = addrlen,
		};

		memcpy(&si->peername.sa.ss, serv_addr, addrlen);
		si->connected = 1;

		/*
		 * When we connect() on a socket than we have to bind the
		 * outgoing connection on the interface we use for the
		 * transport. We already bound it on the right interface
		 * but here we have to update the name so getsockname()
		 * returns correct information.
		 */
		if (si->bindname.sa_socklen > 0) {
			si->myname = (struct swrap_address) {
				.sa_socklen = si->bindname.sa_socklen,
			};

			memcpy(&si->myname.sa.ss,
			       &si->bindname.sa.ss,
			       si->bindname.sa_socklen);

			/* Cleanup bindname */
			si->bindname = (struct swrap_address) {
				.sa_socklen = 0,
			};
		}

		swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_RECV, NULL, 0);
		swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_ACK, NULL, 0);
	} else {
		swrap_pcap_dump_packet(si, serv_addr, SWRAP_CONNECT_UNREACH, NULL, 0);
	}

done:
	SWRAP_UNLOCK_SI(si);
	return ret;
}

int connect(int s, const struct sockaddr *serv_addr, socklen_t addrlen)
{
	return swrap_connect(s, serv_addr, addrlen);
}

/****************************************************************************
 *   BIND
 ***************************************************************************/

static int swrap_bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
{
	int ret;
	struct swrap_address un_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	struct socket_info *si = find_socket_info(s);
	int bind_error = 0;
#if 0 /* FIXME */
	bool in_use;
#endif

	if (!si) {
		return libc_bind(s, myaddr, addrlen);
	}

	SWRAP_LOCK_SI(si);

	switch (si->family) {
	case AF_INET: {
		const struct sockaddr_in *sin;
		if (addrlen < sizeof(struct sockaddr_in)) {
			bind_error = EINVAL;
			break;
		}

		sin = (const struct sockaddr_in *)(const void *)myaddr;

		if (sin->sin_family != AF_INET) {
			bind_error = EAFNOSUPPORT;
		}

		/* special case for AF_UNSPEC */
		if (sin->sin_family == AF_UNSPEC &&
		    (sin->sin_addr.s_addr == htonl(INADDR_ANY)))
		{
			bind_error = 0;
		}

		break;
	}
#ifdef HAVE_IPV6
	case AF_INET6: {
		const struct sockaddr_in6 *sin6;
		if (addrlen < sizeof(struct sockaddr_in6)) {
			bind_error = EINVAL;
			break;
		}

		sin6 = (const struct sockaddr_in6 *)(const void *)myaddr;

		if (sin6->sin6_family != AF_INET6) {
			bind_error = EAFNOSUPPORT;
		}

		break;
	}
#endif
	default:
		bind_error = EINVAL;
		break;
	}

	if (bind_error != 0) {
		errno = bind_error;
		ret = -1;
		goto out;
	}

#if 0 /* FIXME */
	in_use = check_addr_port_in_use(myaddr, addrlen);
	if (in_use) {
		errno = EADDRINUSE;
		ret = -1;
		goto out;
	}
#endif

	si->myname.sa_socklen = addrlen;
	memcpy(&si->myname.sa.ss, myaddr, addrlen);

	ret = sockaddr_convert_to_un(si,
				     myaddr,
				     addrlen,
				     &un_addr.sa.un,
				     1,
				     &si->bcast);
	if (ret == -1) {
		goto out;
	}

	unlink(un_addr.sa.un.sun_path);

	ret = libc_bind(s, &un_addr.sa.s, un_addr.sa_socklen);

	SWRAP_LOG(SWRAP_LOG_TRACE,
		  "bind() path=%s, fd=%d",
		  un_addr.sa.un.sun_path, s);

	if (ret == 0) {
		si->bound = 1;
	}

out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

int bind(int s, const struct sockaddr *myaddr, socklen_t addrlen)
{
	return swrap_bind(s, myaddr, addrlen);
}

/****************************************************************************
 *   BINDRESVPORT
 ***************************************************************************/

#ifdef HAVE_BINDRESVPORT
static int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen);

static int swrap_bindresvport_sa(int sd, struct sockaddr *sa)
{
	struct swrap_address myaddr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	socklen_t salen;
	static uint16_t port;
	uint16_t i;
	int rc = -1;
	int af;

#define SWRAP_STARTPORT 600
#define SWRAP_ENDPORT (IPPORT_RESERVED - 1)
#define SWRAP_NPORTS (SWRAP_ENDPORT - SWRAP_STARTPORT + 1)

	if (port == 0) {
		port = (getpid() % SWRAP_NPORTS) + SWRAP_STARTPORT;
	}

	if (sa == NULL) {
		salen = myaddr.sa_socklen;
		sa = &myaddr.sa.s;

		rc = swrap_getsockname(sd, &myaddr.sa.s, &salen);
		if (rc < 0) {
			return -1;
		}

		af = sa->sa_family;
		memset(&myaddr.sa.ss, 0, salen);
	} else {
		af = sa->sa_family;
	}

	for (i = 0; i < SWRAP_NPORTS; i++, port++) {
		switch(af) {
		case AF_INET: {
			struct sockaddr_in *sinp = (struct sockaddr_in *)(void *)sa;

			salen = sizeof(struct sockaddr_in);
			sinp->sin_port = htons(port);
			break;
		}
		case AF_INET6: {
			struct sockaddr_in6 *sin6p = (struct sockaddr_in6 *)(void *)sa;

			salen = sizeof(struct sockaddr_in6);
			sin6p->sin6_port = htons(port);
			break;
		}
		default:
			errno = EAFNOSUPPORT;
			return -1;
		}
		sa->sa_family = af;

		if (port > SWRAP_ENDPORT) {
			port = SWRAP_STARTPORT;
		}

		rc = swrap_bind(sd, (struct sockaddr *)sa, salen);
		if (rc == 0 || errno != EADDRINUSE) {
			break;
		}
	}

	return rc;
}

int bindresvport(int sockfd, struct sockaddr_in *sinp)
{
	return swrap_bindresvport_sa(sockfd, (struct sockaddr *)sinp);
}
#endif

/****************************************************************************
 *   LISTEN
 ***************************************************************************/

static int swrap_listen(int s, int backlog)
{
	int ret;
	struct socket_info *si = find_socket_info(s);

	if (!si) {
		return libc_listen(s, backlog);
	}

	SWRAP_LOCK_SI(si);

	if (si->bound == 0) {
		ret = swrap_auto_bind(s, si, si->family);
		if (ret == -1) {
			errno = EADDRINUSE;
			goto out;
		}
	}

	ret = libc_listen(s, backlog);
	if (ret == 0) {
		si->listening = 1;
	}

out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

int listen(int s, int backlog)
{
	return swrap_listen(s, backlog);
}

/****************************************************************************
 *   FOPEN
 ***************************************************************************/

static FILE *swrap_fopen(const char *name, const char *mode)
{
	FILE *fp;

	fp = libc_fopen(name, mode);
	if (fp != NULL) {
		int fd = fileno(fp);

		swrap_remove_stale(fd);
	}

	return fp;
}

FILE *fopen(const char *name, const char *mode)
{
	return swrap_fopen(name, mode);
}

/****************************************************************************
 *   FOPEN64
 ***************************************************************************/

#ifdef HAVE_FOPEN64
static FILE *swrap_fopen64(const char *name, const char *mode)
{
	FILE *fp;

	fp = libc_fopen64(name, mode);
	if (fp != NULL) {
		int fd = fileno(fp);

		swrap_remove_stale(fd);
	}

	return fp;
}

FILE *fopen64(const char *name, const char *mode)
{
	return swrap_fopen64(name, mode);
}
#endif /* HAVE_FOPEN64 */

/****************************************************************************
 *   OPEN
 ***************************************************************************/

static int swrap_vopen(const char *pathname, int flags, va_list ap)
{
	int ret;

	ret = libc_vopen(pathname, flags, ap);
	if (ret != -1) {
		/*
		 * There are methods for closing descriptors (libc-internal code
		 * paths, direct syscalls) which close descriptors in ways that
		 * we can't intercept, so try to recover when we notice that
		 * that's happened
		 */
		swrap_remove_stale(ret);
	}
	return ret;
}

int open(const char *pathname, int flags, ...)
{
	va_list ap;
	int fd;

	va_start(ap, flags);
	fd = swrap_vopen(pathname, flags, ap);
	va_end(ap);

	return fd;
}

/****************************************************************************
 *   OPEN64
 ***************************************************************************/

#ifdef HAVE_OPEN64
static int swrap_vopen64(const char *pathname, int flags, va_list ap)
{
	int ret;

	ret = libc_vopen64(pathname, flags, ap);
	if (ret != -1) {
		/*
		 * There are methods for closing descriptors (libc-internal code
		 * paths, direct syscalls) which close descriptors in ways that
		 * we can't intercept, so try to recover when we notice that
		 * that's happened
		 */
		swrap_remove_stale(ret);
	}
	return ret;
}

int open64(const char *pathname, int flags, ...)
{
	va_list ap;
	int fd;

	va_start(ap, flags);
	fd = swrap_vopen64(pathname, flags, ap);
	va_end(ap);

	return fd;
}
#endif /* HAVE_OPEN64 */

/****************************************************************************
 *   OPENAT
 ***************************************************************************/

static int swrap_vopenat(int dirfd, const char *path, int flags, va_list ap)
{
	int ret;

	ret = libc_vopenat(dirfd, path, flags, ap);
	if (ret != -1) {
		/*
		 * There are methods for closing descriptors (libc-internal code
		 * paths, direct syscalls) which close descriptors in ways that
		 * we can't intercept, so try to recover when we notice that
		 * that's happened
		 */
		swrap_remove_stale(ret);
	}

	return ret;
}

int openat(int dirfd, const char *path, int flags, ...)
{
	va_list ap;
	int fd;

	va_start(ap, flags);
	fd = swrap_vopenat(dirfd, path, flags, ap);
	va_end(ap);

	return fd;
}

/****************************************************************************
 *   GETPEERNAME
 ***************************************************************************/

static int swrap_getpeername(int s, struct sockaddr *name, socklen_t *addrlen)
{
	struct socket_info *si = find_socket_info(s);
	socklen_t len;
	int ret = -1;

	if (!si) {
		return libc_getpeername(s, name, addrlen);
	}

	SWRAP_LOCK_SI(si);

	if (si->peername.sa_socklen == 0)
	{
		errno = ENOTCONN;
		goto out;
	}

	len = MIN(*addrlen, si->peername.sa_socklen);
	if (len == 0) {
		ret = 0;
		goto out;
	}

	memcpy(name, &si->peername.sa.ss, len);
	*addrlen = si->peername.sa_socklen;

	ret = 0;
out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

#ifdef HAVE_ACCEPT_PSOCKLEN_T
int getpeername(int s, struct sockaddr *name, Psocklen_t addrlen)
#else
int getpeername(int s, struct sockaddr *name, socklen_t *addrlen)
#endif
{
	return swrap_getpeername(s, name, (socklen_t *)addrlen);
}

/****************************************************************************
 *   GETSOCKNAME
 ***************************************************************************/

static int swrap_getsockname(int s, struct sockaddr *name, socklen_t *addrlen)
{
	struct socket_info *si = find_socket_info(s);
	socklen_t len;
	int ret = -1;

	if (!si) {
		return libc_getsockname(s, name, addrlen);
	}

	SWRAP_LOCK_SI(si);

	len = MIN(*addrlen, si->myname.sa_socklen);
	if (len == 0) {
		ret = 0;
		goto out;
	}

	memcpy(name, &si->myname.sa.ss, len);
	*addrlen = si->myname.sa_socklen;

	ret = 0;
out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

#ifdef HAVE_ACCEPT_PSOCKLEN_T
int getsockname(int s, struct sockaddr *name, Psocklen_t addrlen)
#else
int getsockname(int s, struct sockaddr *name, socklen_t *addrlen)
#endif
{
	return swrap_getsockname(s, name, (socklen_t *)addrlen);
}

/****************************************************************************
 *   GETSOCKOPT
 ***************************************************************************/

#ifndef SO_PROTOCOL
# ifdef SO_PROTOTYPE /* The Solaris name */
#  define SO_PROTOCOL SO_PROTOTYPE
# endif /* SO_PROTOTYPE */
#endif /* SO_PROTOCOL */

static int swrap_getsockopt(int s, int level, int optname,
			    void *optval, socklen_t *optlen)
{
	struct socket_info *si = find_socket_info(s);
	int ret;

	if (!si) {
		return libc_getsockopt(s,
				       level,
				       optname,
				       optval,
				       optlen);
	}

	SWRAP_LOCK_SI(si);

	if (level == SOL_SOCKET) {
		switch (optname) {
#ifdef SO_DOMAIN
		case SO_DOMAIN:
			if (optval == NULL || optlen == NULL ||
			    *optlen < (socklen_t)sizeof(int)) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			*optlen = sizeof(int);
			*(int *)optval = si->family;
			ret = 0;
			goto done;
#endif /* SO_DOMAIN */

#ifdef SO_PROTOCOL
		case SO_PROTOCOL:
			if (optval == NULL || optlen == NULL ||
			    *optlen < (socklen_t)sizeof(int)) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			*optlen = sizeof(int);
			*(int *)optval = si->protocol;
			ret = 0;
			goto done;
#endif /* SO_PROTOCOL */
		case SO_TYPE:
			if (optval == NULL || optlen == NULL ||
			    *optlen < (socklen_t)sizeof(int)) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			*optlen = sizeof(int);
			*(int *)optval = si->type;
			ret = 0;
			goto done;
		default:
			ret = libc_getsockopt(s,
					      level,
					      optname,
					      optval,
					      optlen);
			goto done;
		}
	} else if (level == IPPROTO_TCP) {
		switch (optname) {
#ifdef TCP_NODELAY
		case TCP_NODELAY:
			/*
			 * This enables sending packets directly out over TCP.
			 * As a unix socket is doing that any way, report it as
			 * enabled.
			 */
			if (optval == NULL || optlen == NULL ||
			    *optlen < (socklen_t)sizeof(int)) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			*optlen = sizeof(int);
			*(int *)optval = si->tcp_nodelay;

			ret = 0;
			goto done;
#endif /* TCP_NODELAY */
#ifdef TCP_INFO
		case TCP_INFO: {
			struct tcp_info info;
			socklen_t ilen = sizeof(info);

#ifdef HAVE_NETINET_TCP_FSM_H
/* This is FreeBSD */
# define __TCP_LISTEN TCPS_LISTEN
# define __TCP_ESTABLISHED TCPS_ESTABLISHED
# define __TCP_CLOSE TCPS_CLOSED
#else
/* This is Linux */
# define __TCP_LISTEN TCP_LISTEN
# define __TCP_ESTABLISHED TCP_ESTABLISHED
# define __TCP_CLOSE TCP_CLOSE
#endif

			ZERO_STRUCT(info);
			if (si->listening) {
				info.tcpi_state = __TCP_LISTEN;
			} else if (si->connected) {
				/*
				 * For now we just fake a few values
				 * supported both by FreeBSD and Linux
				 */
				info.tcpi_state = __TCP_ESTABLISHED;
				info.tcpi_rto = 200000;  /* 200 msec */
				info.tcpi_rtt = 5000;    /* 5 msec */
				info.tcpi_rttvar = 5000; /* 5 msec */
			} else {
				info.tcpi_state = __TCP_CLOSE;
				info.tcpi_rto = 1000000;  /* 1 sec */
				info.tcpi_rtt = 0;
				info.tcpi_rttvar = 250000; /* 250 msec */
			}

			if (optval == NULL || optlen == NULL ||
			    *optlen < (socklen_t)ilen) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			*optlen = ilen;
			memcpy(optval, &info, ilen);

			ret = 0;
			goto done;
		}
#endif /* TCP_INFO */
		default:
			break;
		}
	}

	errno = ENOPROTOOPT;
	ret = -1;

done:
	SWRAP_UNLOCK_SI(si);
	return ret;
}

#ifdef HAVE_ACCEPT_PSOCKLEN_T
int getsockopt(int s, int level, int optname, void *optval, Psocklen_t optlen)
#else
int getsockopt(int s, int level, int optname, void *optval, socklen_t *optlen)
#endif
{
	return swrap_getsockopt(s, level, optname, optval, (socklen_t *)optlen);
}

/****************************************************************************
 *   SETSOCKOPT
 ***************************************************************************/

static int swrap_setsockopt(int s, int level, int optname,
			    const void *optval, socklen_t optlen)
{
	struct socket_info *si = find_socket_info(s);
	int ret;

	if (!si) {
		return libc_setsockopt(s,
				       level,
				       optname,
				       optval,
				       optlen);
	}

	if (level == SOL_SOCKET) {
		return libc_setsockopt(s,
				       level,
				       optname,
				       optval,
				       optlen);
	}

	SWRAP_LOCK_SI(si);

	if (level == IPPROTO_TCP) {
		switch (optname) {
#ifdef TCP_NODELAY
		case TCP_NODELAY: {
			int i;

			/*
			 * This enables sending packets directly out over TCP.
			 * A unix socket is doing that any way.
			 */
			if (optval == NULL || optlen == 0 ||
			    optlen < (socklen_t)sizeof(int)) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}

			i = *discard_const_p(int, optval);
			if (i != 0 && i != 1) {
				errno = EINVAL;
				ret = -1;
				goto done;
			}
			si->tcp_nodelay = i;

			ret = 0;
			goto done;
		}
#endif /* TCP_NODELAY */
		default:
			break;
		}
	}

	switch (si->family) {
	case AF_INET:
		if (level == IPPROTO_IP) {
#ifdef IP_PKTINFO
			if (optname == IP_PKTINFO) {
				si->pktinfo = AF_INET;
			}
#endif /* IP_PKTINFO */
		}
		ret = 0;
		goto done;
#ifdef HAVE_IPV6
	case AF_INET6:
		if (level == IPPROTO_IPV6) {
#ifdef IPV6_RECVPKTINFO
			if (optname == IPV6_RECVPKTINFO) {
				si->pktinfo = AF_INET6;
			}
#endif /* IPV6_PKTINFO */
		}
		ret = 0;
		goto done;
#endif
	default:
		errno = ENOPROTOOPT;
		ret = -1;
		goto done;
	}

done:
	SWRAP_UNLOCK_SI(si);
	return ret;
}

int setsockopt(int s, int level, int optname,
	       const void *optval, socklen_t optlen)
{
	return swrap_setsockopt(s, level, optname, optval, optlen);
}

/****************************************************************************
 *   IOCTL
 ***************************************************************************/

static int swrap_vioctl(int s, unsigned long int r, va_list va)
{
	struct socket_info *si = find_socket_info(s);
	va_list ap;
	int *value_ptr = NULL;
	int rc;

	if (!si) {
		return libc_vioctl(s, r, va);
	}

	SWRAP_LOCK_SI(si);

	va_copy(ap, va);

	rc = libc_vioctl(s, r, va);

	switch (r) {
	case FIONREAD:
		if (rc == 0) {
			value_ptr = ((int *)va_arg(ap, int *));
		}

		if (rc == -1 && errno != EAGAIN && errno != ENOBUFS) {
			swrap_pcap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
		} else if (value_ptr != NULL && *value_ptr == 0) { /* END OF FILE */
			swrap_pcap_dump_packet(si, NULL, SWRAP_PENDING_RST, NULL, 0);
		}
		break;
#ifdef FIONWRITE
	case FIONWRITE:
		/* this is FreeBSD */
		FALL_THROUGH; /* to TIOCOUTQ */
#endif /* FIONWRITE */
	case TIOCOUTQ: /* same as SIOCOUTQ on Linux */
		/*
		 * This may return more bytes then the application
		 * sent into the socket, for tcp it should
		 * return the number of unacked bytes.
		 *
		 * On AF_UNIX, all bytes are immediately acked!
		 */
		if (rc == 0) {
			value_ptr = ((int *)va_arg(ap, int *));
			*value_ptr = 0;
		}
		break;
	}

	va_end(ap);

	SWRAP_UNLOCK_SI(si);
	return rc;
}

#ifdef HAVE_IOCTL_INT
int ioctl(int s, int r, ...)
#else
int ioctl(int s, unsigned long int r, ...)
#endif
{
	va_list va;
	int rc;

	va_start(va, r);

	rc = swrap_vioctl(s, (unsigned long int) r, va);

	va_end(va);

	return rc;
}

/*****************
 * CMSG
 *****************/

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL

#ifndef CMSG_ALIGN
# ifdef _ALIGN /* BSD */
#define CMSG_ALIGN _ALIGN
# else
#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1))
# endif /* _ALIGN */
#endif /* CMSG_ALIGN */

/**
 * @brief Add a cmsghdr to a msghdr.
 *
 * This is an function to add any type of cmsghdr. It will operate on the
 * msg->msg_control and msg->msg_controllen you pass in by adapting them to
 * the buffer position after the added cmsg element. Hence, this function is
 * intended to be used with an intermediate msghdr and not on the original
 * one handed in by the client.
 *
 * @param[in]  msg      The msghdr to which to add the cmsg.
 *
 * @param[in]  level    The cmsg level to set.
 *
 * @param[in]  type     The cmsg type to set.
 *
 * @param[in]  data     The cmsg data to set.
 *
 * @param[in]  len      the length of the data to set.
 */
static void swrap_msghdr_add_cmsghdr(struct msghdr *msg,
				     int level,
				     int type,
				     const void *data,
				     size_t len)
{
	size_t cmlen = CMSG_LEN(len);
	size_t cmspace = CMSG_SPACE(len);
	uint8_t cmbuf[cmspace];
	void *cast_ptr = (void *)cmbuf;
	struct cmsghdr *cm = (struct cmsghdr *)cast_ptr;
	uint8_t *p;

	memset(cmbuf, 0, cmspace);

	if (msg->msg_controllen < cmlen) {
		cmlen = msg->msg_controllen;
		msg->msg_flags |= MSG_CTRUNC;
	}

	if (msg->msg_controllen < cmspace) {
		cmspace = msg->msg_controllen;
	}

	/*
	 * We copy the full input data into an intermediate cmsghdr first
	 * in order to more easily cope with truncation.
	 */
	cm->cmsg_len = cmlen;
	cm->cmsg_level = level;
	cm->cmsg_type = type;
	memcpy(CMSG_DATA(cm), data, len);

	/*
	 * We now copy the possibly truncated buffer.
	 * We copy cmlen bytes, but consume cmspace bytes,
	 * leaving the possible padding uninitialiazed.
	 */
	p = (uint8_t *)msg->msg_control;
	memcpy(p, cm, cmlen);
	p += cmspace;
	msg->msg_control = p;
	msg->msg_controllen -= cmspace;

	return;
}

static int swrap_msghdr_add_pktinfo(struct socket_info *si,
				    struct msghdr *msg)
{
	/* Add packet info */
	switch (si->pktinfo) {
#if defined(IP_PKTINFO) && (defined(HAVE_STRUCT_IN_PKTINFO) || defined(IP_RECVDSTADDR))
	case AF_INET: {
		struct sockaddr_in *sin;
#if defined(HAVE_STRUCT_IN_PKTINFO)
		struct in_pktinfo pkt;
#elif defined(IP_RECVDSTADDR)
		struct in_addr pkt;
#endif

		if (si->bindname.sa_socklen == sizeof(struct sockaddr_in)) {
			sin = &si->bindname.sa.in;
		} else {
			if (si->myname.sa_socklen != sizeof(struct sockaddr_in)) {
				return 0;
			}
			sin = &si->myname.sa.in;
		}

		ZERO_STRUCT(pkt);

#if defined(HAVE_STRUCT_IN_PKTINFO)
		pkt.ipi_ifindex = socket_wrapper_default_iface();
		pkt.ipi_addr.s_addr = sin->sin_addr.s_addr;
#elif defined(IP_RECVDSTADDR)
		pkt = sin->sin_addr;
#endif

		swrap_msghdr_add_cmsghdr(msg, IPPROTO_IP, IP_PKTINFO,
					 &pkt, sizeof(pkt));

		break;
	}
#endif /* IP_PKTINFO */
#if defined(HAVE_IPV6)
	case AF_INET6: {
#if defined(IPV6_PKTINFO) && defined(HAVE_STRUCT_IN6_PKTINFO)
		struct sockaddr_in6 *sin6;
		struct in6_pktinfo pkt6;

		if (si->bindname.sa_socklen == sizeof(struct sockaddr_in6)) {
			sin6 = &si->bindname.sa.in6;
		} else {
			if (si->myname.sa_socklen != sizeof(struct sockaddr_in6)) {
				return 0;
			}
			sin6 = &si->myname.sa.in6;
		}

		ZERO_STRUCT(pkt6);

		pkt6.ipi6_ifindex = socket_wrapper_default_iface();
		pkt6.ipi6_addr = sin6->sin6_addr;

		swrap_msghdr_add_cmsghdr(msg, IPPROTO_IPV6, IPV6_PKTINFO,
					&pkt6, sizeof(pkt6));
#endif /* HAVE_STRUCT_IN6_PKTINFO */

		break;
	}
#endif /* IPV6_PKTINFO */
	default:
		return -1;
	}

	return 0;
}

static int swrap_msghdr_add_socket_info(struct socket_info *si,
					struct msghdr *omsg)
{
	int rc = 0;

	if (si->pktinfo > 0) {
		rc = swrap_msghdr_add_pktinfo(si, omsg);
	}

	return rc;
}

static int swrap_sendmsg_copy_cmsg(struct cmsghdr *cmsg,
				   uint8_t **cm_data,
				   size_t *cm_data_space);
static int swrap_sendmsg_filter_cmsg_socket(struct cmsghdr *cmsg,
					    uint8_t **cm_data,
					    size_t *cm_data_space);

static int swrap_sendmsg_filter_cmsghdr(struct msghdr *msg,
					uint8_t **cm_data,
					size_t *cm_data_space) {
	struct cmsghdr *cmsg;
	int rc = -1;

	/* Nothing to do */
	if (msg->msg_controllen == 0 || msg->msg_control == NULL) {
		return 0;
	}

	for (cmsg = CMSG_FIRSTHDR(msg);
	     cmsg != NULL;
	     cmsg = CMSG_NXTHDR(msg, cmsg)) {
		switch (cmsg->cmsg_level) {
		case IPPROTO_IP:
			rc = swrap_sendmsg_filter_cmsg_socket(cmsg,
							      cm_data,
							      cm_data_space);
			break;
		default:
			rc = swrap_sendmsg_copy_cmsg(cmsg,
						     cm_data,
						     cm_data_space);
			break;
		}
	}

	return rc;
}

static int swrap_sendmsg_copy_cmsg(struct cmsghdr *cmsg,
				   uint8_t **cm_data,
				   size_t *cm_data_space)
{
	size_t cmspace;
	uint8_t *p;

	cmspace = *cm_data_space + CMSG_ALIGN(cmsg->cmsg_len);

	p = realloc((*cm_data), cmspace);
	if (p == NULL) {
		return -1;
	}
	(*cm_data) = p;

	p = (*cm_data) + (*cm_data_space);
	*cm_data_space = cmspace;

	memcpy(p, cmsg, cmsg->cmsg_len);

	return 0;
}

static int swrap_sendmsg_filter_cmsg_pktinfo(struct cmsghdr *cmsg,
					    uint8_t **cm_data,
					    size_t *cm_data_space);


static int swrap_sendmsg_filter_cmsg_socket(struct cmsghdr *cmsg,
					    uint8_t **cm_data,
					    size_t *cm_data_space)
{
	int rc = -1;

	switch(cmsg->cmsg_type) {
#ifdef IP_PKTINFO
	case IP_PKTINFO:
		rc = swrap_sendmsg_filter_cmsg_pktinfo(cmsg,
						       cm_data,
						       cm_data_space);
		break;
#endif
#ifdef IPV6_PKTINFO
	case IPV6_PKTINFO:
		rc = swrap_sendmsg_filter_cmsg_pktinfo(cmsg,
						       cm_data,
						       cm_data_space);
		break;
#endif
	default:
		break;
	}

	return rc;
}

static int swrap_sendmsg_filter_cmsg_pktinfo(struct cmsghdr *cmsg,
					     uint8_t **cm_data,
					     size_t *cm_data_space)
{
	(void)cmsg; /* unused */
	(void)cm_data; /* unused */
	(void)cm_data_space; /* unused */

	/*
	 * Passing a IP pktinfo to a unix socket might be rejected by the
	 * Kernel, at least on FreeBSD. So skip this cmsg.
	 */
	return 0;
}
#endif /* HAVE_STRUCT_MSGHDR_MSG_CONTROL */

static ssize_t swrap_sendmsg_before(int fd,
				    struct socket_info *si,
				    struct msghdr *msg,
				    struct iovec *tmp_iov,
				    struct sockaddr_un *tmp_un,
				    const struct sockaddr_un **to_un,
				    const struct sockaddr **to,
				    int *bcast)
{
	size_t i, len = 0;
	ssize_t ret = -1;

	if (to_un) {
		*to_un = NULL;
	}
	if (to) {
		*to = NULL;
	}
	if (bcast) {
		*bcast = 0;
	}

	SWRAP_LOCK_SI(si);

	switch (si->type) {
	case SOCK_STREAM: {
		unsigned long mtu;

		if (!si->connected) {
			errno = ENOTCONN;
			goto out;
		}

		if (msg->msg_iovlen == 0) {
			break;
		}

		mtu = socket_wrapper_mtu();
		for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
			size_t nlen;
			nlen = len + msg->msg_iov[i].iov_len;
			if (nlen < len) {
				/* overflow */
				errno = EMSGSIZE;
				goto out;
			}
			if (nlen > mtu) {
				break;
			}
		}
		msg->msg_iovlen = i;
		if (msg->msg_iovlen == 0) {
			*tmp_iov = msg->msg_iov[0];
			tmp_iov->iov_len = MIN((size_t)tmp_iov->iov_len,
					       (size_t)mtu);
			msg->msg_iov = tmp_iov;
			msg->msg_iovlen = 1;
		}
		break;
	}
	case SOCK_DGRAM:
		if (si->connected) {
			if (msg->msg_name != NULL) {
				/*
				 * We are dealing with unix sockets and if we
				 * are connected, we should only talk to the
				 * connected unix path. Using the fd to send
				 * to another server would be hard to achieve.
				 */
				msg->msg_name = NULL;
				msg->msg_namelen = 0;
			}
		} else {
			const struct sockaddr *msg_name;
			msg_name = (const struct sockaddr *)msg->msg_name;

			if (msg_name == NULL) {
				errno = ENOTCONN;
				goto out;
			}


			ret = sockaddr_convert_to_un(si, msg_name, msg->msg_namelen,
						     tmp_un, 0, bcast);
			if (ret == -1) {
				goto out;
			}

			if (to_un) {
				*to_un = tmp_un;
			}
			if (to) {
				*to = msg_name;
			}
			msg->msg_name = tmp_un;
			msg->msg_namelen = sizeof(*tmp_un);
		}

		if (si->bound == 0) {
			ret = swrap_auto_bind(fd, si, si->family);
			if (ret == -1) {
				SWRAP_UNLOCK_SI(si);
				if (errno == ENOTSOCK) {
					swrap_remove_stale(fd);
					ret = -ENOTSOCK;
				} else {
					SWRAP_LOG(SWRAP_LOG_ERROR, "swrap_sendmsg_before failed");
				}
				return ret;
			}
		}

		if (!si->defer_connect) {
			break;
		}

		ret = sockaddr_convert_to_un(si,
					     &si->peername.sa.s,
					     si->peername.sa_socklen,
					     tmp_un,
					     0,
					     NULL);
		if (ret == -1) {
			goto out;
		}

		ret = libc_connect(fd,
				   (struct sockaddr *)(void *)tmp_un,
				   sizeof(*tmp_un));

		/* to give better errors */
		if (ret == -1 && errno == ENOENT) {
			errno = EHOSTUNREACH;
		}

		if (ret == -1) {
			goto out;
		}

		si->defer_connect = 0;
		break;
	default:
		errno = EHOSTUNREACH;
		goto out;
	}

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	if (msg->msg_controllen > 0 && msg->msg_control != NULL) {
		uint8_t *cmbuf = NULL;
		size_t cmlen = 0;

		ret = swrap_sendmsg_filter_cmsghdr(msg, &cmbuf, &cmlen);
		if (ret < 0) {
			free(cmbuf);
			goto out;
		}

		if (cmlen == 0) {
			msg->msg_controllen = 0;
			msg->msg_control = NULL;
		} else if (cmlen < msg->msg_controllen && cmbuf != NULL) {
			memcpy(msg->msg_control, cmbuf, cmlen);
			msg->msg_controllen = cmlen;
		}
		free(cmbuf);
	}
#endif

	ret = 0;
out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

static void swrap_sendmsg_after(int fd,
				struct socket_info *si,
				struct msghdr *msg,
				const struct sockaddr *to,
				ssize_t ret)
{
	int saved_errno = errno;
	size_t i, len = 0;
	uint8_t *buf;
	off_t ofs = 0;
	size_t avail = 0;
	size_t remain;

	/* to give better errors */
	if (ret == -1) {
		if (saved_errno == ENOENT) {
			saved_errno = EHOSTUNREACH;
		} else if (saved_errno == ENOTSOCK) {
			/* If the fd is not a socket, remove it */
			swrap_remove_stale(fd);
		}
	}

	for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
		avail += msg->msg_iov[i].iov_len;
	}

	if (ret == -1) {
		remain = MIN(80, avail);
	} else {
		remain = ret;
	}

	/* we capture it as one single packet */
	buf = (uint8_t *)malloc(remain);
	if (!buf) {
		/* we just not capture the packet */
		errno = saved_errno;
		return;
	}

	for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
		size_t this_time = MIN(remain, (size_t)msg->msg_iov[i].iov_len);
		memcpy(buf + ofs,
		       msg->msg_iov[i].iov_base,
		       this_time);
		ofs += this_time;
		remain -= this_time;
	}
	len = ofs;

	SWRAP_LOCK_SI(si);

	switch (si->type) {
	case SOCK_STREAM:
		if (ret == -1) {
			swrap_pcap_dump_packet(si, NULL, SWRAP_SEND, buf, len);
			swrap_pcap_dump_packet(si, NULL, SWRAP_SEND_RST, NULL, 0);
		} else {
			swrap_pcap_dump_packet(si, NULL, SWRAP_SEND, buf, len);
		}
		break;

	case SOCK_DGRAM:
		if (si->connected) {
			to = &si->peername.sa.s;
		}
		if (ret == -1) {
			swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
			swrap_pcap_dump_packet(si, to, SWRAP_SENDTO_UNREACH, buf, len);
		} else {
			swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
		}
		break;
	}

	SWRAP_UNLOCK_SI(si);

	free(buf);
	errno = saved_errno;
}

static int swrap_recvmsg_before(int fd,
				struct socket_info *si,
				struct msghdr *msg,
				struct iovec *tmp_iov)
{
	size_t i, len = 0;
	int ret = -1;

	SWRAP_LOCK_SI(si);

	(void)fd; /* unused */

	switch (si->type) {
	case SOCK_STREAM: {
		unsigned int mtu;
		if (!si->connected) {
			errno = ENOTCONN;
			goto out;
		}

		if (msg->msg_iovlen == 0) {
			break;
		}

		mtu = socket_wrapper_mtu();
		for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
			size_t nlen;
			nlen = len + msg->msg_iov[i].iov_len;
			if (nlen > mtu) {
				break;
			}
		}
		msg->msg_iovlen = i;
		if (msg->msg_iovlen == 0) {
			*tmp_iov = msg->msg_iov[0];
			tmp_iov->iov_len = MIN((size_t)tmp_iov->iov_len,
					       (size_t)mtu);
			msg->msg_iov = tmp_iov;
			msg->msg_iovlen = 1;
		}
		break;
	}
	case SOCK_DGRAM:
		if (msg->msg_name == NULL) {
			errno = EINVAL;
			goto out;
		}

		if (msg->msg_iovlen == 0) {
			break;
		}

		if (si->bound == 0) {
			ret = swrap_auto_bind(fd, si, si->family);
			if (ret == -1) {
				SWRAP_UNLOCK_SI(si);
				/*
				 * When attempting to read or write to a
				 * descriptor, if an underlying autobind fails
				 * because it's not a socket, stop intercepting
				 * uses of that descriptor.
				 */
				if (errno == ENOTSOCK) {
					swrap_remove_stale(fd);
					ret = -ENOTSOCK;
				} else {
					SWRAP_LOG(SWRAP_LOG_ERROR,
						  "swrap_recvmsg_before failed");
				}
				return ret;
			}
		}
		break;
	default:
		errno = EHOSTUNREACH;
		goto out;
	}

	ret = 0;
out:
	SWRAP_UNLOCK_SI(si);

	return ret;
}

static int swrap_recvmsg_after(int fd,
			       struct socket_info *si,
			       struct msghdr *msg,
			       const struct sockaddr_un *un_addr,
			       socklen_t un_addrlen,
			       ssize_t ret)
{
	int saved_errno = errno;
	size_t i;
	uint8_t *buf = NULL;
	off_t ofs = 0;
	size_t avail = 0;
	size_t remain;
	int rc;

	/* to give better errors */
	if (ret == -1) {
		if (saved_errno == ENOENT) {
			saved_errno = EHOSTUNREACH;
		} else if (saved_errno == ENOTSOCK) {
			/* If the fd is not a socket, remove it */
			swrap_remove_stale(fd);
		}
	}

	for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
		avail += msg->msg_iov[i].iov_len;
	}

	SWRAP_LOCK_SI(si);

	/* Convert the socket address before we leave */
	if (si->type == SOCK_DGRAM && un_addr != NULL) {
		rc = sockaddr_convert_from_un(si,
					      un_addr,
					      un_addrlen,
					      si->family,
					      msg->msg_name,
					      &msg->msg_namelen);
		if (rc == -1) {
			goto done;
		}
	}

	if (avail == 0) {
		rc = 0;
		goto done;
	}

	if (ret == -1) {
		remain = MIN(80, avail);
	} else {
		remain = ret;
	}

	/* we capture it as one single packet */
	buf = (uint8_t *)malloc(remain);
	if (buf == NULL) {
		/* we just not capture the packet */
		SWRAP_UNLOCK_SI(si);
		errno = saved_errno;
		return -1;
	}

	for (i = 0; i < (size_t)msg->msg_iovlen; i++) {
		size_t this_time = MIN(remain, (size_t)msg->msg_iov[i].iov_len);
		memcpy(buf + ofs,
		       msg->msg_iov[i].iov_base,
		       this_time);
		ofs += this_time;
		remain -= this_time;
	}

	switch (si->type) {
	case SOCK_STREAM:
		if (ret == -1 && saved_errno != EAGAIN && saved_errno != ENOBUFS) {
			swrap_pcap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
		} else if (ret == 0) { /* END OF FILE */
			swrap_pcap_dump_packet(si, NULL, SWRAP_RECV_RST, NULL, 0);
		} else if (ret > 0) {
			swrap_pcap_dump_packet(si, NULL, SWRAP_RECV, buf, ret);
		}
		break;

	case SOCK_DGRAM:
		if (ret == -1) {
			break;
		}

		if (un_addr != NULL) {
			swrap_pcap_dump_packet(si,
					  msg->msg_name,
					  SWRAP_RECVFROM,
					  buf,
					  ret);
		} else {
			swrap_pcap_dump_packet(si,
					  msg->msg_name,
					  SWRAP_RECV,
					  buf,
					  ret);
		}

		break;
	}

	rc = 0;
done:
	free(buf);
	errno = saved_errno;

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	if (rc == 0 &&
	    msg->msg_controllen > 0 &&
	    msg->msg_control != NULL) {
		rc = swrap_msghdr_add_socket_info(si, msg);
		if (rc < 0) {
			SWRAP_UNLOCK_SI(si);
			return -1;
		}
	}
#endif

	SWRAP_UNLOCK_SI(si);
	return rc;
}

/****************************************************************************
 *   RECVFROM
 ***************************************************************************/

static ssize_t swrap_recvfrom(int s, void *buf, size_t len, int flags,
			      struct sockaddr *from, socklen_t *fromlen)
{
	struct swrap_address from_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	ssize_t ret;
	struct socket_info *si = find_socket_info(s);
	struct swrap_address saddr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	struct msghdr msg;
	struct iovec tmp;
	int tret;

	if (!si) {
		return libc_recvfrom(s,
				     buf,
				     len,
				     flags,
				     from,
				     fromlen);
	}

	tmp.iov_base = buf;
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	if (from != NULL && fromlen != NULL) {
		msg.msg_name = from;   /* optional address */
		msg.msg_namelen = *fromlen; /* size of address */
	} else {
		msg.msg_name = &saddr.sa.s; /* optional address */
		msg.msg_namelen = saddr.sa_socklen; /* size of address */
	}
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	tret = swrap_recvmsg_before(s, si, &msg, &tmp);
	if (tret < 0) {
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	ret = libc_recvfrom(s,
			    buf,
			    len,
			    flags,
			    &from_addr.sa.s,
			    &from_addr.sa_socklen);
	if (ret == -1) {
		return ret;
	}

	tret = swrap_recvmsg_after(s,
				   si,
				   &msg,
				   &from_addr.sa.un,
				   from_addr.sa_socklen,
				   ret);
	if (tret != 0) {
		return tret;
	}

	if (from != NULL && fromlen != NULL) {
		*fromlen = msg.msg_namelen;
	}

	return ret;
}

#ifdef HAVE_ACCEPT_PSOCKLEN_T
ssize_t recvfrom(int s, void *buf, size_t len, int flags,
		 struct sockaddr *from, Psocklen_t fromlen)
#else
ssize_t recvfrom(int s, void *buf, size_t len, int flags,
		 struct sockaddr *from, socklen_t *fromlen)
#endif
{
	return swrap_recvfrom(s, buf, len, flags, from, (socklen_t *)fromlen);
}

/****************************************************************************
 *   SENDTO
 ***************************************************************************/

static ssize_t swrap_sendto(int s, const void *buf, size_t len, int flags,
			    const struct sockaddr *to, socklen_t tolen)
{
	struct msghdr msg;
	struct iovec tmp;
	struct swrap_address un_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	const struct sockaddr_un *to_un = NULL;
	ssize_t ret;
	int rc;
	struct socket_info *si = find_socket_info(s);
	int bcast = 0;

	if (!si) {
		return libc_sendto(s, buf, len, flags, to, tolen);
	}

	tmp.iov_base = discard_const_p(char, buf);
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	msg.msg_name = discard_const_p(struct sockaddr, to); /* optional address */
	msg.msg_namelen = tolen;       /* size of address */
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	rc = swrap_sendmsg_before(s,
				  si,
				  &msg,
				  &tmp,
				  &un_addr.sa.un,
				  &to_un,
				  &to,
				  &bcast);
	if (rc < 0) {
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	if (bcast) {
		struct stat st;
		unsigned int iface;
		unsigned int prt = ntohs(((const struct sockaddr_in *)(const void *)to)->sin_port);
		char type;
		char *swrap_dir = NULL;

		type = SOCKET_TYPE_CHAR_UDP;

		swrap_dir = socket_wrapper_dir();
		if (swrap_dir == NULL) {
			return -1;
		}

		for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) {
			swrap_un_path(&un_addr.sa.un,
				      swrap_dir,
				      type,
				      iface,
				      prt);
			if (stat(un_addr.sa.un.sun_path, &st) != 0) continue;

			/* ignore the any errors in broadcast sends */
			libc_sendto(s,
				    buf,
				    len,
				    flags,
				    &un_addr.sa.s,
				    un_addr.sa_socklen);
		}

		SAFE_FREE(swrap_dir);

		SWRAP_LOCK_SI(si);

		swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len);

		SWRAP_UNLOCK_SI(si);

		return len;
	}

	SWRAP_LOCK_SI(si);
	/*
	 * If it is a dgram socket and we are connected, don't include the
	 * 'to' address.
	 */
	if (si->type == SOCK_DGRAM && si->connected) {
		ret = libc_sendto(s,
				  buf,
				  len,
				  flags,
				  NULL,
				  0);
	} else {
		ret = libc_sendto(s,
				  buf,
				  len,
				  flags,
				  (struct sockaddr *)msg.msg_name,
				  msg.msg_namelen);
	}

	SWRAP_UNLOCK_SI(si);

	swrap_sendmsg_after(s, si, &msg, to, ret);

	return ret;
}

ssize_t sendto(int s, const void *buf, size_t len, int flags,
	       const struct sockaddr *to, socklen_t tolen)
{
	return swrap_sendto(s, buf, len, flags, to, tolen);
}

/****************************************************************************
 *   READV
 ***************************************************************************/

static ssize_t swrap_recv(int s, void *buf, size_t len, int flags)
{
	struct socket_info *si;
	struct msghdr msg;
	struct swrap_address saddr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	struct iovec tmp;
	ssize_t ret;
	int tret;

	si = find_socket_info(s);
	if (si == NULL) {
		return libc_recv(s, buf, len, flags);
	}

	tmp.iov_base = buf;
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	msg.msg_name = &saddr.sa.s;    /* optional address */
	msg.msg_namelen = saddr.sa_socklen; /* size of address */
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	tret = swrap_recvmsg_before(s, si, &msg, &tmp);
	if (tret < 0) {
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	ret = libc_recv(s, buf, len, flags);

	tret = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret);
	if (tret != 0) {
		return tret;
	}

	return ret;
}

ssize_t recv(int s, void *buf, size_t len, int flags)
{
	return swrap_recv(s, buf, len, flags);
}

/****************************************************************************
 *   READ
 ***************************************************************************/

static ssize_t swrap_read(int s, void *buf, size_t len)
{
	struct socket_info *si;
	struct msghdr msg;
	struct iovec tmp;
	struct swrap_address saddr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	ssize_t ret;
	int tret;

	si = find_socket_info(s);
	if (si == NULL) {
		return libc_read(s, buf, len);
	}

	tmp.iov_base = buf;
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	msg.msg_name = &saddr.sa.ss;   /* optional address */
	msg.msg_namelen = saddr.sa_socklen; /* size of address */
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	tret = swrap_recvmsg_before(s, si, &msg, &tmp);
	if (tret < 0) {
		if (tret == -ENOTSOCK) {
			return libc_read(s, buf, len);
		}
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	ret = libc_read(s, buf, len);

	tret = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret);
	if (tret != 0) {
		return tret;
	}

	return ret;
}

ssize_t read(int s, void *buf, size_t len)
{
	return swrap_read(s, buf, len);
}

/****************************************************************************
 *   WRITE
 ***************************************************************************/

static ssize_t swrap_write(int s, const void *buf, size_t len)
{
	struct msghdr msg;
	struct iovec tmp;
	struct sockaddr_un un_addr;
	ssize_t ret;
	int rc;
	struct socket_info *si;

	si = find_socket_info(s);
	if (si == NULL) {
		return libc_write(s, buf, len);
	}

	tmp.iov_base = discard_const_p(char, buf);
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	msg.msg_name = NULL;           /* optional address */
	msg.msg_namelen = 0;           /* size of address */
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL);
	if (rc < 0) {
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	ret = libc_write(s, buf, len);

	swrap_sendmsg_after(s, si, &msg, NULL, ret);

	return ret;
}

ssize_t write(int s, const void *buf, size_t len)
{
	return swrap_write(s, buf, len);
}

/****************************************************************************
 *   SEND
 ***************************************************************************/

static ssize_t swrap_send(int s, const void *buf, size_t len, int flags)
{
	struct msghdr msg;
	struct iovec tmp;
	struct sockaddr_un un_addr;
	ssize_t ret;
	int rc;
	struct socket_info *si = find_socket_info(s);

	if (!si) {
		return libc_send(s, buf, len, flags);
	}

	tmp.iov_base = discard_const_p(char, buf);
	tmp.iov_len = len;

	ZERO_STRUCT(msg);
	msg.msg_name = NULL;           /* optional address */
	msg.msg_namelen = 0;           /* size of address */
	msg.msg_iov = &tmp;            /* scatter/gather array */
	msg.msg_iovlen = 1;            /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL);
	if (rc < 0) {
		return -1;
	}

	buf = msg.msg_iov[0].iov_base;
	len = msg.msg_iov[0].iov_len;

	ret = libc_send(s, buf, len, flags);

	swrap_sendmsg_after(s, si, &msg, NULL, ret);

	return ret;
}

ssize_t send(int s, const void *buf, size_t len, int flags)
{
	return swrap_send(s, buf, len, flags);
}

/****************************************************************************
 *   RECVMSG
 ***************************************************************************/

static ssize_t swrap_recvmsg(int s, struct msghdr *omsg, int flags)
{
	struct swrap_address from_addr = {
		.sa_socklen = sizeof(struct sockaddr_un),
	};
	struct swrap_address convert_addr = {
		.sa_socklen = sizeof(struct sockaddr_storage),
	};
	struct socket_info *si;
	struct msghdr msg;
	struct iovec tmp;
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	size_t msg_ctrllen_filled;
	size_t msg_ctrllen_left;
#endif

	ssize_t ret;
	int rc;

	si = find_socket_info(s);
	if (si == NULL) {
		return libc_recvmsg(s, omsg, flags);
	}

	tmp.iov_base = NULL;
	tmp.iov_len = 0;

	ZERO_STRUCT(msg);
	msg.msg_name = &from_addr.sa;              /* optional address */
	msg.msg_namelen = from_addr.sa_socklen;    /* size of address */
	msg.msg_iov = omsg->msg_iov;               /* scatter/gather array */
	msg.msg_iovlen = omsg->msg_iovlen;         /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg_ctrllen_filled = 0;
	msg_ctrllen_left = omsg->msg_controllen;

	msg.msg_control = omsg->msg_control;       /* ancillary data, see below */
	msg.msg_controllen = omsg->msg_controllen; /* ancillary data buffer len */
	msg.msg_flags = omsg->msg_flags;           /* flags on received message */
#endif

	rc = swrap_recvmsg_before(s, si, &msg, &tmp);
	if (rc < 0) {
		return -1;
	}

	ret = libc_recvmsg(s, &msg, flags);

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg_ctrllen_filled += msg.msg_controllen;
	msg_ctrllen_left -= msg.msg_controllen;

	if (omsg->msg_control != NULL) {
		uint8_t *p;

		p = omsg->msg_control;
		p += msg_ctrllen_filled;

		msg.msg_control = p;
		msg.msg_controllen = msg_ctrllen_left;
	} else {
		msg.msg_control = NULL;
		msg.msg_controllen = 0;
	}
#endif

	/*
	 * We convert the unix address to a IP address so we need a buffer
	 * which can store the address in case of SOCK_DGRAM, see below.
	 */
	msg.msg_name = &convert_addr.sa;
	msg.msg_namelen = convert_addr.sa_socklen;

	rc = swrap_recvmsg_after(s,
				 si,
				 &msg,
				 &from_addr.sa.un,
				 from_addr.sa_socklen,
				 ret);
	if (rc != 0) {
		return rc;
	}

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	if (omsg->msg_control != NULL) {
		/* msg.msg_controllen = space left */
		msg_ctrllen_left = msg.msg_controllen;
		msg_ctrllen_filled = omsg->msg_controllen - msg_ctrllen_left;
	}

	/* Update the original message length */
	omsg->msg_controllen = msg_ctrllen_filled;
	omsg->msg_flags = msg.msg_flags;
#endif
	omsg->msg_iovlen = msg.msg_iovlen;

	SWRAP_LOCK_SI(si);

	/*
	 * From the manpage:
	 *
	 * The  msg_name  field  points  to a caller-allocated buffer that is
	 * used to return the source address if the socket is unconnected.  The
	 * caller should set msg_namelen to the size of this buffer before this
	 * call; upon return from a successful call, msg_name will contain the
	 * length of the returned address.  If the application  does  not  need
	 * to know the source address, msg_name can be specified as NULL.
	 */
	if (si->type == SOCK_STREAM) {
		omsg->msg_namelen = 0;
	} else if (omsg->msg_name != NULL &&
	           omsg->msg_namelen != 0 &&
	           omsg->msg_namelen >= msg.msg_namelen) {
		memcpy(omsg->msg_name, msg.msg_name, msg.msg_namelen);
		omsg->msg_namelen = msg.msg_namelen;
	}

	SWRAP_UNLOCK_SI(si);

	return ret;
}

ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags)
{
	return swrap_recvmsg(sockfd, msg, flags);
}

/****************************************************************************
 *   SENDMSG
 ***************************************************************************/

static ssize_t swrap_sendmsg(int s, const struct msghdr *omsg, int flags)
{
	struct msghdr msg;
	struct iovec tmp;
	struct sockaddr_un un_addr;
	const struct sockaddr_un *to_un = NULL;
	const struct sockaddr *to = NULL;
	ssize_t ret;
	int rc;
	struct socket_info *si = find_socket_info(s);
	int bcast = 0;

	if (!si) {
		return libc_sendmsg(s, omsg, flags);
	}

	ZERO_STRUCT(un_addr);

	tmp.iov_base = NULL;
	tmp.iov_len = 0;

	ZERO_STRUCT(msg);

	SWRAP_LOCK_SI(si);

	if (si->connected == 0) {
		msg.msg_name = omsg->msg_name;             /* optional address */
		msg.msg_namelen = omsg->msg_namelen;       /* size of address */
	}
	msg.msg_iov = omsg->msg_iov;               /* scatter/gather array */
	msg.msg_iovlen = omsg->msg_iovlen;         /* # elements in msg_iov */

	SWRAP_UNLOCK_SI(si);

#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	if (msg.msg_controllen > 0 && msg.msg_control != NULL) {
		/* omsg is a const so use a local buffer for modifications */
		uint8_t cmbuf[omsg->msg_controllen];

		memcpy(cmbuf, omsg->msg_control, omsg->msg_controllen);

		msg.msg_control = cmbuf;       /* ancillary data, see below */
		msg.msg_controllen = omsg->msg_controllen; /* ancillary data buffer len */
	}
	msg.msg_flags = omsg->msg_flags;           /* flags on received message */
#endif

	rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, &to_un, &to, &bcast);
	if (rc < 0) {
		return -1;
	}

	if (bcast) {
		struct stat st;
		unsigned int iface;
		unsigned int prt = ntohs(((const struct sockaddr_in *)(const void *)to)->sin_port);
		char type;
		size_t i, len = 0;
		uint8_t *buf;
		off_t ofs = 0;
		size_t avail = 0;
		size_t remain;
		char *swrap_dir = NULL;

		for (i = 0; i < (size_t)msg.msg_iovlen; i++) {
			avail += msg.msg_iov[i].iov_len;
		}

		len = avail;
		remain = avail;

		/* we capture it as one single packet */
		buf = (uint8_t *)malloc(remain);
		if (!buf) {
			return -1;
		}

		for (i = 0; i < (size_t)msg.msg_iovlen; i++) {
			size_t this_time = MIN(remain, (size_t)msg.msg_iov[i].iov_len);
			memcpy(buf + ofs,
			       msg.msg_iov[i].iov_base,
			       this_time);
			ofs += this_time;
			remain -= this_time;
		}

		type = SOCKET_TYPE_CHAR_UDP;

		swrap_dir = socket_wrapper_dir();
		if (swrap_dir == NULL) {
			free(buf);
			return -1;
		}

		for(iface=0; iface <= MAX_WRAPPED_INTERFACES; iface++) {
			swrap_un_path(&un_addr, swrap_dir, type, iface, prt);
			if (stat(un_addr.sun_path, &st) != 0) continue;

			msg.msg_name = &un_addr;           /* optional address */
			msg.msg_namelen = sizeof(un_addr); /* size of address */

			/* ignore the any errors in broadcast sends */
			libc_sendmsg(s, &msg, flags);
		}

		SAFE_FREE(swrap_dir);

		SWRAP_LOCK_SI(si);

		swrap_pcap_dump_packet(si, to, SWRAP_SENDTO, buf, len);
		free(buf);

		SWRAP_UNLOCK_SI(si);

		return len;
	}

	ret = libc_sendmsg(s, &msg, flags);

	swrap_sendmsg_after(s, si, &msg, to, ret);

	return ret;
}

ssize_t sendmsg(int s, const struct msghdr *omsg, int flags)
{
	return swrap_sendmsg(s, omsg, flags);
}

/****************************************************************************
 *   READV
 ***************************************************************************/

static ssize_t swrap_readv(int s, const struct iovec *vector, int count)
{
	struct socket_info *si;
	struct msghdr msg;
	struct iovec tmp;
	struct swrap_address saddr = {
		.sa_socklen = sizeof(struct sockaddr_storage)
	};
	ssize_t ret;
	int rc;

	si = find_socket_info(s);
	if (si == NULL) {
		return libc_readv(s, vector, count);
	}

	tmp.iov_base = NULL;
	tmp.iov_len = 0;

	ZERO_STRUCT(msg);
	msg.msg_name = &saddr.sa.s; /* optional address */
	msg.msg_namelen = saddr.sa_socklen;      /* size of address */
	msg.msg_iov = discard_const_p(struct iovec, vector); /* scatter/gather array */
	msg.msg_iovlen = count;        /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	rc = swrap_recvmsg_before(s, si, &msg, &tmp);
	if (rc < 0) {
		if (rc == -ENOTSOCK) {
			return libc_readv(s, vector, count);
		}
		return -1;
	}

	ret = libc_readv(s, msg.msg_iov, msg.msg_iovlen);

	rc = swrap_recvmsg_after(s, si, &msg, NULL, 0, ret);
	if (rc != 0) {
		return rc;
	}

	return ret;
}

ssize_t readv(int s, const struct iovec *vector, int count)
{
	return swrap_readv(s, vector, count);
}

/****************************************************************************
 *   WRITEV
 ***************************************************************************/

static ssize_t swrap_writev(int s, const struct iovec *vector, int count)
{
	struct msghdr msg;
	struct iovec tmp;
	struct sockaddr_un un_addr;
	ssize_t ret;
	int rc;
	struct socket_info *si = find_socket_info(s);

	if (!si) {
		return libc_writev(s, vector, count);
	}

	tmp.iov_base = NULL;
	tmp.iov_len = 0;

	ZERO_STRUCT(msg);
	msg.msg_name = NULL;           /* optional address */
	msg.msg_namelen = 0;           /* size of address */
	msg.msg_iov = discard_const_p(struct iovec, vector); /* scatter/gather array */
	msg.msg_iovlen = count;        /* # elements in msg_iov */
#ifdef HAVE_STRUCT_MSGHDR_MSG_CONTROL
	msg.msg_control = NULL;        /* ancillary data, see below */
	msg.msg_controllen = 0;        /* ancillary data buffer len */
	msg.msg_flags = 0;             /* flags on received message */
#endif

	rc = swrap_sendmsg_before(s, si, &msg, &tmp, &un_addr, NULL, NULL, NULL);
	if (rc < 0) {
		if (rc == -ENOTSOCK) {
			return libc_readv(s, vector, count);
		}
		return -1;
	}

	ret = libc_writev(s, msg.msg_iov, msg.msg_iovlen);

	swrap_sendmsg_after(s, si, &msg, NULL, ret);

	return ret;
}

ssize_t writev(int s, const struct iovec *vector, int count)
{
	return swrap_writev(s, vector, count);
}

/****************************
 * CLOSE
 ***************************/

static int swrap_close(int fd)
{
	struct socket_info *si = NULL;
	int si_index;
	int ret;

	swrap_mutex_lock(&socket_reset_mutex);

	si_index = find_socket_info_index(fd);
	if (si_index == -1) {
		swrap_mutex_unlock(&socket_reset_mutex);
		return libc_close(fd);
	}

	SWRAP_LOG(SWRAP_LOG_TRACE, "Close wrapper for fd=%d", fd);
	reset_socket_info_index(fd);

	si = swrap_get_socket_info(si_index);

	swrap_mutex_lock(&first_free_mutex);
	SWRAP_LOCK_SI(si);

	ret = libc_close(fd);

	swrap_dec_refcount(si);

	if (swrap_get_refcount(si) > 0) {
		/* there are still references left */
		goto out;
	}

	if (si->myname.sa_socklen > 0 && si->peername.sa_socklen > 0) {
		swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_SEND, NULL, 0);
	}

	if (si->myname.sa_socklen > 0 && si->peername.sa_socklen > 0) {
		swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_RECV, NULL, 0);
		swrap_pcap_dump_packet(si, NULL, SWRAP_CLOSE_ACK, NULL, 0);
	}

	if (si->un_addr.sun_path[0] != '\0') {
		unlink(si->un_addr.sun_path);
	}

	swrap_set_next_free(si, first_free);
	first_free = si_index;

out:
	SWRAP_UNLOCK_SI(si);
	swrap_mutex_unlock(&first_free_mutex);
	swrap_mutex_unlock(&socket_reset_mutex);

	return ret;
}

int close(int fd)
{
	return swrap_close(fd);
}

/****************************
 * DUP
 ***************************/

static int swrap_dup(int fd)
{
	struct socket_info *si;
	int dup_fd, idx;

	idx = find_socket_info_index(fd);
	if (idx == -1) {
		return libc_dup(fd);
	}

	si = swrap_get_socket_info(idx);

	dup_fd = libc_dup(fd);
	if (dup_fd == -1) {
		int saved_errno = errno;
		errno = saved_errno;
		return -1;
	}

	SWRAP_LOCK_SI(si);

	swrap_inc_refcount(si);

	SWRAP_UNLOCK_SI(si);

	/* Make sure we don't have an entry for the fd */
	swrap_remove_stale(dup_fd);

	set_socket_info_index(dup_fd, idx);

	return dup_fd;
}

int dup(int fd)
{
	return swrap_dup(fd);
}

/****************************
 * DUP2
 ***************************/

static int swrap_dup2(int fd, int newfd)
{
	struct socket_info *si;
	int dup_fd, idx;

	idx = find_socket_info_index(fd);
	if (idx == -1) {
		return libc_dup2(fd, newfd);
	}

	si = swrap_get_socket_info(idx);

	if (fd == newfd) {
		/*
		 * According to the manpage:
		 *
		 * "If oldfd is a valid file descriptor, and newfd has the same
		 * value as oldfd, then dup2() does nothing, and returns newfd."
		 */
		return newfd;
	}

	if (find_socket_info(newfd)) {
		/* dup2() does an implicit close of newfd, which we
		 * need to emulate */
		swrap_close(newfd);
	}

	dup_fd = libc_dup2(fd, newfd);
	if (dup_fd == -1) {
		int saved_errno = errno;
		errno = saved_errno;
		return -1;
	}

	SWRAP_LOCK_SI(si);

	swrap_inc_refcount(si);

	SWRAP_UNLOCK_SI(si);

	/* Make sure we don't have an entry for the fd */
	swrap_remove_stale(dup_fd);

	set_socket_info_index(dup_fd, idx);

	return dup_fd;
}

int dup2(int fd, int newfd)
{
	return swrap_dup2(fd, newfd);
}

/****************************
 * FCNTL
 ***************************/

static int swrap_vfcntl(int fd, int cmd, va_list va)
{
	struct socket_info *si;
	int rc, dup_fd, idx;

	idx = find_socket_info_index(fd);
	if (idx == -1) {
		return libc_vfcntl(fd, cmd, va);
	}

	si = swrap_get_socket_info(idx);

	switch (cmd) {
	case F_DUPFD:
		dup_fd = libc_vfcntl(fd, cmd, va);
		if (dup_fd == -1) {
			int saved_errno = errno;
			errno = saved_errno;
			return -1;
		}

		SWRAP_LOCK_SI(si);

		swrap_inc_refcount(si);

		SWRAP_UNLOCK_SI(si);

		/* Make sure we don't have an entry for the fd */
		swrap_remove_stale(dup_fd);

		set_socket_info_index(dup_fd, idx);

		rc = dup_fd;
		break;
	default:
		rc = libc_vfcntl(fd, cmd, va);
		break;
	}

	return rc;
}

int fcntl(int fd, int cmd, ...)
{
	va_list va;
	int rc;

	va_start(va, cmd);

	rc = swrap_vfcntl(fd, cmd, va);

	va_end(va);

	return rc;
}

/****************************
 * EVENTFD
 ***************************/

#ifdef HAVE_EVENTFD
static int swrap_eventfd(int count, int flags)
{
	int fd;

	fd = libc_eventfd(count, flags);
	if (fd != -1) {
		swrap_remove_stale(fd);
	}

	return fd;
}

#ifdef HAVE_EVENTFD_UNSIGNED_INT
int eventfd(unsigned int count, int flags)
#else
int eventfd(int count, int flags)
#endif
{
	return swrap_eventfd(count, flags);
}
#endif

#ifdef HAVE_PLEDGE
int pledge(const char *promises, const char *paths[])
{
	(void)promises; /* unused */
	(void)paths; /* unused */

	return 0;
}
#endif /* HAVE_PLEDGE */

static void swrap_thread_prepare(void)
{
	/*
	 * This function should only be called here!!
	 *
	 * We bind all symobls to avoid deadlocks of the fork is
	 * interrupted by a signal handler using a symbol of this
	 * library.
	 */
	swrap_bind_symbol_all();

	SWRAP_LOCK_ALL;
}

static void swrap_thread_parent(void)
{
	SWRAP_UNLOCK_ALL;
}

static void swrap_thread_child(void)
{
	SWRAP_UNLOCK_ALL;
}

/****************************
 * CONSTRUCTOR
 ***************************/
void swrap_constructor(void)
{
	int ret;

	/*
	* If we hold a lock and the application forks, then the child
	* is not able to unlock the mutex and we are in a deadlock.
	* This should prevent such deadlocks.
	*/
	pthread_atfork(&swrap_thread_prepare,
		       &swrap_thread_parent,
		       &swrap_thread_child);

	ret = socket_wrapper_init_mutex(&sockets_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		exit(-1);
	}

	ret = socket_wrapper_init_mutex(&socket_reset_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		exit(-1);
	}

	ret = socket_wrapper_init_mutex(&first_free_mutex);
	if (ret != 0) {
		SWRAP_LOG(SWRAP_LOG_ERROR,
			  "Failed to initialize pthread mutex");
		exit(-1);
	}
}

/****************************
 * DESTRUCTOR
 ***************************/

/*
 * This function is called when the library is unloaded and makes sure that
 * sockets get closed and the unix file for the socket are unlinked.
 */
void swrap_destructor(void)
{
	size_t i;

	if (socket_fds_idx != NULL) {
		for (i = 0; i < socket_fds_max; ++i) {
			if (socket_fds_idx[i] != -1) {
				swrap_close(i);
			}
		}
		SAFE_FREE(socket_fds_idx);
	}

	SAFE_FREE(sockets);

	if (swrap.libc.handle != NULL) {
		dlclose(swrap.libc.handle);
	}
	if (swrap.libc.socket_handle) {
		dlclose(swrap.libc.socket_handle);
	}
}

#if defined(HAVE__SOCKET) && defined(HAVE__CLOSE)
/*
 * On FreeBSD 12 (and maybe other platforms)
 * system libraries like libresolv prefix there
 * syscalls with '_' in order to always use
 * the symbols from libc.
 *
 * In the interaction with resolv_wrapper,
 * we need to inject socket wrapper into libresolv,
 * which means we need to private all socket
 * related syscalls also with the '_' prefix.
 *
 * This is tested in Samba's 'make test',
 * there we noticed that providing '_read'
 * and '_open' would cause errors, which
 * means we skip '_read', '_write' and
 * all non socket related calls without
 * further analyzing the problem.
 */
#define SWRAP_SYMBOL_ALIAS(__sym, __aliassym) \
	extern typeof(__sym) __aliassym __attribute__ ((alias(#__sym)))

#ifdef HAVE_ACCEPT4
SWRAP_SYMBOL_ALIAS(accept4, _accept4);
#endif
SWRAP_SYMBOL_ALIAS(accept, _accept);
SWRAP_SYMBOL_ALIAS(bind, _bind);
SWRAP_SYMBOL_ALIAS(close, _close);
SWRAP_SYMBOL_ALIAS(connect, _connect);
SWRAP_SYMBOL_ALIAS(dup, _dup);
SWRAP_SYMBOL_ALIAS(dup2, _dup2);
SWRAP_SYMBOL_ALIAS(fcntl, _fcntl);
SWRAP_SYMBOL_ALIAS(getpeername, _getpeername);
SWRAP_SYMBOL_ALIAS(getsockname, _getsockname);
SWRAP_SYMBOL_ALIAS(getsockopt, _getsockopt);
SWRAP_SYMBOL_ALIAS(ioctl, _ioctl);
SWRAP_SYMBOL_ALIAS(listen, _listen);
SWRAP_SYMBOL_ALIAS(readv, _readv);
SWRAP_SYMBOL_ALIAS(recv, _recv);
SWRAP_SYMBOL_ALIAS(recvfrom, _recvfrom);
SWRAP_SYMBOL_ALIAS(recvmsg, _recvmsg);
SWRAP_SYMBOL_ALIAS(send, _send);
SWRAP_SYMBOL_ALIAS(sendmsg, _sendmsg);
SWRAP_SYMBOL_ALIAS(sendto, _sendto);
SWRAP_SYMBOL_ALIAS(setsockopt, _setsockopt);
SWRAP_SYMBOL_ALIAS(socket, _socket);
SWRAP_SYMBOL_ALIAS(socketpair, _socketpair);
SWRAP_SYMBOL_ALIAS(writev, _writev);

#endif /* SOCKET_WRAPPER_EXPORT_UNDERSCORE_SYMBOLS */