]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/libalias/libalias.3
IFC @ r242684
[FreeBSD/FreeBSD.git] / sys / netinet / libalias / libalias.3
1 .\"-
2 .\" Copyright (c) 2001 Charles Mott <cm@linktel.net>
3 .\" All rights reserved.
4 .\"
5 .\" Redistribution and use in source and binary forms, with or without
6 .\" modification, are permitted provided that the following conditions
7 .\" are met:
8 .\" 1. Redistributions of source code must retain the above copyright
9 .\"    notice, this list of conditions and the following disclaimer.
10 .\" 2. Redistributions in binary form must reproduce the above copyright
11 .\"    notice, this list of conditions and the following disclaimer in the
12 .\"    documentation and/or other materials provided with the distribution.
13 .\"
14 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 .\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 .\" SUCH DAMAGE.
25 .\"
26 .\" $FreeBSD$
27 .\"
28 .Dd July 4, 2011
29 .Dt LIBALIAS 3
30 .Os
31 .Sh NAME
32 .Nm libalias
33 .Nd packet aliasing library for masquerading and network address translation
34 .Sh SYNOPSIS
35 .In sys/types.h
36 .In netinet/in.h
37 .In alias.h
38 .Pp
39 Function prototypes are given in the main body of the text.
40 .Sh DESCRIPTION
41 The
42 .Nm
43 library is a collection of functions for aliasing and de-aliasing of IP
44 packets, intended for masquerading and network address translation (NAT).
45 .Sh INTRODUCTION
46 This library is a moderately portable set of functions designed to assist
47 in the process of IP masquerading and network address translation.
48 Outgoing packets from a local network with unregistered IP addresses can
49 be aliased to appear as if they came from an accessible IP address.
50 Incoming packets are then de-aliased so that they are sent to the correct
51 machine on the local network.
52 .Pp
53 A certain amount of flexibility is built into the packet aliasing engine.
54 In the simplest mode of operation, a many-to-one address mapping takes
55 place between the local network and the packet aliasing host.
56 This is known as IP masquerading.
57 In addition, one-to-one mappings between local and public addresses can
58 also be implemented, which is known as static NAT.
59 In between these extremes, different groups of private addresses can be
60 linked to different public addresses, comprising several distinct
61 many-to-one mappings.
62 Also, a given public address and port can be statically redirected to a
63 private address/port.
64 .Sh INITIALIZATION AND CONTROL
65 One special function,
66 .Fn LibAliasInit ,
67 must always be called before any packet handling may be performed, and
68 the returned instance pointer must be passed to all the other functions.
69 Normally, the
70 .Fn LibAliasSetAddress
71 function is called afterwards, to set the default aliasing address.
72 In addition, the operating mode of the packet aliasing engine can be
73 customized by calling
74 .Fn LibAliasSetMode .
75 .Pp
76 .Ft "struct libalias *"
77 .Fn LibAliasInit "struct libalias *"
78 .Bd -ragged -offset indent
79 This function is used to initialize
80 internal data structures.
81 When called the first time, a
82 .Dv NULL
83 pointer should be passed as an argument.
84 The following mode bits are always set after calling
85 .Fn LibAliasInit .
86 See the description of
87 .Fn LibAliasSetMode
88 below for the meaning of these mode bits.
89 .Pp
90 .Bl -item -offset indent -compact
91 .It
92 .Dv PKT_ALIAS_SAME_PORTS
93 .It
94 .Dv PKT_ALIAS_USE_SOCKETS
95 .It
96 .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE
97 .El
98 .Pp
99 This function will always return the packet aliasing engine to the same
100 initial state.
101 The
102 .Fn LibAliasSetAddress
103 function is normally called afterwards, and any desired changes from the
104 default mode bits listed above require a call to
105 .Fn LibAliasSetMode .
106 .Pp
107 It is mandatory that this function be called at the beginning of a program
108 prior to any packet handling.
109 .Ed
110 .Pp
111 .Ft void
112 .Fn LibAliasUninit "struct libalias *"
113 .Bd -ragged -offset indent
114 This function has no return value and is used to clear any
115 resources attached to internal data structures.
116 .Pp
117 This function should be called when a program stops using the aliasing
118 engine; amongst other things, it clears out any firewall holes.
119 To provide backwards compatibility and extra security, it is added to
120 the
121 .Xr atexit 3
122 chain by
123 .Fn LibAliasInit .
124 .Ed
125 .Pp
126 .Ft void
127 .Fn LibAliasSetAddress "struct libalias *" "struct in_addr addr"
128 .Bd -ragged -offset indent
129 This function sets the source address to which outgoing packets from the
130 local area network are aliased.
131 All outgoing packets are re-mapped to this address unless overridden by a
132 static address mapping established by
133 .Fn LibAliasRedirectAddr .
134 If this function has not been called, and no static rules match, an outgoing
135 packet retains its source address.
136 .Pp
137 If the
138 .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE
139 mode bit is set (the default mode of operation), then the internal aliasing
140 link tables will be reset any time the aliasing address changes.
141 This is useful for interfaces such as
142 .Xr ppp 8 ,
143 where the IP
144 address may or may not change on successive dial-up attempts.
145 .Pp
146 If the
147 .Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE
148 mode bit is set to zero, this function can also be used to dynamically change
149 the aliasing address on a packet-to-packet basis (it is a low overhead call).
150 .Pp
151 It is mandatory that this function be called prior to any packet handling.
152 .Ed
153 .Pp
154 .Ft unsigned int
155 .Fn LibAliasSetMode "struct libalias *" "unsigned int flags" "unsigned int mask"
156 .Bd -ragged -offset indent
157 This function sets or clears mode bits
158 according to the value of
159 .Fa flags .
160 Only bits marked in
161 .Fa mask
162 are affected.
163 The following mode bits are defined in
164 .In alias.h :
165 .Bl -tag -width indent
166 .It Dv PKT_ALIAS_LOG
167 Enables logging into
168 .Pa /var/log/alias.log .
169 Each time an aliasing link is created or deleted, the log file is appended to
170 with the current number of ICMP, TCP and UDP links.
171 Mainly useful for debugging when the log file is viewed continuously with
172 .Xr tail 1 .
173 .It Dv PKT_ALIAS_DENY_INCOMING
174 If this mode bit is set, all incoming packets associated with new TCP
175 connections or new UDP transactions will be marked for being ignored
176 .Fn ( LibAliasIn
177 returns
178 .Dv PKT_ALIAS_IGNORED
179 code)
180 by the calling program.
181 Response packets to connections or transactions initiated from the packet
182 aliasing host or local network will be unaffected.
183 This mode bit is useful for implementing a one-way firewall.
184 .It Dv PKT_ALIAS_SAME_PORTS
185 If this mode bit is set, the packet-aliasing engine will attempt to leave
186 the alias port numbers unchanged from the actual local port numbers.
187 This can be done as long as the quintuple (proto, alias addr, alias port,
188 remote addr, remote port) is unique.
189 If a conflict exists, a new aliasing port number is chosen even if this
190 mode bit is set.
191 .It Dv PKT_ALIAS_USE_SOCKETS
192 This bit should be set when the packet aliasing host originates network
193 traffic as well as forwards it.
194 When the packet aliasing host is waiting for a connection from an unknown
195 host address or unknown port number (e.g.\& an FTP data connection), this
196 mode bit specifies that a socket be allocated as a place holder to prevent
197 port conflicts.
198 Once a connection is established, usually within a minute or so, the socket
199 is closed.
200 .It Dv PKT_ALIAS_UNREGISTERED_ONLY
201 If this mode bit is set, traffic on the local network which does not
202 originate from unregistered address spaces will be ignored.
203 Standard Class A, B and C unregistered addresses are:
204 .Pp
205 10.0.0.0     ->  10.255.255.255   (Class A subnet)
206 172.16.0.0   ->  172.31.255.255   (Class B subnets)
207 192.168.0.0  ->  192.168.255.255  (Class C subnets)
208 .Pp
209 This option is useful in the case that the packet aliasing host has both
210 registered and unregistered subnets on different interfaces.
211 The registered subnet is fully accessible to the outside world, so traffic
212 from it does not need to be passed through the packet aliasing engine.
213 .It Dv PKT_ALIAS_RESET_ON_ADDR_CHANGE
214 When this mode bit is set and
215 .Fn LibAliasSetAddress
216 is called to change the aliasing address, the internal link table of the
217 packet aliasing engine will be cleared.
218 This operating mode is useful for
219 .Xr ppp 8
220 links where the interface address can sometimes change or remain the same
221 between dial-up attempts.
222 If this mode bit is not set, the link table will never be reset in the event
223 of an address change.
224 .It Dv PKT_ALIAS_PUNCH_FW
225 This option makes
226 .Nm
227 .Dq punch holes
228 in an
229 .Xr ipfirewall 4 -
230 based firewall for FTP/IRC DCC connections.
231 The holes punched are bound by from/to IP address and port; it will not be
232 possible to use a hole for another connection.
233 A hole is removed when the connection that uses it dies.
234 To cater to unexpected death of a program using
235 .Nm
236 (e.g.\& kill -9),
237 changing the state of the flag will clear the entire firewall range
238 allocated for holes.
239 This clearing will also happen on the initial call to
240 .Fn LibAliasSetFWBase ,
241 which must happen prior to setting this flag.
242 .It Dv PKT_ALIAS_REVERSE
243 This option makes
244 .Nm
245 reverse the way it handles incoming and outgoing packets, allowing it
246 to be fed with data that passes through the internal interface rather
247 than the external one.
248 .It Dv PKT_ALIAS_PROXY_ONLY
249 This option tells
250 .Nm
251 to obey transparent proxy rules only.
252 Normal packet aliasing is not performed.
253 See
254 .Fn LibAliasProxyRule
255 below for details.
256 .It Dv PKT_ALIAS_SKIP_GLOBAL
257 This option is used by
258 .Pa ipfw_nat
259 only.
260 Specifying it as a flag to
261 .Fn LibAliasSetMode
262 has no effect.
263 See section
264 .Sx NETWORK ADDRESS TRANSLATION
265 in
266 .Xr ipfw 8
267 for more details.
268 .El
269 .Ed
270 .Pp
271 .Ft void
272 .Fn LibAliasSetFWBase "struct libalias *" "unsigned int base" "unsigned int num"
273 .Bd -ragged -offset indent
274 Set the firewall range allocated for punching firewall holes (with the
275 .Dv PKT_ALIAS_PUNCH_FW
276 flag).
277 The range is cleared for all rules on initialization.
278 .Ed
279 .Pp
280 .Ft void
281 .Fn LibAliasSkinnyPort "struct libalias *" "unsigned int port"
282 .Bd -ragged -offset indent
283 Set the TCP port used by the Skinny Station protocol.
284 Skinny is used by Cisco IP phones to communicate with
285 Cisco Call Managers to set up voice over IP calls.
286 If this is not set, Skinny aliasing will not be done.
287 The typical port used by Skinny is 2000.
288 .Ed
289 .Sh PACKET HANDLING
290 The packet handling functions are used to modify incoming (remote to local)
291 and outgoing (local to remote) packets.
292 The calling program is responsible for receiving and sending packets via
293 network interfaces.
294 .Pp
295 Along with
296 .Fn LibAliasInit
297 and
298 .Fn LibAliasSetAddress ,
299 the two packet handling functions,
300 .Fn LibAliasIn
301 and
302 .Fn LibAliasOut ,
303 comprise the minimal set of functions needed for a basic IP masquerading
304 implementation.
305 .Pp
306 .Ft int
307 .Fn LibAliasIn "struct libalias *" "char *buffer" "int maxpacketsize"
308 .Bd -ragged -offset indent
309 An incoming packet coming from a remote machine to the local network is
310 de-aliased by this function.
311 The IP packet is pointed to by
312 .Fa buffer ,
313 and
314 .Fa maxpacketsize
315 indicates the size of the data structure containing the packet and should
316 be at least as large as the actual packet size.
317 .Pp
318 Return codes:
319 .Bl -tag -width indent
320 .It Dv PKT_ALIAS_OK
321 The packet aliasing process was successful.
322 .It Dv PKT_ALIAS_IGNORED
323 The packet was ignored and not de-aliased.
324 This can happen if the protocol is unrecognized, as for an ICMP message
325 type that is not handled, or if incoming packets for new connections are being
326 ignored (if the
327 .Dv PKT_ALIAS_DENY_INCOMING
328 mode bit was set using
329 .Fn LibAliasSetMode ) .
330 .It Dv PKT_ALIAS_UNRESOLVED_FRAGMENT
331 This is returned when a fragment cannot be resolved because the header
332 fragment has not been sent yet.
333 In this situation, fragments must be saved with
334 .Fn LibAliasSaveFragment
335 until a header fragment is found.
336 .It Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT
337 The packet aliasing process was successful, and a header fragment was found.
338 This is a signal to retrieve any unresolved fragments with
339 .Fn LibAliasGetFragment
340 and de-alias them with
341 .Fn LibAliasFragmentIn .
342 .It Dv PKT_ALIAS_ERROR
343 An internal error within the packet aliasing engine occurred.
344 .El
345 .Ed
346 .Pp
347 .Ft int
348 .Fn LibAliasOut "struct libalias *" "char *buffer" "int maxpacketsize"
349 .Bd -ragged -offset indent
350 An outgoing packet coming from the local network to a remote machine is
351 aliased by this function.
352 The IP packet is pointed to by
353 .Fa buffer ,
354 and
355 .Fa maxpacketsize
356 indicates the maximum packet size permissible should the packet length be
357 changed.
358 IP encoding protocols place address and port information in the encapsulated
359 data stream which has to be modified and can account for changes in packet
360 length.
361 Well known examples of such protocols are FTP and IRC DCC.
362 .Pp
363 Return codes:
364 .Bl -tag -width indent
365 .It Dv PKT_ALIAS_OK
366 The packet aliasing process was successful.
367 .It Dv PKT_ALIAS_IGNORED
368 The packet was ignored and not aliased.
369 This can happen if the protocol is unrecognized, or possibly an ICMP message
370 type is not handled.
371 .It Dv PKT_ALIAS_ERROR
372 An internal error within the packet aliasing engine occurred.
373 .El
374 .Ed
375 .Sh PORT AND ADDRESS REDIRECTION
376 The functions described in this section allow machines on the local network
377 to be accessible in some degree to new incoming connections from the external
378 network.
379 Individual ports can be re-mapped or static network address translations can
380 be designated.
381 .Pp
382 .Ft struct alias_link *
383 .Fo LibAliasRedirectPort
384 .Fa "struct libalias *"
385 .Fa "struct in_addr local_addr"
386 .Fa "u_short local_port"
387 .Fa "struct in_addr remote_addr"
388 .Fa "u_short remote_port"
389 .Fa "struct in_addr alias_addr"
390 .Fa "u_short alias_port"
391 .Fa "u_char proto"
392 .Fc
393 .Bd -ragged -offset indent
394 This function specifies that traffic from a given remote address/port to
395 an alias address/port be redirected to a specified local address/port.
396 The parameter
397 .Fa proto
398 can be either
399 .Dv IPPROTO_TCP
400 or
401 .Dv IPPROTO_UDP ,
402 as defined in
403 .In netinet/in.h .
404 .Pp
405 If
406 .Fa local_addr
407 or
408 .Fa alias_addr
409 is zero, this indicates that the packet aliasing address as established
410 by
411 .Fn LibAliasSetAddress
412 is to be used.
413 Even if
414 .Fn LibAliasSetAddress
415 is called to change the address after
416 .Fn LibAliasRedirectPort
417 is called, a zero reference will track this change.
418 .Pp
419 If the link is further set up to operate with load sharing, then
420 .Fa local_addr
421 and
422 .Fa local_port
423 are ignored, and are selected dynamically from the server pool, as described in
424 .Fn LibAliasAddServer
425 below.
426 .Pp
427 If
428 .Fa remote_addr
429 is zero, this indicates to redirect packets from any remote address.
430 Likewise, if
431 .Fa remote_port
432 is zero, this indicates to redirect packets originating from any remote
433 port number.
434 The remote port specification will almost always be zero, but non-zero
435 remote addresses can sometimes be useful for firewalling.
436 If two calls to
437 .Fn LibAliasRedirectPort
438 overlap in their address/port specifications, then the most recent call
439 will have precedence.
440 .Pp
441 This function returns a pointer which can subsequently be used by
442 .Fn LibAliasRedirectDelete .
443 If
444 .Dv NULL
445 is returned, then the function call did not complete successfully.
446 .Pp
447 All port numbers should be in network address byte order, so it is necessary
448 to use
449 .Xr htons 3
450 to convert these parameters from internally readable numbers to network byte
451 order.
452 Addresses are also in network byte order, which is implicit in the use of the
453 .Fa struct in_addr
454 data type.
455 .Ed
456 .Pp
457 .Ft struct alias_link *
458 .Fo LibAliasRedirectAddr
459 .Fa "struct libalias *"
460 .Fa "struct in_addr local_addr"
461 .Fa "struct in_addr alias_addr"
462 .Fc
463 .Bd -ragged -offset indent
464 This function designates that all incoming traffic to
465 .Fa alias_addr
466 be redirected to
467 .Fa local_addr .
468 Similarly, all outgoing traffic from
469 .Fa local_addr
470 is aliased to
471 .Fa alias_addr .
472 .Pp
473 If
474 .Fa local_addr
475 or
476 .Fa alias_addr
477 is zero, this indicates that the packet aliasing address as established by
478 .Fn LibAliasSetAddress
479 is to be used.
480 Even if
481 .Fn LibAliasSetAddress
482 is called to change the address after
483 .Fn LibAliasRedirectAddr
484 is called, a zero reference will track this change.
485 .Pp
486 If the link is further set up to operate with load sharing, then the
487 .Fa local_addr
488 argument is ignored, and is selected dynamically from the server pool,
489 as described in
490 .Fn LibAliasAddServer
491 below.
492 .Pp
493 If subsequent calls to
494 .Fn LibAliasRedirectAddr
495 use the same aliasing address, all new incoming traffic to this aliasing
496 address will be redirected to the local address made in the last function
497 call.
498 New traffic generated by any of the local machines, designated in the
499 several function calls, will be aliased to the same address.
500 Consider the following example:
501 .Pp
502 LibAliasRedirectAddr(la, inet_aton("192.168.0.2"),
503                         inet_aton("141.221.254.101"));
504 LibAliasRedirectAddr(la, inet_aton("192.168.0.3"),
505                         inet_aton("141.221.254.101"));
506 LibAliasRedirectAddr(la, inet_aton("192.168.0.4"),
507                         inet_aton("141.221.254.101"));
508 .Pp
509 Any outgoing connections such as
510 .Xr telnet 1
511 or
512 .Xr ftp 1
513 from 192.168.0.2, 192.168.0.3 and 192.168.0.4 will appear to come from
514 141.221.254.101.
515 Any incoming connections to 141.221.254.101 will be directed to 192.168.0.4.
516 .Pp
517 Any calls to
518 .Fn LibAliasRedirectPort
519 will have precedence over address mappings designated by
520 .Fn LibAliasRedirectAddr .
521 .Pp
522 This function returns a pointer which can subsequently be used by
523 .Fn LibAliasRedirectDelete .
524 If
525 .Dv NULL
526 is returned, then the function call did not complete successfully.
527 .Ed
528 .Pp
529 .Ft int
530 .Fo LibAliasAddServer
531 .Fa "struct libalias *"
532 .Fa "struct alias_link *link"
533 .Fa "struct in_addr addr"
534 .Fa "u_short port"
535 .Fc
536 .Bd -ragged -offset indent
537 This function sets the
538 .Fa link
539 up for Load Sharing using IP Network Address Translation (RFC 2391, LSNAT).
540 LSNAT operates as follows.
541 A client attempts to access a server by using the server virtual address.
542 The LSNAT router transparently redirects the request to one of the hosts
543 in the server pool, using a real-time load sharing algorithm.
544 Multiple sessions may be initiated from the same client, and each session
545 could be directed to a different host based on the load balance across server
546 pool hosts when the sessions are initiated.
547 If load sharing is desired for just a few specific services, the configuration
548 on LSNAT could be defined to restrict load sharing to just the services
549 desired.
550 .Pp
551 Currently, only the simplest selection algorithm is implemented, where a
552 host is selected on a round-robin basis only, without regard to load on
553 the host.
554 .Pp
555 First, the
556 .Fa link
557 is created by either
558 .Fn LibAliasRedirectPort
559 or
560 .Fn LibAliasRedirectAddr .
561 Then,
562 .Fn LibAliasAddServer
563 is called multiple times to add entries to the
564 .Fa link Ns 's
565 server pool.
566 .Pp
567 For links created with
568 .Fn LibAliasRedirectAddr ,
569 the
570 .Fa port
571 argument is ignored and could have any value, e.g.\& htons(~0).
572 .Pp
573 This function returns 0 on success, \-1 otherwise.
574 .Ed
575 .Pp
576 .Ft int
577 .Fn LibAliasRedirectDynamic "struct libalias *" "struct alias_link *link"
578 .Bd -ragged -offset indent
579 This function marks the specified static redirect rule entered by
580 .Fn LibAliasRedirectPort
581 as dynamic.
582 This can be used to e.g.\& dynamically redirect a single TCP connection,
583 after which the rule is removed.
584 Only fully specified links can be made dynamic.
585 (See the
586 .Sx STATIC AND DYNAMIC LINKS
587 and
588 .Sx PARTIALLY SPECIFIED ALIASING LINKS
589 sections below for a definition of static vs.\& dynamic,
590 and partially vs.\& fully specified links.)
591 .Pp
592 This function returns 0 on success, \-1 otherwise.
593 .Ed
594 .Pp
595 .Ft void
596 .Fn LibAliasRedirectDelete "struct libalias *" "struct alias_link *link"
597 .Bd -ragged -offset indent
598 This function will delete a specific static redirect rule entered by
599 .Fn LibAliasRedirectPort
600 or
601 .Fn LibAliasRedirectAddr .
602 The parameter
603 .Fa link
604 is the pointer returned by either of the redirection functions.
605 If an invalid pointer is passed to
606 .Fn LibAliasRedirectDelete ,
607 then a program crash or unpredictable operation could result, so
608 care is needed when using this function.
609 .Ed
610 .Pp
611 .Ft int
612 .Fn LibAliasProxyRule "struct libalias *" "const char *cmd"
613 .Bd -ragged -offset indent
614 The passed
615 .Fa cmd
616 string consists of one or more pairs of words.
617 The first word in each pair is a token and the second is the value that
618 should be applied for that token.
619 Tokens and their argument types are as follows:
620 .Bl -tag -width indent
621 .It Cm type encode_ip_hdr | encode_tcp_stream | no_encode
622 In order to support transparent proxying, it is necessary to somehow
623 pass the original address and port information into the new destination
624 server.
625 If
626 .Cm encode_ip_hdr
627 is specified, the original destination address and port are passed
628 as an extra IP option.
629 If
630 .Cm encode_tcp_stream
631 is specified, the original destination address and port are passed
632 as the first piece of data in the TCP stream in the format
633 .Dq Li DEST Ar IP port .
634 .It Cm port Ar portnum
635 Only packets with the destination port
636 .Ar portnum
637 are proxied.
638 .It Cm server Ar host Ns Op : Ns Ar portnum
639 This specifies the
640 .Ar host
641 and
642 .Ar portnum
643 that the data is to be redirected to.
644 .Ar host
645 must be an IP address rather than a DNS host name.
646 If
647 .Ar portnum
648 is not specified, the destination port number is not changed.
649 .Pp
650 The
651 .Ar server
652 specification is mandatory unless the
653 .Cm delete
654 command is being used.
655 .It Cm rule Ar index
656 Normally, each call to
657 .Fn LibAliasProxyRule
658 inserts the next rule at the start of a linear list of rules.
659 If an
660 .Ar index
661 is specified, the new rule will be checked after all rules with lower
662 indices.
663 Calls to
664 .Fn LibAliasProxyRule
665 that do not specify a rule are assigned rule 0.
666 .It Cm delete Ar index
667 This token and its argument MUST NOT be used with any other tokens.
668 When used, all existing rules with the given
669 .Ar index
670 are deleted.
671 .It Cm proto tcp | udp
672 If specified, only packets of the given protocol type are matched.
673 .It Cm src Ar IP Ns Op / Ns Ar bits
674 If specified, only packets with a source address matching the given
675 .Ar IP
676 are matched.
677 If
678 .Ar bits
679 is also specified, then the first
680 .Ar bits
681 bits of
682 .Ar IP
683 are taken as a network specification, and all IP addresses from that
684 network will be matched.
685 .It Cm dst Ar IP Ns Op / Ns Ar bits
686 If specified, only packets with a destination address matching the given
687 .Ar IP
688 are matched.
689 If
690 .Ar bits
691 is also specified, then the first
692 .Ar bits
693 bits of
694 .Ar IP
695 are taken as a network specification, and all IP addresses from that
696 network will be matched.
697 .El
698 .Pp
699 This function is usually used to redirect outgoing connections for
700 internal machines that are not permitted certain types of internet
701 access, or to restrict access to certain external machines.
702 .Ed
703 .Pp
704 .Ft struct alias_link *
705 .Fo LibAliasRedirectProto
706 .Fa "struct libalias *"
707 .Fa "struct in_addr local_addr"
708 .Fa "struct in_addr remote_addr"
709 .Fa "struct in_addr alias_addr"
710 .Fa "u_char proto"
711 .Fc
712 .Bd -ragged -offset indent
713 This function specifies that any IP packet with protocol number of
714 .Fa proto
715 from a given remote address to an alias address will be
716 redirected to a specified local address.
717 .Pp
718 If
719 .Fa local_addr
720 or
721 .Fa alias_addr
722 is zero, this indicates that the packet aliasing address as established
723 by
724 .Fn LibAliasSetAddress
725 is to be used.
726 Even if
727 .Fn LibAliasSetAddress
728 is called to change the address after
729 .Fn LibAliasRedirectProto
730 is called, a zero reference will track this change.
731 .Pp
732 If
733 .Fa remote_addr
734 is zero, this indicates to redirect packets from any remote address.
735 Non-zero remote addresses can sometimes be useful for firewalling.
736 .Pp
737 If two calls to
738 .Fn LibAliasRedirectProto
739 overlap in their address specifications, then the most recent call
740 will have precedence.
741 .Pp
742 This function returns a pointer which can subsequently be used by
743 .Fn LibAliasRedirectDelete .
744 If
745 .Dv NULL
746 is returned, then the function call did not complete successfully.
747 .Ed
748 .Sh FRAGMENT HANDLING
749 The functions in this section are used to deal with incoming fragments.
750 .Pp
751 Outgoing fragments are handled within
752 .Fn LibAliasOut
753 by changing the address according to any applicable mapping set by
754 .Fn LibAliasRedirectAddr ,
755 or the default aliasing address set by
756 .Fn LibAliasSetAddress .
757 .Pp
758 Incoming fragments are handled in one of two ways.
759 If the header of a fragmented IP packet has already been seen, then all
760 subsequent fragments will be re-mapped in the same manner the header
761 fragment was.
762 Fragments which arrive before the header are saved and then retrieved
763 once the header fragment has been resolved.
764 .Pp
765 .Ft int
766 .Fn LibAliasSaveFragment "struct libalias *" "char *ptr"
767 .Bd -ragged -offset indent
768 When
769 .Fn LibAliasIn
770 returns
771 .Dv PKT_ALIAS_UNRESOLVED_FRAGMENT ,
772 this function can be used to save the pointer to the unresolved fragment.
773 .Pp
774 It is implicitly assumed that
775 .Fa ptr
776 points to a block of memory allocated by
777 .Xr malloc 3 .
778 If the fragment is never resolved, the packet aliasing engine will
779 automatically free the memory after a timeout period.
780 [Eventually this function should be modified so that a callback function
781 for freeing memory is passed as an argument.]
782 .Pp
783 This function returns
784 .Dv PKT_ALIAS_OK
785 if it was successful and
786 .Dv PKT_ALIAS_ERROR
787 if there was an error.
788 .Ed
789 .Pp
790 .Ft char *
791 .Fn LibAliasGetFragment "struct libalias *" "char *buffer"
792 .Bd -ragged -offset indent
793 This function can be used to retrieve fragment pointers saved by
794 .Fn LibAliasSaveFragment .
795 The IP header fragment pointed to by
796 .Fa buffer
797 is the header fragment indicated when
798 .Fn LibAliasIn
799 returns
800 .Dv PKT_ALIAS_FOUND_HEADER_FRAGMENT .
801 Once a fragment pointer is retrieved, it becomes the calling program's
802 responsibility to free the dynamically allocated memory for the fragment.
803 .Pp
804 The
805 .Fn LibAliasGetFragment
806 function can be called sequentially until there are no more fragments
807 available, at which time it returns
808 .Dv NULL .
809 .Ed
810 .Pp
811 .Ft void
812 .Fn LibAliasFragmentIn "struct libalias *" "char *header" "char *fragment"
813 .Bd -ragged -offset indent
814 When a fragment is retrieved with
815 .Fn LibAliasGetFragment ,
816 it can then be de-aliased with a call to
817 .Fn LibAliasFragmentIn .
818 The
819 .Fa header
820 argument is the pointer to a header fragment used as a template, and
821 .Fa fragment
822 is the pointer to the packet to be de-aliased.
823 .Ed
824 .Sh MISCELLANEOUS FUNCTIONS
825 .Ft struct alias_link *
826 .Fn AddLink "struct libalias *" "struct in_addr src_addr" "struct in_addr dst_addr" \
827 "struct in_addr alias_addr" "u_short src_port" "u_short dst_port" \
828 "int alias_param" "int link_type"
829 .Bd -ragged -offset indent
830 This function adds new state to the instance hash table.
831 The dst_address and/or dst_port may be given as zero, which
832 introduces some dynamic character into the link, since
833 LibAliasSetAddress can change the address that is used.
834 However, in the current implementation, such links can only be used
835 for inbound (ext -> int) traffic.
836 .Ed
837 .Pp
838 .Ft void
839 .Fn LibAliasSetTarget "struct libalias *" "struct in_addr addr"
840 .Bd -ragged -offset indent
841 When an incoming packet not associated with any pre-existing aliasing link
842 arrives at the host machine, it will be sent to the address indicated by a
843 call to
844 .Fn LibAliasSetTarget .
845 .Pp
846 If this function is called with an
847 .Dv INADDR_NONE
848 address argument, then all new incoming packets go to the address set by
849 .Fn LibAliasSetAddress .
850 .Pp
851 If this function is not called, or is called with an
852 .Dv INADDR_ANY
853 address argument, then all new incoming packets go to the address specified
854 in the packet.
855 This allows external machines to talk directly to internal machines if they
856 can route packets to the machine in question.
857 .Ed
858 .Pp
859 .Ft int
860 .Fn LibAliasCheckNewLink "struct libalias *"
861 .Bd -ragged -offset indent
862 This function returns a non-zero value when a new aliasing link is created.
863 In circumstances where incoming traffic is being sequentially sent to
864 different local servers, this function can be used to trigger when
865 .Fn LibAliasSetTarget
866 is called to change the default target address.
867 .Ed
868 .Pp
869 .Ft u_short
870 .Fn LibAliasInternetChecksum "struct libalias *" "u_short *buffer" "int nbytes"
871 .Bd -ragged -offset indent
872 This is a utility function that does not seem to be available elsewhere and
873 is included as a convenience.
874 It computes the internet checksum, which is used in both IP and
875 protocol-specific headers (TCP, UDP, ICMP).
876 .Pp
877 The
878 .Fa buffer
879 argument points to the data block to be checksummed, and
880 .Fa nbytes
881 is the number of bytes.
882 The 16-bit checksum field should be zeroed before computing the checksum.
883 .Pp
884 Checksums can also be verified by operating on a block of data including
885 its checksum.
886 If the checksum is valid,
887 .Fn LibAliasInternetChecksum
888 will return zero.
889 .Ed
890 .Pp
891 .Ft int
892 .Fn LibAliasUnaliasOut "struct libalias *" "char *buffer" "int maxpacketsize"
893 .Bd -ragged -offset indent
894 An outgoing packet, which has already been aliased,
895 has its private address/port information restored by this function.
896 The IP packet is pointed to by
897 .Fa buffer ,
898 and
899 .Fa maxpacketsize
900 is provided for error checking purposes.
901 This function can be used if an already-aliased packet needs to have its
902 original IP header restored for further processing (e.g.\& logging).
903 .Ed
904 .Sh AUTHORS
905 .An Charles Mott Aq cm@linktel.net ,
906 versions 1.0 - 1.8, 2.0 - 2.4.
907 .An Eivind Eklund Aq eivind@FreeBSD.org ,
908 versions 1.8b, 1.9 and 2.5.
909 Added IRC DCC support as well as contributing a number of architectural
910 improvements; added the firewall bypass for FTP/IRC DCC.
911 .An Erik Salander Aq erik@whistle.com
912 added support for PPTP and RTSP.
913 .An Junichi Satoh Aq junichi@junichi.org
914 added support for RTSP/PNA.
915 .An Ruslan Ermilov Aq ru@FreeBSD.org
916 added support for PPTP and LSNAT as well as general hacking.
917 .An Paolo Pisati Aq piso@FreeBSD.org
918 made the library modular, moving support for all
919 protocols (except for IP, TCP and UDP) to external modules.
920 .Sh ACKNOWLEDGEMENTS
921 Listed below, in approximate chronological order, are individuals who
922 have provided valuable comments and/or debugging assistance.
923 .Bd -ragged -offset indent
924 .An -split
925 .An Gary Roberts
926 .An Tom Torrance
927 .An Reto Burkhalter
928 .An Martin Renters
929 .An Brian Somers
930 .An Paul Traina
931 .An Ari Suutari
932 .An Dave Remien
933 .An J. Fortes
934 .An Andrzej Bialecki
935 .An Gordon Burditt
936 .Ed
937 .Sh CONCEPTUAL BACKGROUND
938 This section is intended for those who are planning to modify the source
939 code or want to create somewhat esoteric applications using the packet
940 aliasing functions.
941 .Pp
942 The conceptual framework under which the packet aliasing engine operates
943 is described here.
944 Central to the discussion is the idea of an
945 .Em aliasing link
946 which describes the relationship for a given packet transaction between
947 the local machine, aliased identity and remote machine.
948 It is discussed how such links come into existence and are destroyed.
949 .Ss ALIASING LINKS
950 There is a notion of an
951 .Em aliasing link ,
952 which is a 7-tuple describing a specific translation:
953 .Bd -literal -offset indent
954 (local addr, local port, alias addr, alias port,
955  remote addr, remote port, protocol)
956 .Ed
957 .Pp
958 Outgoing packets have the local address and port number replaced with the
959 alias address and port number.
960 Incoming packets undergo the reverse process.
961 The packet aliasing engine attempts to match packets against an internal
962 table of aliasing links to determine how to modify a given IP packet.
963 Both the IP header and protocol dependent headers are modified as necessary.
964 Aliasing links are created and deleted as necessary according to network
965 traffic.
966 .Pp
967 Protocols can be TCP, UDP or even ICMP in certain circumstances.
968 (Some types of ICMP packets can be aliased according to sequence or ID
969 number which acts as an equivalent port number for identifying how
970 individual packets should be handled.)
971 .Pp
972 Each aliasing link must have a unique combination of the following five
973 quantities: alias address/port, remote address/port and protocol.
974 This ensures that several machines on a local network can share the
975 same aliasing IP address.
976 In cases where conflicts might arise, the aliasing port is chosen so that
977 uniqueness is maintained.
978 .Ss STATIC AND DYNAMIC LINKS
979 Aliasing links can either be static or dynamic.
980 Static links persist indefinitely and represent fixed rules for translating
981 IP packets.
982 Dynamic links come into existence for a specific TCP connection or UDP
983 transaction or ICMP ECHO sequence.
984 For the case of TCP, the connection can be monitored to see when the
985 associated aliasing link should be deleted.
986 Aliasing links for UDP transactions (and ICMP ECHO and TIMESTAMP requests)
987 work on a simple timeout rule.
988 When no activity is observed on a dynamic link for a certain amount of time
989 it is automatically deleted.
990 Timeout rules also apply to TCP connections which do not open or close
991 properly.
992 .Ss PARTIALLY SPECIFIED ALIASING LINKS
993 Aliasing links can be partially specified, meaning that the remote address
994 and/or remote port are unknown.
995 In this case, when a packet matching the incomplete specification is found,
996 a fully specified dynamic link is created.
997 If the original partially specified link is dynamic, it will be deleted
998 after the fully specified link is created, otherwise it will persist.
999 .Pp
1000 For instance, a partially specified link might be
1001 .Bd -literal -offset indent
1002 (192.168.0.4, 23, 204.228.203.215, 8066, 0, 0, tcp)
1003 .Ed
1004 .Pp
1005 The zeros denote unspecified components for the remote address and port.
1006 If this link were static it would have the effect of redirecting all
1007 incoming traffic from port 8066 of 204.228.203.215 to port 23 (telnet)
1008 of machine 192.168.0.4 on the local network.
1009 Each individual telnet connection would initiate the creation of a distinct
1010 dynamic link.
1011 .Ss DYNAMIC LINK CREATION
1012 In addition to aliasing links, there are also address mappings that can be
1013 stored within the internal data table of the packet aliasing mechanism.
1014 .Bd -literal -offset indent
1015 (local addr, alias addr)
1016 .Ed
1017 .Pp
1018 Address mappings are searched when creating new dynamic links.
1019 .Pp
1020 All outgoing packets from the local network automatically create a dynamic
1021 link if they do not match an already existing fully specified link.
1022 If an address mapping exists for the outgoing packet, this determines
1023 the alias address to be used.
1024 If no mapping exists, then a default address, usually the address of the
1025 packet aliasing host, is used.
1026 If necessary, this default address can be changed as often as each individual
1027 packet arrives.
1028 .Pp
1029 The aliasing port number is determined such that the new dynamic link does
1030 not conflict with any existing links.
1031 In the default operating mode, the packet aliasing engine attempts to set
1032 the aliasing port equal to the local port number.
1033 If this results in a conflict, then port numbers are randomly chosen until
1034 a unique aliasing link can be established.
1035 In an alternate operating mode, the first choice of an aliasing port is also
1036 random and unrelated to the local port number.
1037 .Sh MODULAR ARCHITECTURE (AND Xr ipfw 4 Sh SUPPORT)
1038 One of the latest improvements to
1039 .Nm
1040 was to make its support
1041 for new protocols independent from the rest of the library, giving it
1042 the ability to load/unload support for new protocols at run-time.
1043 To achieve this feature, all the code for protocol handling was moved
1044 to a series of modules outside of the main library.
1045 These modules are compiled from the same sources but work in
1046 different ways, depending on whether they are compiled to work inside a kernel
1047 or as part of the userland library.
1048 .Ss LIBALIAS MODULES IN KERNEL LAND
1049 When compiled for the kernel,
1050 .Nm
1051 modules are plain KLDs recognizable with the
1052 .Pa alias_
1053 prefix.
1054 .Pp
1055 To add support for a new protocol, load the corresponding module.
1056 For example:
1057 .Pp
1058 .Dl "kldload alias_ftp"
1059 .Pp
1060 When support for a protocol is no longer needed, its module can be unloaded:
1061 .Pp
1062 .Dl "kldunload alias_ftp"
1063 .Ss LIBALIAS MODULES IN USERLAND
1064 Due to the differences between kernel and userland (no KLD mechanism,
1065 many different address spaces, etc.), we had to change a bit how to
1066 handle module loading/tracking/unloading in userland.
1067 .Pp
1068 While compiled for a userland
1069 .Nm ,
1070 all the modules are plain libraries, residing in
1071 .Pa /usr/lib ,
1072 and recognizable with the
1073 .Pa libalias_
1074 prefix.
1075 .Pp
1076 There is a configuration file,
1077 .Pa /etc/libalias.conf ,
1078 with the following contents (by default):
1079 .Bd -literal -offset indent
1080 /usr/lib/libalias_cuseeme.so
1081 /usr/lib/libalias_ftp.so
1082 /usr/lib/libalias_irc.so
1083 /usr/lib/libalias_nbt.so
1084 /usr/lib/libalias_pptp.so
1085 /usr/lib/libalias_skinny.so
1086 /usr/lib/libalias_smedia.so
1087 .Ed
1088 .Pp
1089 This file contains the paths to the modules that
1090 .Nm
1091 will load.
1092 To load/unload a new module, just add its path to
1093 .Pa libalias.conf
1094 and call
1095 .Fn LibAliasRefreshModules
1096 from the program.
1097 In case the application provides a
1098 .Dv SIGHUP
1099 signal handler, add a call to
1100 .Fn LibAliasRefreshModules
1101 inside the handler, and everytime you want to refresh the loaded modules,
1102 send it the
1103 .Dv SIGHUP
1104 signal:
1105 .Pp
1106 .Dl "kill -HUP <process_pid>"
1107 .Ss MODULAR ARCHITECURE: HOW IT WORKS
1108 The modular architecture of
1109 .Nm
1110 works similar whether it is running inside the
1111 kernel or in userland.
1112 From
1113 .Pa alias_mod.c :
1114 .Bd -literal
1115 /* Protocol and userland module handlers chains. */
1116 LIST_HEAD(handler_chain, proto_handler) handler_chain ...
1117 \&...
1118 SLIST_HEAD(dll_chain, dll) dll_chain ...
1119 .Ed
1120 .Pp
1121 .Va handler_chain
1122 keeps track of all the protocol handlers loaded, while
1123 .Va ddl_chain
1124 tracks which userland modules are loaded.
1125 .Pp
1126 .Va handler_chain
1127 is composed of
1128 .Vt "struct proto_handler"
1129 entries:
1130 .Bd -literal
1131 struct proto_handler {
1132         u_int pri;
1133         int16_t dir;
1134         uint8_t proto;
1135         int (*fingerprint)(struct libalias *la,
1136                  struct ip *pip, struct alias_data *ah);
1137         int (*protohandler)(struct libalias *la,
1138                  struct ip *pip, struct alias_data *ah);
1139         LIST_ENTRY(proto_handler) entries;
1140 };
1141 .Ed
1142 .Pp
1143 where:
1144 .Bl -inset
1145 .It Va pri
1146 is the priority assigned to a protocol handler; lower priority
1147 is better.
1148 .It Va dir
1149 is the direction of packets: ingoing or outgoing.
1150 .It Va proto
1151 indicates to which protocol this packet belongs: IP, TCP or UDP.
1152 .It Va fingerprint
1153 points to the fingerprint function while protohandler points
1154 to the protocol handler function.
1155 .El
1156 .Pp
1157 The
1158 .Va fingerprint
1159 function has the dual role of checking if the
1160 incoming packet is found, and if it belongs to any categories that this
1161 module can handle.
1162 .Pp
1163 The
1164 .Va protohandler
1165 function actually manipulates
1166 the packet to make
1167 .Nm
1168 correctly NAT it.
1169 .Pp
1170 When a packet enters
1171 .Nm ,
1172 if it meets a module hook,
1173 .Va handler_chain
1174 is searched to see if there is an handler that matches
1175 this type of a packet (it checks protocol and direction of packet).
1176 Then, if more than one handler is found, it starts with the module with
1177 the lowest priority number: it calls the
1178 .Va fingerprint
1179 function and interprets the result.
1180 .Pp
1181 If the result value is equal to 0 then it calls the protocol handler
1182 of this handler and returns.
1183 Otherwise, it proceeds to the next eligible module until the
1184 .Va handler_chain
1185 is exhausted.
1186 .Pp
1187 Inside
1188 .Nm ,
1189 the module hook looks like this:
1190 .Bd -literal -offset indent
1191 struct alias_data ad = {
1192         lnk,
1193         &original_address,
1194         &alias_address,
1195         &alias_port,
1196         &ud->uh_sport,          /* original source port */
1197         &ud->uh_dport,          /* original dest port */
1198         256                     /* maxpacketsize */
1199 };
1200
1201 \&...
1202
1203 /* walk out chain */
1204 err = find_handler(IN, UDP, la, pip, &ad);
1205 .Ed
1206 .Pp
1207 All data useful to a module are gathered together in an
1208 .Vt alias_data
1209 structure, then
1210 .Fn find_handler
1211 is called.
1212 The
1213 .Fn find_handler
1214 function is responsible for walking the handler
1215 chain; it receives as input parameters:
1216 .Bl -tag -width indent
1217 .It Fa IN
1218 direction
1219 .It Fa UDP
1220 working protocol
1221 .It Fa la
1222 pointer to this instance of libalias
1223 .It Fa pip
1224 pointer to a
1225 .Vt "struct ip"
1226 .It Fa ad
1227 pointer to
1228 .Vt "struct alias_data"
1229 (see above)
1230 .El
1231 .Pp
1232 In this case,
1233 .Fn find_handler
1234 will search only for modules registered for
1235 supporting INcoming UDP packets.
1236 .Pp
1237 As was mentioned earlier,
1238 .Nm
1239 in userland is a bit different, as
1240 care must be taken in module handling as well (avoiding duplicate load of
1241 modules, avoiding modules with same name, etc.) so
1242 .Va dll_chain
1243 was introduced.
1244 .Pp
1245 .Va dll_chain
1246 contains a list of all userland
1247 .Nm
1248 modules loaded.
1249 .Pp
1250 When an application calls
1251 .Fn LibAliasRefreshModules ,
1252 .Nm
1253 first unloads all the loaded modules, then reloads all the modules listed in
1254 .Pa /etc/libalias.conf :
1255 for every module loaded, a new entry is added to
1256 .Va dll_chain .
1257 .Pp
1258 .Va dll_chain
1259 is composed of
1260 .Vt "struct dll"
1261 entries:
1262 .Bd -literal
1263 struct dll {
1264         /* name of module */
1265         char            name[DLL_LEN];
1266         /*
1267          * ptr to shared obj obtained through
1268          * dlopen() - use this ptr to get access
1269          * to any symbols from a loaded module
1270          * via dlsym()
1271          */
1272         void            *handle;
1273         struct dll      *next;
1274 };
1275 .Ed
1276 .Bl -inset
1277 .It Va name
1278 is the name of the module.
1279 .It Va handle
1280 is a pointer to the module obtained through
1281 .Xr dlopen 3 .
1282 .El
1283 Whenever a module is loaded in userland, an entry is added to
1284 .Va dll_chain ,
1285 then every protocol handler present in that module
1286 is resolved and registered in
1287 .Va handler_chain .
1288 .Ss HOW TO WRITE A MODULE FOR LIBALIAS
1289 There is a module (called
1290 .Pa alias_dummy.[ch] )
1291 in
1292 .Nm
1293 that can be used as a skeleton for future work.
1294 Here we analyse some parts of that module.
1295 From
1296 .Pa alias_dummy.c :
1297 .Bd -literal
1298 struct proto_handler handlers [] = {{666, IN|OUT, UDP|TCP,
1299                                     &fingerprint, &protohandler}};
1300 .Ed
1301 .Pp
1302 The variable
1303 .Va handlers
1304 is the
1305 .Dq "most important thing"
1306 in a module
1307 since it describes the handlers present and lets the outside world use
1308 it in an opaque way.
1309 .Pp
1310 It must ALWAYS be present in every module, and it MUST retain
1311 the name
1312 .Va handlers ,
1313 otherwise attempting to load a module in userland will fail and
1314 complain about missing symbols: for more information about module
1315 load/unload, please refer to
1316 .Fn LibAliasRefreshModules ,
1317 .Fn LibAliasLoadModule
1318 and
1319 .Fn LibAliasUnloadModule
1320 in
1321 .Pa alias.c .
1322 .Pp
1323 .Va handlers
1324 contains all the
1325 .Vt proto_handler
1326 structures present in a module.
1327 .Bd -literal
1328 static int
1329 mod_handler(module_t mod, int type, void *data)
1330 {
1331         int error;
1332
1333         switch (type) {
1334         case MOD_LOAD:
1335                 error = 0;
1336                 attach_handlers(handlers);
1337                 break;
1338         case MOD_UNLOAD:
1339                 error = 0;
1340                 detach_handlers(handlers;
1341                 break;
1342         default:
1343                 error = EINVAL;
1344         }
1345         return (error);
1346 }
1347 .Ed
1348 When running as KLD,
1349 .Fn mod_handler
1350 registers/deregisters the module using
1351 .Fn attach_handlers
1352 and
1353 .Fn detach_handlers ,
1354 respectively.
1355 .Pp
1356 Every module must contain at least 2 functions: one fingerprint
1357 function and a protocol handler function.
1358 .Bd -literal
1359 #ifdef _KERNEL
1360 static
1361 #endif
1362 int
1363 fingerprint(struct libalias *la, struct ip *pip, struct alias_data *ah)
1364 {
1365
1366 \&...
1367 }
1368
1369 #ifdef _KERNEL
1370 static
1371 #endif
1372 int
1373 protohandler(struct libalias *la, struct ip *pip,
1374              struct alias_data *ah)
1375 {
1376
1377 \&...
1378 }
1379 .Ed
1380 and they must accept exactly these input parameters.
1381 .Ss PATCHING AN APPLICATION FOR USERLAND LIBALIAS MODULES
1382 To add module support into an application that uses
1383 .Nm ,
1384 the following simple steps can be followed.
1385 .Bl -enum
1386 .It
1387 Find the main file of an application
1388 (let us call it
1389 .Pa main.c ) .
1390 .It
1391 Add this to the header section of
1392 .Pa main.c ,
1393 if not already present:
1394 .Pp
1395 .Dl "#include <signal.h>"
1396 .Pp
1397 and this just after the header section:
1398 .Pp
1399 .Dl "static void signal_handler(int);"
1400 .It
1401 Add the following line to the init function of an application or,
1402 if it does not have any init function, put it in
1403 .Fn main :
1404 .Pp
1405 .Dl "signal(SIGHUP, signal_handler);"
1406 .Pp
1407 and place the
1408 .Fn signal_handler
1409 function somewhere in
1410 .Pa main.c :
1411 .Bd -literal -offset indent
1412 static void
1413 signal_handler(int sig)
1414 {
1415
1416         LibAliasRefreshModules();
1417 }
1418 .Ed
1419 .Pp
1420 Otherwise, if an application already traps the
1421 .Dv SIGHUP
1422 signal, just add a call to
1423 .Fn LibAliasRefreshModules
1424 in the signal handler function.
1425 .El
1426 For example, to patch
1427 .Xr natd 8
1428 to use
1429 .Nm
1430 modules, just add the following line to
1431 .Fn RefreshAddr "int sig __unused" :
1432 .Pp
1433 .Dl "LibAliasRefreshModules()"
1434 .Pp
1435 recompile and you are done.
1436 .Ss LOGGING SUPPORT IN KERNEL LAND
1437 When working as KLD,
1438 .Nm
1439 now has log support that
1440 happens on a buffer allocated inside
1441 .Vt "struct libalias"
1442 (from
1443 .Pa alias_local.h ) :
1444 .Bd -literal
1445 struct libalias {
1446        ...
1447
1448         /* log descriptor        */
1449 #ifdef  KERNEL_LOG
1450         char           *logDesc;        /*
1451                                          * ptr to an auto-malloced
1452                                          * memory buffer when libalias
1453                                          * works as kld
1454                                          */
1455 #else
1456         FILE           *logDesc;        /*
1457                                          * ptr to /var/log/alias.log
1458                                          * when libalias runs as a
1459                                          * userland lib
1460                                          */
1461 #endif
1462
1463         ...
1464 }
1465 .Ed
1466 so all applications using
1467 .Nm
1468 will be able to handle their
1469 own logs, if they want, accessing
1470 .Va logDesc .
1471 Moreover, every change to a log buffer is automatically added to
1472 .Xr syslog 3
1473 with the
1474 .Dv LOG_SECURITY
1475 facility and the
1476 .Dv LOG_INFO
1477 level.