1 /*
2  *  lft_lib.h
3  *  Layer Four Traceroute
4  *
5  *  This file is part of LFT.
6  *
7  *  The LFT software provided in this Distribution is
8  *  Copyright 2007 VOSTROM Holdings, Inc.
9  *
10  *  The full text of our legal notices is contained in the file called
11  *  COPYING, included with this Distribution.
12  *
13  */
14 #ifndef LFT_LIB_H
15 #define LFT_LIB_H
16 
17 #include "lft_types.h"
18 
19 /* not available in earlier darwin systems */
20 #ifndef AI_NUMERICSERV
21 #define AI_NUMERICSERV 0
22 #endif
23 
24 /* As the trace progresses, each hope will attempt
25 to work through the states one by one until it
26 receives an answer (2 attempts per state).
27 Whatever state "works" - will be then set up on
28 following hops to continue from.
29 */
30 #define HS_SEND_FIN         0x00
31 #define HS_SEND_SYN         0x01
32 #define HS_SEND_SYN_FIN     0x02
33 #define HS_SEND_RST         0x04
34 #define HS_SEND_SYN_ACK     0x12
35 #define HS_SEND_ACK         0x16
36 #define HS_MAX              (HS_SEND_SYN)
37 
38 #define HF_ENDPOINT         0x01
39 
40 /* default timeout value */
41 #define DEFAULT_TIMEOUT_MS  250
42 
43 /* Common EtherType values */
44 #ifndef ETHERTYPE_IP
45 #define	ETHERTYPE_IP		0x0800	/* IP protocol */
46 #endif
47 #ifndef ETHERTYPE_ARP
48 #define	ETHERTYPE_ARP		0x0806	/* Addr. resolution protocol */
49 #endif
50 #ifndef ETHERTYPE_REVARP
51 #define	ETHERTYPE_REVARP	0x8035	/* reverse Addr. resolution protocol */
52 #endif
53 #ifndef ETHERTYPE_VLAN
54 #define	ETHERTYPE_VLAN		0x8100	/* IEEE 802.1Q VLAN tagging */
55 #endif
56 #ifndef ETHERTYPE_IPV6
57 #define	ETHERTYPE_IPV6		0x86dd	/* IPv6 */
58 #endif
59 
60 /* Sometimes-missing BPF values */
61 #ifndef DLT_RAW
62 #define DLT_RAW         101     /* Raw IP */
63 #endif
64 #ifndef DLT_PPP_SERIAL
65 #define DLT_PPP_SERIAL  50      /* PPP with HDLC encapsulation */
66 #endif
67 #ifndef DLT_PPP_ETHER
68 #define DLT_PPP_ETHER   51      /* PPP over Ethernet */
69 #endif
70 #ifndef DLT_LINUX_SLL
71 #define DLT_LINUX_SLL   113     /* Linux cooked capture */
72 #endif
73 #ifndef DLT_PPP
74 #define DLT_PPP         9       /* PPP over Ethernet */
75 #endif
76 
77 
78 /* ToS (type of service) bits we can set on the IP datagram */
79 
80 #define TOSMINDELAY         0x10
81 #define TOSMAXTHROUGH       0x08
82 #define TOSMAXRELIABLE      0x04
83 #define TOSMINCOST          0x02
84 
85 /*Errors and warnings codes*/
86 #define WRN_CANT_SETUP_FIN              -1
87 #define WRN_CANT_DISP_HOST_NAMES        -2
88 #define WRN_ADAPTIVE_DISABLED_BY_UDP    -3
89 #define WRN_FIN_DISABLED_BY_UDP         -4
90 #define WRN_ONLY_ONE_ASN_LOOKUP         -5
91 #define WRN_UDP_PORT_TOO_HIGH           -6
92 #define WRN_PACKET_LENGTH_TOO_HIGH      -7
93 #define WRN_PACKET_LENGTH_TOO_LOW       -8
94 #define WRN_CANT_DISABLE_RESOLVER       -9
95 #define WRN_ALREADY_RANDOM_SPORT        -10
96 #define WRN_ADAPTIVE_DISABLED_BY_FIN    -12
97 #define ERR_DEVNAME_TOO_LONG            -13
98 #define WRN_UNABLE_SETUP_UTC            -14
99 
100 #define WRN_GETIFFORREMOTE_SOCKET       -15
101 #define WRN_GETIFFORREMOTE_CONNECT      -16
102 #define WRN_GETIFFORREMOTE_SOCKNAME     -17
103 #define ERR_UNKNOWN_HOST                -18
104 #define ERR_RAW_SOCKET                  -19
105 #define ERR_SOCKET_BIND                 -20
106 #define WRN_WSAIOCTL                    -21
107 #define ERR_IP_HDRINCL                  -22
108 #define ERR_NOT_ENOUGH_MEM              -23
109 #define ERR_RAW_TCP_DISABLED            -24
110 
111 typedef struct _badhopstateparam
112 {
113     const struct hop_info_s *h;
114     short nhop;
115 }WrnBadHopStateParam;
116 #define WRN_BAD_HOP_STATE               -25
117 #define WRN_NS_LOOKUP_FAILED            -26
118 #define ERR_WIN_SELECT                  -27
119 #define ERR_WIN_RECV                    -28
120 #define ERR_WIN_WSASTARTUP              -29
121 #define ERR_PCAP_ERROR                  -30
122 #define ERR_DISCOVER_INTERFACE          -31
123 #define ERR_UNKNOWN_INTERFACE           -32
124 #define ERR_UNKNOWN_SEND_INTERFACE      -32
125 #define ERR_PCAP_DEV_UNAVAILABLE        -33
126 #define WRN_BIOCIMMEDIATE               -34
127 #define ERR_PCAP_NONBLOCK_ERROR         -35
128 /*Events codes and their params structures*/
129 #define EVT_AUTOCONFIGURED_TO_PORTS     1
130 #define EVT_ADDRESS_INITIALIZED         2
131 typedef struct _sentpacketparams
132 {
133     short nhop;
134     unsigned int tseq;
135     unsigned char flags;
136     unsigned short tttl;
137 }EvtSentPacketParam;
138 #define EVT_SENT_PACKET                 3
139 #define EVT_SHOW_PAYLOAD                4
140 #define EVT_SHOW_UDP_CHECKSUM           5
141 #define EVT_SHOW_TCP_CHECKSUM           6
142 #define EVT_SHOW_HOPS                   7
143 #define EVT_SHOW_NUM_HOPS               8
144 #define EVT_TRACE_COMPLETED             9
145 #define EVT_ON_RESOLUTION               10
146 #define EVT_TRACE_REPORT_START          11
147 typedef struct _rptnoreplyparams
148 {
149     int hopno;
150     int noreply;
151 }EvtNoReplyParam;
152 #define EVT_RPT_NO_REPLY                12
153 #define EVT_RPT_FRW_INSPECT_PACKS       13
154 #define EVT_RPT_FRW_STATE_FILTER        14
155 #define EVT_RPT_BSD_BUG                 15
156 #define EVT_RPT_HOP_INFO_START          16
157 typedef struct _packetinfoevtparam
158 {
159     int asnumber;
160     const char * netname;
161     struct in_addr last_hop;
162 	int is_asseam;
163 	int is_netseam;
164 	int seam_traced;
165 	int is_open;
166 	int is_filtered;
167     const struct trace_packet_info_s * tp;
168 }EvtPacketInfoParam;
169 #define EVT_RPT_PACKET_INFO             17
170 #define EVT_RPT_PACKET_LIST_END         18
171 #define EVT_RPT_NO_HOPS                 19
172 #define EVT_RPT_TIME_TRACE              20
173 #define EVT_ON_EXIT                     21
174 #define EVT_TTL_NO_REPLY                22
175 #define EVT_PROGRESS_NO_REPLY           23
176 #define EVT_TTL_TOUT_RESEND             24
177 #define EVT_TTL_TOUT_GIVINGUP           25
178 typedef struct _debugchkpoint1
179 {
180     int last_return;
181     int no_reply;
182     int need_reply;
183 }EvtDebugCheckpoint1Param;
184 #define EVT_DBG_CHECKPOINT1             26
185 #define EVT_CANT_RELIABLY_RTRIP         27
186 #define EVT_HAVE_UNANSWERRED_HOPS       28
187 #define EVT_TOO_FAR_AHEAD               29
188 #define EVT_HAVE_GAPS                   30
189 #define EVT_EITHER_RESP_OR_TOUT         31
190 #define EVT_LOOKFOR_UNINC_ACK           32
191 #define EVT_LOOKFOR_OFF_BY_LEN          33
192 #define EVT_LOOKFOR_LAST_RESORT         34
193 #define EVT_SKIP_PACKET                 35
194 typedef struct _nonseqpack
195 {
196     struct in_addr ipaddr;
197     const struct trace_packet_info_s * tp;
198 }EvtNonSeqPacketParam;
199 #define EVT_ACK_WAS_NOT_INC             36
200 #define EVT_RST_REL_TO_ISN              37
201 #define EVT_ACK_WAS_WAY_OFF             38
202 #define EVT_DUPLICATE_PACKET            39
203 #define EVT_PROGRESS_DUPLICATE          40
204 typedef struct _recvpacket
205 {
206     struct in_addr ipaddr;
207 	struct trace_packet_info_s * tp;
208     unsigned int seq;
209 }EvtRecvPacketParam;
210 #define EVT_RECV_PACKET                 41
211 #define EVT_PROGRESS_OK                 42
212 #define EVT_TCP_PORT_CLOSED             43
213 #define EVT_TCP_PORT_OPEN               44
214 #define EVT_PROCESS_PACKET_START        45
215 #define EVT_UDP_NOT_FOR_US              46
216 typedef struct _incomudpicmp
217 {
218     const struct ip * ip;
219     const struct ip * orig_ip;
220     const struct udphdr *udp;
221     const struct icmp *icmp;
222 }EvtIncomingICMPUDPParam;
223 #define EVT_INCOMING_ICMP_UDP           47
224 #define EVT_RCVD_ICMP_UDP               48
225 typedef struct _incomtcpicmp
226 {
227     const struct ip * ip;
228     const struct ip * orig_ip;
229     const struct tcphdr *tcp;
230     const struct icmp *icmp;
231 }EvtIncomingICMPTCPParam;
232 #define EVT_INCOMING_ICMP_TCP           49
233 #define EVT_RCVD_ICMP_TCP               50
234 #define EVT_RCVD_TCP                    51
235 #define EVT_RCVD_UNKNOWN                52
236 #define EVT_DEVICE_SELECTED             53
237 #define EVT_SHOW_INITIAL_SEQNUM         54
238 #define EVT_TRACE_START                 55
239 #define EVT_DBG_CHECKPOINT2             56
240 
241 #define EVT_DBG_LOG_MESSAGE             57
242 
243 #define EVT_PROGRESS_SKIP_PACKET	58
244 
245 #define EVT_OPEN_CHECK_RESULT		59
246 
247 #define ERR_BTCP_PROBE_PORT_IS_BUSY	60
248 #define ERR_BTCP_WRONG_PORT_VALUE	61
249 
250 #define EVT_OCHECK_START		62
251 #define WRN_OCHECK_OPEN_SOCK		63
252 #define WRN_OCHECK_IOCTL		64
253 #define WRN_OCHECK_SELECT		65
254 #define WRN_OCHECK_GETERROR		66
255 #define WRN_OCHECK_SOCKERROR		67
256 #define WRN_OCHECK_TIMEOUT		68
257 #define EVT_OCHECK_OPEN			69
258 #define WRN_OCHECK_FCNTLGET		70
259 #define WRN_OCHECK_FCNTLSET		71
260 #define WRN_OCHECK_CONNECTERR		72
261 
262 typedef struct _incomechoreplyicmp
263 {
264     const struct ip * ip;
265     const struct icmp_echo_header_s * echo;
266 }EvtIncomingICMPEchoParam;
267 #define EVT_INCOMING_ICMP_Echo		73
268 #define EVT_RCVD_ICMP_Echo		74
269 
270 typedef struct _incomicmpicmp
271 {
272     const struct ip * ip;
273 	const struct icmp * icmp;
274 	const struct ip * orig_ip;
275     const struct icmp_echo_header_s * echo;
276 }EvtIncomingICMPICMPParam;
277 #define EVT_INCOMING_ICMP_ICMP		75
278 #define EVT_RCVD_ICMP_ICMP		76
279 
280 #if defined(BSD_IP_STACK) && !defined(OPENBSD) && !defined(__FreeBSD__)
281 #define SCREWED_IP_LEN
282 #endif
283 
284 typedef struct btcpmapentry
285 {
286 	int nhop;
287 	int port;
288 	int sentcount;
289 }BasicTCPMapEntry;
290 #ifdef	__cplusplus
291 extern "C" {
292 #endif
293 typedef struct _btcp_debug_info
294 {
295 	int type;
296 	int hop;
297 	int phop;
298 	int port;
299 	struct in_addr ip;
300 }btcp_debug_info;
301 /* Session parameters */
302 typedef struct _lft_session_params
303 {
304     struct timeval ts_last_sent;
305     struct timeval now;
306     double scatter_ms;                      /* milleseconds between sends */
307     int ttl_min;                            /* user may request to start at a higher TTL */
308     int hop_info_length;
309 
310     unsigned short ip_id;                   /*not used*/
311     unsigned char tcp_flags;
312 
313     int use_fins;
314 
315     int seq_start;       /* generate ISN internally by default */
316     int dport;           /* set default destination to tcp/80 HTTP */
317     int sport;           /* set default source to tcp/53 dns-xfer */
318     int auto_ports;      /* enable port autoselection by default */
319     int random_source;   /* disable random source port by default */
320     int set_tos;         /* disable set ToS bit by default */
321     int userlen;         /* user-requested packet length */
322     int payloadlen;      /* the final probe payloadlength */
323     int win_len;
324 
325     int timeout_ms;      /* timeout between retries */
326     int retry_max;       /* number of retries before giving up */
327     int retry_min;       /* minimum number of checks per hop */
328     int ahead_limit;     /* number of probes we can send
329                           * without replies if we don't know
330                           * the number of hops */
331     int dflag;
332 
333     int ttl_limit;       /* max # hops to traverse (highest TTL) */
334     int break_on_icmp;	 /* break on icmp other than time exceeded */
335     int noisy;           /* disable verbose debug by default */
336     int nostatus;        /* print status bar by default */
337     int userdevsel;      /* by default, we'll select the device */
338     int senddevsel;      /* by default, we'll select the device */
339     int resolve_names;   /* dns resolution enabled by default */
340     int hostnames_only;	 /* disable printing of IP addresses */
341     int timetrace;       /* disable tracer timing by default */
342     int adaptive;		 /* disable state engine by default */
343 	int protocol;		 /* 0 - TCP, 1 - UDP, 2 - ICMP base, 3 - ICMP RFC 1393, 4 - TCP basic */
344     int do_netlookup;    /* disable netname lookup by default */
345     int do_aslookup;     /* disable asn lookup by default */
346     int use_radb;        /* use RADB instead of pwhois */
347     int use_cymru;       /* use Cymru instead of pwhois */
348     int use_ris;         /* use RIPE NCC RIS instead of pwhois */
349 
350     char *payload;
351 
352     int send_sock;
353     int skip_header_len;
354 
355 #if defined( __CYGWIN__ ) || defined( WIN32 ) || defined(_WIN32)
356     int recv_sock;
357     int wsastarted;
358 #else
359     pcap_t * pcapdescr;
360 #endif
361     int UseLocalTime;
362 
363     int num_hops;
364     /*int num_sent;*/
365     int num_rcvd;
366     int target_open;
367 	int target_filtered;
368     int target_anomaly;
369 
370     char *hostname;
371     char *hostname_lsrr[9];
372     int hostname_lsrr_size;
373 
374     struct in_addr local_address;
375     struct in_addr remote_address;
376 
377     struct timeval begin_time, trace_done_time;
378 
379     /* The actual packet data (one of..)*/
380     struct trace_packet_s trace_packet;
381 	struct icmp_trace_packet_s icmp_packet;
382 
383     /* Packet container with additional info */
384     /* struct trace_packet_info_s * trace_packet_info;*/		/* indexed by dport - dport NOT USED*/
385 
386     /* list of packet containers */
387     SLIST_HEAD(packets_s, trace_packet_info_s) trace_packets;
388     int trace_packets_num;
389 
390 	/* Map of ports for basic TCP trace */
391 	BasicTCPMapEntry * btcpmap;
392 	int latestmapchoice;
393 	int btcpmapsize;
394 	int btcpdpucnt;
395 	int trg_probe_is_sent;
396 	/* btcp_debug_info debugmap[1000]; */
397 	/* int debugmapidx; */
398 
399     /* hop information, by ttl */
400     struct hop_info_s * hop_info;
401     const char * pcap_dev;
402     /* data link type as in pcap_datalink() */
403     int pcap_datalink;
404     const char * pcap_send_dev;
405     const char * userdev;
406     const char * senddev;
407     /*WHOIS parameters*/
408     whois_session_params * wsess;
409     /*User's data*/
410     void * UsersDataCookie;
411 
412 	/* GraphViz subquery. Disables any output. */
413 	int is_graphviz_subquery;
414 	int check_seam;
415 	char * graphviz_icon_path;
416     /*Exit status. When this field has value <0 lft will end work as soon as possible*/
417     int exit_state;
418 }lft_session_params;
419 
420 extern const char * icmp_messages[];
421 extern const char *version;
422 extern const char *appname;
423 extern const int maxpacklen;
424 /*--------------------------- Callbacks definition ---------------------------*/
425 /*
426 Paramaters:
427     lft_session_params * sess - session handle,
428     int code - code of error or event,
429     const void * param - additional parameters, depend on code
430 */
431 typedef void (*LFT_CALLBACK)(lft_session_params *, int, const void *);
432 /*----------------------------------------------------------------------------*/
433 void LFTInitializeCallbacks(LFT_CALLBACK error_handler, LFT_CALLBACK event_handler);
434 lft_session_params * LFTSessionOpen(void);
435 void LFTSessionClose(lft_session_params * sess);
436 double timediff_ms (struct timeval prior, struct timeval latter);
437 unsigned int get_address(lft_session_params * sess, const char *host);
438 #ifndef SCREWED_IP_LEN
439 u_int32_t ip_cksum (const struct ip *ip);
440 #endif
441 u_int32_t tcp_cksum (struct ip *ip, struct tcphdr *tcp, const char * payload, int payload_len);
442 int hop_state_up (lft_session_params * sess, short nhop);
443 int hop_state_copy(lft_session_params * sess, short nhop);
444 unsigned int new_seq(lft_session_params * sess);
445 /*----------------------------------------------------------------------------*/
446 /*                          Safe setting of parameters                        */
447 /*----------------------------------------------------------------------------*/
448 /*Use TCP FIN packets exclusively (defaults are SYN)*/
449 int LFTSetupFIN(lft_session_params * sess);
450 /*Display hosts symbolically; suppress IP address display*/
451 int LFTSetupDispSymbHost(lft_session_params * sess);
452 /*Use traditional UDP (probes) for tracing instead of TCP*/
453 int LFTSetupUDPMode(lft_session_params * sess);
454 #define ASN_LOOKUP_RIS      0
455 #define ASN_LOOKUP_RADB     1
456 #define ASN_LOOKUP_CYMRU    2
457 /*Use RIPE NCC's RIS to resolve ASNs instead of Prefix WhoIs*/
458 int LFTSetupRISLookup(lft_session_params * sess);
459 /*Use the RADB to resolve ASNs instead of Prefix WhoIs*/
460 int LFTSetupRADBLookup(lft_session_params * sess);
461 /*Use Cymru to resolve ASNs instead of Prefix WhoIs*/
462 int LFTSetupCYMRULookup(lft_session_params * sess);
463 /*Destination port number (same as using target:port as target)*/
464 int LFTSetupDestinationPort(lft_session_params * sess, char * userport);
465 /*Set the length of the probe packet in bytes*/
466 int LFTSetupLengthOfPacket(lft_session_params * sess, int plen);
467 /*Display hosts numerically; disable use of the DNS resolver*/
468 int LFTSetupDisableResolver(lft_session_params * sess);
469 /*Source port number*/
470 int LFTSetupSourcePort(lft_session_params * sess, int port);
471 /*Use LFT's stateful engine to detect firewalls and path anomalies*/
472 int LFTSetupAdaptiveMode(lft_session_params * sess);
473 /*Use a specific device by name or IP address (\"en1\" or \"1.2.3.4\")*/
474 int LFTSetupDevice(lft_session_params * sess,char * udev);
475 /*Use a specific device by name or IP address (\"en1\" or \"1.2.3.4\")*/
476 int LFTSetupSendDevice(lft_session_params * sess,char * sdev);
477 /*Display all times in UTC (GMT0).  Activates -T option automatically*/
478 int LFTSetupUTCTimes(lft_session_params * sess);
479 /*----------------------------------------------------------------------------*/
480 int lft_resolve_port (lft_session_params * sess, const char *strport);
481 void LFTExecute(lft_session_params * sess);
482 void lft_printf(lft_session_params * sess, const char *templ, ...);
483 /*----------------------------------------------------------------------------*/
484 void setOutputStyle(int nstyle); /* 0 - ordinary output, 1 - xml output */
485 int outputStyleIsXML(void);
486 int outputStyleIsGraphViz(void);
487 int getOutputStyle(void);
488 /*----------------------------------------------------------------------------*/
489 #ifdef	__cplusplus
490 }
491 #endif
492 
493 #endif /*LFT_LIB_H*/
494