/*
 * $Id: mrt.h,v 1.5 1999/10/17 05:22:17 labovit Exp $
 */

#ifndef _MRT_H
#define _MRT_H

#include <version.h>
#include <config.h>

#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
#  include <sys/time.h>
# else
#  include <time.h>
# endif
#endif
#include <sys/param.h>
#include <sys/socket.h>
#include <assert.h>
#include <unistd.h>

#include <netinet/in.h>

#ifndef HAVE_PTHREAD_H
#include <pthread_fake.h>
#else
#include <pthread.h>
#endif /* HAVE_PTHREAD_H */

typedef void (*void_fn_t)();
typedef int (*int_fn_t)();
typedef void *(*thread_fn_t)(void *);

#include <New.h>
#include <linked_list.h>
#include <defs.h>
#include <object.h>
#include <trace.h>
#include <schedule.h>
#include <proto.h>
#include <select.h>

#ifdef notdef
extern int IPV4;
#ifdef HAVE_IPV6
extern int IPV6;
#endif /* IPV6 */
#endif

#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN   16
#endif /* INET_ADDRSTRLEN */

#ifndef HAVE_IPV6
#ifndef AF_INET6
#define AF_INET6 24 /* XXX - may conflict with other value */
#endif
/*struct in6_addr {
  u_char s6_addr[16];
}; */   /* is this really need ??? - Crasig */
#endif /* HAVE_IPV6 */

typedef struct _prefix_t {
    u_short family;		/* AF_INET | AF_INET6 */
    u_short bitlen;		/* same as mask? */
    int ref_count;		/* reference count */
    pthread_mutex_t mutex_lock; /* lock down structure */
    union {
	struct in_addr sin;
#ifdef HAVE_IPV6
	struct in6_addr sin6;
#endif /* IPV6 */
    } add;
} prefix_t;

typedef struct _prefix4_t {
    u_short family;		/* AF_INET | AF_INET6 */
    u_short bitlen;		/* same as mask? */
    int ref_count;		/* reference count */
    pthread_mutex_t mutex_lock; /* lock down structure */
    struct in_addr sin;
} prefix4_t;

#ifdef HAVE_IPV6
typedef struct _prefix6_t {
    u_short family;		/* AF_INET | AF_INET6 */
    u_short bitlen;		/* same as mask? */
    int ref_count;		/* reference count */
    pthread_mutex_t mutex_lock; /* lock down structure */
    struct in6_addr sin6;
} prefix6_t;
#endif /* IPV6 */

#include <alist.h>

typedef struct _Route {
    prefix_t *prefix;
    void *attr;			/* attribure strcutre like bgp_attr_t */
} Route;


enum ROUTE_ATTR_TYPES {
    ROUTE_ATTR_BGP4,
    ROUTE_ATTR_RIP,
    ROUTE_ATTR_IDRP
};


typedef struct _buffer_t {
    int type; /* may not be used by all */
    int len;
    u_char *data;
} buffer_t;


typedef struct _gateway_t {
    prefix_t *prefix;
    struct _interface_t *interface;
/* the following two are protocol (BGP) dependent ? */
    int AS;
    u_long routerid;
/* the following two are for shared nexthop structure */
    int ref_count;		/* reference count */
    pthread_mutex_t mutex_lock; /* lock down structure */
} gateway_t;

/* they share the same hash table */
typedef gateway_t nexthop_t;


/* this should match with other attributes */
typedef struct _generic_attr_t {
    u_char type;		/* RIP, BGP, OSPF */
    u_int ref_count;
    pthread_mutex_t mutex_lock; /* lock down structure */
    /* here is 3 bytes space */
    nexthop_t *nexthop;
    gateway_t *gateway;		/* gateway we learned route from */
    u_long tag;
} generic_attr_t;


extern int VERBOSE_ERROR_FLAG;	/* yuck, delete this */


#include <hash.h>

typedef struct _mrt_hash_table_t {
    HASH_TABLE *table;
    pthread_mutex_t mutex_lock;
} mrt_hash_table_t;


#ifdef notdef
typedef struct _nexthop_t {
    prefix_t *prefix;
    int ref_count;		/* reference count */
    pthread_mutex_t mutex_lock; /* lock down structure */
} nexthop_t;
#endif


typedef void (*proto_update_route_t) (prefix_t *prefix, generic_attr_t *new,
                         generic_attr_t *old, int pref);
typedef void (*rib_update_route_t) (prefix_t *prefix, generic_attr_t *new,
                         generic_attr_t *old, int pref, u_long flags);
typedef prefix_t *(*rib_find_best_route_t) (prefix_t *prefix);
typedef void (*proto_redistribute_request_t) (int from, int to, int on);


/* Main MRT structure
 * holds bookkeeping information on gateways, threads, signals, etc
 * ALL MRT programs depend on this structure
 */
typedef struct _mrt_t {
    pthread_mutex_t mutex_lock;		/* lock down structure */
    trace_t *trace;			/* default trace - go away future? */
    LINKED_LIST *ll_threads;		/* list of all thread_t */
    LINKED_LIST *ll_signal_call_fn;	/* list of mrt_signal_t */
    LINKED_LIST *ll_gateways;		/* list of gateway_t for Solaris */
    LINKED_LIST *ll_trace;		/* list of trace_t */
    char *config_file_name;
    long start_time;			/* uptime of system (debugging) */
    /* for use on non-thread systems -- current thread # */
    int threadn;
    u_long protocols;			/* protocols enabled */
    /* u_long redist[PROTO_MAX + 1]; */	/* protocols redistribute */
    proto_update_route_t proto_update_route[PROTO_MAX + 1];
    proto_update_route_t kernel_update_route;
    rib_update_route_t rib_update_route;
    rib_find_best_route_t rib_find_best_route;
    int (*rib_redistribute_request)();
    int (*rib_redistribute_network)();
    /* for rebooting - save cwd, and arguments */
    char	*cwd;
    char        **argv;
    int    	argc;
    int		daemon_mode;
    mrt_hash_table_t hash_table;
#ifdef HAVE_IPV6
    mrt_hash_table_t hash_table6;
#endif /* HAVE_IPV6 */
    int		force_exit_flag;
    int		kernel_install_flag4;
    int		kernel_install_flag6;
} mrt_t;


typedef struct _redistribute_t {
    int type;
    proto_update_route_t fn;
} redistribute_t;


typedef struct _ll_value_t {
    int value;
    LL_POINTERS ptrs;
} ll_value_t;


extern mrt_t *MRT;
extern int IPV4;
extern int IPV6;

/* Main thread gets all signals. Threads can request to have call_fn
 * executed upon receipt of a signal
 */
typedef struct _mrt_signal_t {
    int signal;
    void_fn_t call_fn;
/*    mrt_call_fn_t call_fn; */
} mrt_signal_t;

typedef struct _mrt_thread_t {
    char *name;
    pthread_t thread;
    pthread_attr_t attr;
    schedule_t *schedule; /* schedule sttached to the thread */
} mrt_thread_t;


#ifdef HAVE_PTHREADLIB

#define THREAD_SPECIFIC_DATA(type, data, size) \
    do { \
        static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; \
        static pthread_key_t key = -1; \
        \
        if (key < 0) { \
	    pthread_mutex_lock (&mutex); \
	    if (key < 0) { \
	        if (pthread_key_create(&key, free) < 0) { \
		    pthread_mutex_unlock(&mutex); \
		    /* XXX should we report an error? */ \
		    data = (type *) NULL; \
		    break; \
	        } \
	    } \
	    pthread_mutex_unlock (&mutex); \
        } \
        if ((data = (type *) pthread_getspecific (key)) == NULL) { \
	    if ((data = (type *) malloc (size)) == NULL) { \
	        /* XXX should we report an error? */ \
	        break; \
	    } \
        } \
    } while (0)
#else
#define THREAD_SPECIFIC_DATA(type, data, size) \
    do { \
        static type buff[size]; \
        data = buff; \
    } while (0)
#endif /* HAVE_PTHREADLIB */

#define THREAD_SPECIFIC_STRAGE_LEN 1024
#define THREAD_SPECIFIC_STRAGE(data) \
    do { \
	/* sigset_t sigset; */ \
        struct buffer { \
            char buffs[16][THREAD_SPECIFIC_STRAGE_LEN]; \
            int i; \
        } *buffp; \
	\
	THREAD_SPECIFIC_DATA (struct buffer, buffp, 1); \
	if (buffp) { \
	    /* In theory, we need to disable alarm and interupts here \
	       to keep this function re-entrant */ \
	    /* alarm interrupt no longer used */ \
	    /* sigset = block_signal (SIGALRM); */ \
	    data = buffp->buffs[buffp->i++]; \
	    buffp->i &= 0x0f; \
	    /* recover_signal (sigset); */ \
	} \
	else { \
	    data = NULL; \
	} \
    } while (0) \

#define ASSERT(x) {if (!x) err_dump ("\nAssert failed line %d in %s", __LINE__, __FILE__);}

#define UTIL_GET_BYTE(val, cp)   ((val) = *(cp)++)

#define UTIL_GET_SHORT(val, cp) \
        { \
            register u_char *val_p; \
	    val_p = (u_char *) &(val); \
	    *val_p++ = *(cp)++; \
	    *val_p++ = *(cp)++; \
        }

#define UTIL_GET_NETSHORT(val, cp) \
	{ \
            register u_char *val_p; \
            val_p = (u_char *) &(val); \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
	    (val) = ntohs(val); \
	}

#define UTIL_GET_LONG(val, cp) \
        { \
            register u_char *val_p; \
            val_p = (u_char *) &(val); \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
        }

/* This version of UTIL_GET_NETLONG uses ntohl for cross-platform
 * compatibility, which is A Good Thing (tm) */
#define UTIL_GET_NETLONG(val, cp) \
        { \
            register u_char *val_p; \
            val_p = (u_char *) &(val); \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
            *val_p++ = *(cp)++; \
            (val) = ntohl(val); \
        }

#define UTIL_GET_BITCOUNT(bitcount, cp)  ((bitcount) = *(cp)++)

#define UTIL_PUT_BYTE(val, cp)   (*(cp)++ = (byte)(val))

#define UTIL_PUT_SHORT(val, cp) \
        { \
            u_short tmp = (val); \
	    register u_char *tmp_p = (u_char *) &tmp; \
	    *(cp)++ = *tmp_p++; \
	    *(cp)++ = *tmp_p++; \
        }

/* Network version of UTIL_PUT_SHORT, using htons for cross-platform
 * compatibility */
#define UTIL_PUT_NETSHORT(val, cp) \
	{ \
	    u_short tmp; \
            register u_char *val_p; \
	    tmp = htons(val); \
	    val_p = (u_char *) &tmp; \
            *(cp)++ = *val_p++; \
            *(cp)++ = *val_p++; \
	}


#define UTIL_PUT_LONG(val, cp) \
        { \
            u_long tmp = (val); \
	    register u_char *tmp_p = (u_char *) &tmp; \
            *(cp)++ = *tmp_p++; \
            *(cp)++ = *tmp_p++; \
            *(cp)++ = *tmp_p++; \
            *(cp)++ = *tmp_p++; \
        }

/* Network version of UTIL_PUT_LONG which uses htonl to maintain
 * cross-platform byte-orderings across the network */
#define UTIL_PUT_NETLONG(val, cp) \
        { \
            u_long tmp; \
            register u_char *val_p; \
            tmp = htonl(val); \
            val_p = (u_char *) &tmp; \
            *(cp)++ = *val_p++; \
            *(cp)++ = *val_p++; \
            *(cp)++ = *val_p++; \
            *(cp)++ = *val_p++; \
        }

#include <user.h>
/*#include <filter.h>*/

/* public functions */

prefix_t *New_Prefix (int family, void * dest, int bitlen);
prefix_t *Change_Prefix (int family, void * dest, int bitlen, prefix_t * prefix);
prefix_t *Ref_Prefix (prefix_t * prefix);
void Deref_Prefix (prefix_t * prefix);
void Delete_Prefix (prefix_t * prefix);
int prefix_check_prefix_in_list (LINKED_LIST * ll_prefix, prefix_t * prefix);
void print_prefix_list (LINKED_LIST * ll_prefixes);
void print_prefix (prefix_t * p_prefix);
prefix_t *copy_prefix (prefix_t * prefix);
void print_pref_prefix_list (LINKED_LIST * ll_prefixes, u_short *pref);

struct sockaddr *prefix_tosockaddr(prefix_t *);
prefix_t *name_toprefix(char *, trace_t *);
prefix_t *string_toprefix(char *, trace_t *);
char *prefix_toname(prefix_t *prefix);

#define prefix_tolong(prefix) (assert ((prefix)->family == AF_INET),\
			       (prefix)->add.sin.s_addr)
#define prefix_tochar(prefix) ((char *)&(prefix)->add.sin)
#define prefix_touchar(prefix) ((u_char *)&(prefix)->add.sin)
#define prefix_toaddr(prefix) (&(prefix)->add.sin)
#define prefix_getfamily(prefix) ((prefix)->family)
#define prefix_getlen(prefix) (((prefix)->bitlen)/8)
#ifdef HAVE_IPV6
#define prefix_toaddr6(prefix) (assert ((prefix)->family == AF_INET6),\
				&(prefix)->add.sin6)
#endif /* IPV6 */

#ifdef notdef
u_char *prefix_tochar (prefix_t * prefix);
#endif
int prefix_compare (prefix_t * p1, prefix_t * p2);
int prefix_compare2 (prefix_t * p1, prefix_t * p2);
int a_include_b (prefix_t * a, prefix_t * b);
char *prefix_toa (prefix_t * prefix);
char *prefix_toa2 (prefix_t * prefix, char *tmp);
char *prefix_toax (prefix_t * prefix);
char *prefix_toa2x (prefix_t * prefix, char *tmp, int with_len);
prefix_t *ascii2prefix (int family, char *string);
int my_inet_pton (int af, const char *src, void *dst);
/*int my_inet_pton6(int family, const char *string, struct in6_addr *sin6);*/

char *get_netname (int dest, int bitlen);
int munge_route_string ();
int _atoi ();
char *my_strftime (long t, char *fmt);

gateway_t *add_gateway (prefix_t * prefix, int AS,
	    /* resolve cross reference ... */ struct _interface_t *interface);
/* gateway_t *find_gateway (prefix_t * prefix, int AS); */
char *gateway_toa (char *tmp, gateway_t * gateway);
char *gateway_toa2 (gateway_t * gateway);
/* void destroy_gateway (gateway_t * gateway); */

/*nexthop_t * add_nexthop (prefix_t *prefix, interface_t *interface);
void deref_nexthop (nexthop_t *nexthop);
nexthop_t * ref_nexthop (nexthop_t *nexthop);*/
gateway_t * find_gateway (prefix_t *prefix);


int init_mrt ();
mrt_thread_t *mrt_thread_create (char *name, schedule_t * schedule,
				 thread_fn_t callfn, void *arg);
mrt_thread_t *mrt_thread_create2 (char *name, schedule_t * schedule,
				 thread_fn_t callfn, void *arg);
/*int is_ipv4_prefix (char *string);*/

#ifdef HAVE_IPV6
int is_ipv6_prefix (char *string);
int ipv6_multicast_addr (struct in6_addr *sin6);
int ipv6_link_local_addr (struct in6_addr *sin6);
int ipv6_ipv4_addr (struct in6_addr *sin6);
int ipv6_compat_addr (struct in6_addr *sin6);
int ipv6_any_addr (struct in6_addr *sin6);
#endif /* HAVE_IPV6 */
u_char *netmasking (int family, void *addr, u_int bitlen);
int comp_with_mask (void *addr, void *dest, u_int mask);
int byte_compare (void *addr, void *dest, int bits, void *wildcard);

#include <arpa/inet.h>
#ifndef HAVE_INET_NTOP
const char *inet_ntop (int af, const void *src, char *dst, size_t size);
int inet_pton (int af, const char *src, void *dst);
#endif /* HAVE_INET_NTOP */
#ifndef HAVE_MEMMOVE
/*char *memmove (void *dest, const void *src, size_t n);*/
char *memmove (char *dest, const char *src, size_t n);
#endif /* HAVE_MEMMOVE */

int atox (char *str);
char *r_inet_ntoa (char *buf, int n, u_char *l, int len);
char *family2string (u_int family);
int is_any_addr (prefix_t *prefix);
int prefix_is_unspecified (prefix_t *prefix);
int prefix_is_loopback (prefix_t *prefix);
#ifdef HAVE_IPV6
int prefix_is_linklocal (prefix_t *prefix);
#endif /* IPV6 */

int nonblock_connect (trace_t *default_trace, prefix_t *prefix, int port, int sockfd);
void mrt_reboot ();
int init_mrt_reboot (int argc, char *argv[]);
void mrt_main_loop ();
void mrt_busy_loop (int *force_exit_flag, int ok);
void mrt_thread_exit ();
void init_mrt_thread_signals ();
void mrt_exit (int status);
void mrt_process_signal (int sig);

buffer_t *New_Buffer (int len);
void Delete_Buffer (buffer_t *buffer);

#define LL_Add2(ll, a) LL_Add (((ll)? (ll): ((ll) = LL_Create (0))), (a))
extern int BGPSIM_TRANSPARENT;
#endif /* _MRT_H */
