星期五, 七月 13, 2007

随便说说字符集和编码


  快下班时,爱问问题的小朋友Nico又问了一个问题:
"sqlserver里面有char和nchar,那个n据说是指unicode的数据,这个是什么意思。"

  并不是所有简单的问题都很容易回答,就像这个问题一样。于是我答应专门写一篇BLOG来从头讲讲编码的故事。那么就让我们找个草堆坐下,先抽口烟,看看夜晚天空上的银河,然后想一想要从哪里开始讲起。嗯,也许这样开始比较好……

  很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物。他们看到8个开关状态是好的,于是他们把这称为"字节"。

  再后来,他们又做了一些可以处理这些字节的机器,机器开动了,可以用字节来组合出很多状态,状态开始变来变去。他们看到这样是好的,于是它们就称这机器称为"计算机"。

  开始计算机只在美国用。八位的字节一共可以组合出256(2的8次方)种不同的状态。 他们把其中的编号从0开始的32种状态分别规定了特殊的用途,一但终端、打印机遇上约定好的这些字节被传过来时,就要做一些约定的动作。遇上0x10, 终端就换行,遇上0x07, 终端就向人们嘟嘟叫,例好遇上0x1b, 打印机就打印反白的字,或者终端就用彩色显示字母。他们看到这样很好,于是就把这些0x20以下的字节状态称为"控制码"。 他们又把所有的空格、标点符号、数字、大小写字母分别用连续的字节状态表示,一直编到了第127号,这样计算机就可以用不同字节来存储英语的文字了。大家 看到这样,都感觉很好,于是大家都把这个方案叫做 ANSI 的"Ascii"编码(American Standard Code for Information Interchange,美国信息互换标准代码)。当时世界上所有的计算机都用同样的ASCII方案来保存英文文字。

  后来,就像建造巴比伦塔一样,世界各地的都开始使用计算机,但是很多国家用的不是英文,他们的字母里有许多是ASCII里没有的,为了可以在计算机保存他 们的文字,他们决定采用127号之后的空位来表示这些新的字母、符号,还加入了很多画表格时需要用下到的横线、竖线、交叉等形状,一直把序号编到了最后一个状态255。从128到255这一页的字符集被称"扩展字符集"。从此之后,贪婪的人类再没有新的状态可以用了,美帝国主义可能没有想到还有第三世界国家的人们也希望可以用到计算机吧!

  等中国人们得到计算机时,已经没有可以利用的字节状态来表示汉字,况且有6000多个常用汉字需要保存呢。但是这难不倒智慧的中国人民,我们不客气地把那 些127号之后的奇异符号们直接取消掉, 规定:一个小于127的字符的意义与原来相同,但两个大于127的字符连在一起时,就表示一个汉字,前面的一个字节(他称之为高字节)从0xA1用到 0xF7,后面一个字节(低字节)从0xA1到0xFE,这样我们就可以组合出大约7000多个简体汉字了。在这些编码里,我们还把数学符号、罗马希腊的字母、日文的假名们都编进去了,连在 ASCII 里本来就有的数字、标点、字母都统统重新编了两个字节长的编码,这就是常说的"全角"字符,而原来在127号以下的那些就叫"半角"字符了。

  中国人民看到这样很不错,于是就把这种汉字方案叫做 "GB2312"。GB2312 是对 ASCII 的中文扩展。 但是中国的汉字太多了,我们很快就就发现有许多人的人名没有办法在这里打出来,特别是某些很会麻烦别人的国家领导人。于是我们不得不继续把 GB2312 没有用到的码位找出来老实不客气地用上。 后来还是不够用,于是干脆不再要求低字节一定是127号之后的内码,只要第一个字节是大于127就固定表示这是一个汉字的开始,不管后面跟的是不是扩展字 符集里的内容。结果扩展之后的编码方案被称为 GBK 标准,GBK 包括了 GB2312 的所有内容,同时又增加了近20000个新的汉字(包括繁体字)和符号。后来少数民族也要用电脑了,于是我们再扩展,又加了几千个新的少数民族的字,GBK 扩成了 GB18030。从此之后,中华民族的文化就可以在计算机时代中传承了。

  中国的程序员们看到这一系列汉字编码的标准是好的,于是通称他们叫做 "DBCS"(Double Byte Charecter Set 双字节字符集)。在DBCS系列标准里,最大的特点是两字节长的汉字字符和一字节长的英文字符并存于同一套编码方案里,因此他们写的程序为了支持中文处 理,必须要注意字串里的每一个字节的值,如果这个值是大于127的,那么就认为一个双字节字符集里的字符出现了。那时候凡是受过加持,会编程的计算机僧侣们都要每天念下面这个咒语数百遍: "一个汉字算两个英文字符!一个汉字算两个英文字符……"

  因为当时各个国家都像中国这样搞出一套自己的编码标准,结果互相之间谁也不懂谁的编码,谁也不支持别人的编码,连大陆和台湾这样只相隔了150海里,使用着同一种语言的兄弟地区,也分别采用了不同的 DBCS 编码方案——当时的中国人想让电脑显示汉字,就必须装上一个"汉字系统",专门用来处理汉字的显示、输入的问题,但是那个台湾的愚昧封建人士写的算命程序 就必须加装另一套支持 BIG5 编码的什么"倚天汉字系统"才可以用,装错了字符系统,显示就会乱了套!这怎么办?而且世界民族之林中还有那些一时用不上电脑的穷苦人民,他们的文字又怎 么办?

  真是计算机的巴比伦塔命题啊!

  正在这时,大天使加百列及时出现了——一个叫 ISO (国际标谁化组织)的国际组织决定着手解决这个问题。他们采用的方法很简单:废了所有的地区性编码方案,重新搞一个包括了地球上所有文化、所有字母和符号 的编码!他们打算叫它"Universal Multiple-Octet Coded Character Set",简称 UCS, 俗称 "UNICODE"。

  UNICODE 开始制订时,计算机的存储器容量极大地发展了,空间再也不成为问题了。于是 ISO 就直接规定必须用两个字节,也就是16位来统一表示所有的字符,对于ascii里的那些“半角”字符,UNICODE 包持其原编码不变,只是将其长度由原来的8位扩展为16位,而其他文化和语言的字符则全部重新统一编码。由于"半角"英文符号只需要用到低8位,所以其高 8位永远是0,因此这种大气的方案在保存英文文本时会多浪费一倍的空间。

  这时候,从旧社会里走过来的程序员开始发现一个奇怪的现象:他们的strlen函数靠不住了,一个汉字不再是相当于两个字符了,而是一个!是的,从 UNICODE 开始,无论是半角的英文字母,还是全角的汉字,它们都是统一的"一个字符"!同时,也都是统一的"两个字节",请注意"字符"和"字节"两个术语的不同, “字节”是一个8位的物理存贮单元,而“字符”则是一个文化相关的符号。在UNICODE 中,一个字符就是两个字节。一个汉字算两个英文字符的时代已经快过去了。

  从前多种字符集存在时,那些做多语言软件的公司遇上过很大麻烦,他们为了在不同的国家销售同一套软件,就不得不在区域化软件时也加持那个双字节字符集咒 语,不仅要处处小心不要搞错,还要把软件中的文字在不同的字符集中转来转去。UNICODE 对于他们来说是一个很好的一揽子解决方案,于是从 Windows NT 开始,MS 趁机把它们的操作系统改了一遍,把所有的核心代码都改成了用 UNICODE 方式工作的版本,从这时开始,WINDOWS 系统终于无需要加装各种本土语言系统,就可以显示全世界上所有文化的字符了。

  但是,UNICODE 在制订时没有考虑与任何一种现有的编码方案保持兼容,这使得 GBK 与UNICODE 在汉字的内码编排上完全是不一样的,没有一种简单的算术方法可以把文本内容从UNICODE编码和另一种编码进行转换,这种转换必须通过查表来进行。

  如前所述,UNICODE 是用两个字节来表示为一个字符,他总共可以组合出65535不同的字符,这大概已经可以覆盖世界上所有文化的符号。如果还不够也没有关系,ISO已经准备 了UCS-4方案,说简单了就是四个字节来表示一个字符,这样我们就可以组合出21亿个不同的字符出来(最高位有其他用途),这大概可以用到银河联邦成立 那一天吧!

  UNICODE 来到时,一起到来的还有计算机网络的兴起,UNICODE 如何在网络上传输也是一个必须考虑的问题,于是面向传输的众多 UTF(UCS Transfer Format)标准出现了,顾名思义,UTF8就是每次8个位传输数据,而UTF16就是每次16个位,只不过为了传输时的可靠性,从UNICODE到 UTF时并不是直接的对应,而是要过一些算法和规则来转换。

从网上引来一段从UNICODE到UTF8的转换规则:



Unicode UTF-8

0000 - 007F 0xxxxxxx

0080 - 07FF 110xxxxx 10xxxxxx

0800 - FFFF 1110xxxx 10xxxxxx 10xxxxxx


  例如"汉"字的Unicode编码是6C49。6C49在0800-FFFF之间,所以要用3字节模板:1110xxxx 10xxxxxx 10xxxxxx。将6C49写成二进制是:0110 1100 0100 1001,将这个比特流按三字节模板的分段方法分为0110 110001 001001,依次代替模板中的x,得到:1110-0110 10-110001 10-001001,即E6 B1 89,这就是其UTF8的编码。

  讲到这里,我们再顺便说说一个很著名的奇怪现象:当你在 windows 的记事本里新建一个文件,输入"联通"两个字之后,保存,关闭,然后再次打开,你会发现这两个字已经消失了,代之的是几个乱码!呵呵,有人说这就是联通之所以拼不过移动的原因。

  其实这是因为GB2312编码与UTF8编码产生了编码冲撞的原因。

  而当你新建一个文本文件时,记事本的编码默认是ANSI, 如果你在ANSI的编码输入汉字,那么他实际就是GB系列的编码方式,在这种编码下,"联通"的内码是:

  c1 1100 0001
  aa 1010 1010
  cd 1100 1101
  a8 1010 1000

  注意到了吗?第一二个字节、第三四个字节的起始部分的都是"110"和"10",正好与UTF8规则里的两字节模板是一致的,于是再次打开记事本时,记事 本就误认为这是一个UTF8编码的文件,让我们把第一个字节的110和第二个字节的10去掉,我们就得到了"00001 101010",再把各位对齐,补上前导的0,就得到了"0000 0000 0110 1010",不好意思,这是UNICODE的006A,也就是小写的字母"j",而之后的两字节用UTF8解码之后是0368,这个字符什么也不是。这就 是只有"联通"两个字的文件没有办法在记事本里正常显示的原因。

  而如果你在"联通"之后多输入几个字,其他的字的编码不见得又恰好是110和10开始的字节,这样再次打开时,记事本就不会坚持这是一个utf8编码的文件,而会用ANSI的方式解读之,这时乱码又不出现了。



  受到过网络编程加持的计算机僧侣们都知道,在网络里传递信息时有一个很重要的问题,就是对于数据高低位的解读方式,一些计算机是采用低位先发送的方法,例如我们PC机采用的 INTEL 架构,而另一些是采用高位先发送的方式,在网络中交换数据时,为了核对双方对于高低位的认识是否是一致的,采用了一种很简便的方法,就是在文本流的开始时 向对方发送一个标志符——如果之后的文本是高位在位,那就发送"FEFF",反之,则发送"FFFE"。不信你可以用二进制方式打开一个UTF-X格式的 文件,看看开头两个字节是不是这两个字节?

  顺便提一下little endian和big endian这两个网络术语的来历: 在《格列佛游记》中, 小人国中由于争论吃鸡蛋应该从大头敲还是从小头敲而分成了不同派系, 还发生了战争, 连皇帝都被干掉了. 在计算机技术发展中, 不同体系的硬件之间的通信也因为大头在前还是小头在前产生了同样严重的问题, 因此技术专家里比较幽默的那部分人——那一绝大部分人——就采用了"endian"这个有强烈政治隐喻的术语.

  好了,终于可以回答NICO的问题了,在数据库里,有n前缀的字串类型就是UNICODE类型,这种类型中,固定用两个字节来表示一个字符,无论这个字符是汉字还是英文字母,或是别的什么。

  下面的例子应该可以说明unicode型和ansi型的字段的区别:

  我们在任意类型的数据库中建一个表, 含有如下的字段.
    • nc nchar(10)
    • c char(10)
  然后, 我们再试着向其中加入下面的记录:
    • "1234567890", "1234567890"
    • "一二三四五六七八九十","一二三四五六七八九十"
  对于第一条记录, 两个字段都可以插入10个字符, 同时也都一个字符也多存不了.
但对于第二条记录, nc字段可以把从"一"到"十"的数据都保存进去, 而c字段只能保存到"五", 再多就会出错.

  为什么? 因为在nchar字段里, 一个汉字一个字符, 10字符宽的字段就可以保存10个汉字. 而char字段里, 一个汉字算两个字符, 10字符宽的字段就只能保存5个汉字了.

  "abc汉字"这个串的长度,在没有n前缀的数据类型里,这个字串是7个字符的长度,因为一个汉字相当于两个字符。而在有n前缀的数据类型里,同样的测试串长度的函数将会告诉你是5个字符,因为一个汉字就是一个字符。

  希望这篇文章是NICO想要的.

参考资料:http://spaces.msn.com/haoxiaobo/blog/cns!D1C72860197EBF38!425.entry

星期二, 七月 10, 2007

郁闷中

上个月月底,去铁通给医院取ADSL上网费的发票,正值周五,加上韩冬送我一个冰箱,总而言之,一段乱七八糟的时间过去后,发票找不到了。

非但找不到了,而且忘得一干二净,在我的记忆里竟是一块空白。光说我老了也不能排解我的郁闷。

我很久没丢失过什么东西了,而且工作上相关的更是从来没有过。生气,生气。

总结这次的教训,我认为我的生活习惯有很多很多缺点。如不改正,我将永远像现在这个样子!

星期一, 七月 09, 2007

卷土重来

我的博客:http://chengchao.blogspot.com/ 不能访问已经很久了。我几乎没心情去留下什么了。今天让我改成了 ftp 发布方式,可以访问了。哈哈,先爽朗的笑一下。但是,偌大的国家用这种不要脸的方式封堵,真是让我不知道说什么好了。嘿嘿 - 再鄙视的笑一声。

这个标题:卷土重来,让我想起了我的学生时代:许yh和张lch。我离开学生时代也已经很久了。

星期三, 六月 06, 2007

双线路问题

开始

还是去年的这个时候,李硕问我在FreeBSD上有没有网吧(电信、网通)双线路的解决办法,共同研究。我说有,但是上网一找却没找到。后来李硕再没提此事,就忘了。

后来,韩冬媳妇问我会不会做网吧双线,说可以用来联系电信的业务。我说可以试试看。再后来,结婚,去哈尔滨学习水手业务,从哈尔滨回来就回家过年,然后找工作,上班。这件事一直没有结果。

直到上个月,给吉林教育杂志社做网络共享连接,一时兴起用 m0n0Wall 做了,又想起这件事来。

离开方正维修站后。暂时没有好的想法和打算,于是趁机研究了一下。

实践

起初,在网上找相关的文章,大多是用专用路由器解决。除了那些专用设备以外我能接触上的只有:Route OS 、 m0n0Wall 、Iptables 、ipfw、ipf 和 pf 。我一个一个的试。其实这些东西都是我所不了解的,下载找资料安装测试就花去了很多时间。后来我决定从 pf 开始着手,因为这个我手上的资料最多,FreeBSD 是我相对来说最熟悉的。

以前用过 ipfw 、 ipfilter 之后就没用过 pf ,主要是和他们老是弄混。一个功能的实现方式不一样,所以学着很别扭。用过了以后才知道 pf 真的是很好的一个防火墙系统,我很喜欢。

我给自己搭建了以下的环境:


pc1 : ---------------------| | pc2 : --------------------------------- || modem:

FreeBSD 4.11 + ipfilter ----| | FreeBSD 6.2 + pf

rl0 192.168.1.254 ---------|-|----------------------------------------> (to modem)

rl1 172.16.11.1/24 <-------|-|-> fxp0 172.16.11.2/24 (default 172.16.11.1)

rl2 172.17.12.1/24 <------- |-|-> fxp1 172.16.12.2/24


pc3 :Windowx 2003 -------|
192.168.0.2/24 -default- <-|---> rl0 192.168.0.1/24
Windows 2003

pc1 设置:

自动 PPPoE 拨号
ipfilter 共享上网,一切从简。
pass in quick all
pass out quick all
map tun0 172.16.0.0/16 -> 0/32 portmap tcp/udp 10000:40000
map tun0 172.16.0.0/16 -> 0/32

中间忘记了启用ip转发,上不了网,浪费了一些时间,晕一下。

pc2 设置:

1.表

table 《表名》 persist file "/etc/telecom_ip"

2.规则
ext_if1 = "fxp0"
ext_gw2 = "172.16.11.1"
ext_if2 = "fxp1"
ext_gw2 = "172.16.12.1"
int_if = "rl0:
int_net = "192.168.0.0/24"

table perstst files "/etc/telecom_ip"

下面是手册中的说明,我按照他给出的例子做了修改。

#下面的例子通过2条到因特网的连接平衡输出流量:
#pass in on $int_if route-to {($ext_if1 $ext_gw2), ($ext_if2 $ext_gw2)} round-robin from $int_net to any keep state

# route-to 选项用来在收到流量的内部接口上指定平衡的流量经过各自的网关到输出的网络接口。
# 注意route-to 选项必须在每个需要均衡的过滤规则上出现。返回的数据包会路由到它们出去时的外部接口(这是由ISP做的),然后正常路由回内部网络。
# 要保证带有属于$ext_if1源地址的数据包总是路由到$ext_gw1($ext_if2 和 $ext_gw2也是同样的),下面2行必须包括在规则集中:
pass out on $ext_if1 route-to ($ext_if2 $ext_gw2) from $ext_if2 to any
pass out on $ext_if2 route-to ($ext_if2 $ext_gw2) from $ext_if1 to any

# 最后,NAT也可以使用在输出接口中:
nat on $ext_if2 from $int_net to -> $ext_if2
nat on $ext_if1 from $int_net to any -> $ext_if1


实验到晚上,我发现,问题的关键在于静态路由表:不添加静态路由表的话,走另外一条线路的访问不会回来。但是做负载均衡的可以。目前来看,只要加了静态路由表,做一下两个方向的NAT 规则就可已各走各的路。不加静态路由表,怎么做都没有用。明天加一台机器再测试。

下面是第二天(12:56 2007-6-6)做的实验。

以下的这个规则是从手册上修改过来的,他的确可以实现负载均衡。

# cat pf.2
lan_net = "192.168.0.0/24"
int_if = "rl0"
ext_if1 = "fxp0"
ext_if2 = "fxp1"
ext_gw1 = "172.16.11.1"
ext_gw2 = "172.16.12.1"

table persist file "/etc/telecom_ip"


# nat outgoing connections on each internet interface
nat on $ext_if1 from $lan_net to any -> ($ext_if1)
nat on $ext_if2 from $lan_net to any -> ($ext_if2)

# default deny
block in from any to any
block out from any to any

# pass all outgoing packets on internal interface
pass out on $int_if from any to $lan_net

# pass in quick any packets destined for the gateway itself
pass in quick on $int_if from $lan_net to $int_if

# load balance outgoing tcp traffic from internal network.
pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto tcp from $lan_net to any flags S/SA modulate state

# load balance outgoing udp and icmp traffic from internal network
pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto { udp, icmp } from $lan_net to any keep state

# general "pass out" rules for external interfaces
pass out on $ext_if1 proto tcp from any to any flags S/SA modulate state
pass out on $ext_if1 proto { udp, icmp } from any to any keep state
pass out on $ext_if2 proto tcp from any to any flags S/SA modulate state
pass out on $ext_if2 proto { udp, icmp } from any to any keep state

# route packets from any IPs on $ext_if1 to $ext_gw1 and the same for
# $ext_if2 and $ext_gw2
pass out on $ext_if1 route-to ($ext_if2 $ext_gw2) from $ext_if2 to any
pass out on $ext_if2 route-to ($ext_if1 $ext_gw1) from $ext_if1 to any



既然双线路出口都有数据通过,似乎加不加默认网关已经没什么作用了。于是我删除了默认网关。没错,在pc2 上已经不能 nslookup 了,但是在 2003 上可以,同样可以下载文件,同样是负载均衡状态,两条出口线路都有数据经过。

最后我发现:问题出现在问题出在局域网入口上:


# load balance outgoing tcp traffic from internal network.
pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto tcp from $lan_net to any flags S/SA modulate state

# load balance outgoing udp and icmp traffic from internal network
pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto { udp, icmp } from $lan_net to any keep state


这两条就是让从连接局域网的网卡上进入的数据平均分摊到两条出口上。所以我做了如下修改:

pass in quick on $int_if route-to ($ext_if2 $ext_gw2) proto tcp from $lan_net to 《表名》 flags S/SA modulate state

pass in quick on $int_if route-to ($ext_if1 $ext_gw1) proto tcp from $lan_net to any flags S/SA modulate state


现在似乎是成功了。
下面是我最终的修改结果,让 tcp 和 icmp 分线走,udp 到 dns 的走默认线路。其实我想可以在局域网网关机器上添加默认路由并做 DNS 转发,这样就可以都分开了。

# cat pf.2
lan_net = "192.168.0.0/24"
int_if = "rl0"
ext_if1 = "fxp0"
ext_if2 = "fxp1"
ext_gw1 = "172.16.11.1"
ext_gw2 = "172.16.12.1"
table persist file "/etc/telecom_ip"

# nat outgoing connections on each internet interface
### nat on $ext_if1 from $lan_net to any -> ($ext_if1)
### nat on $ext_if2 from $lan_net to any -> ($ext_if2)

nat on $ext_if2 from $lan_net to -> ($ext_if2)
nat on $ext_if1 from $lan_net to any -> ($ext_if1)

# default deny
block in from any to any
block out from any to any

# pass all outgoing packets on internal interface
pass out on $int_if from any to $lan_net

# pass in quick any packets destined for the gateway itself
pass in quick on $int_if from $lan_net to $int_if

# load balance outgoing tcp traffic from internal network.
#### pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto tcp from $lan_net to any flags S/SA modulate state
############

pass in quick on $int_if route-to ($ext_if2 $ext_gw2) \
proto tcp from $lan_net to flags S/SA modulate state

pass in quick on $int_if route-to ($ext_if1 $ext_gw1) \
proto tcp from $lan_net to any flags S/SA modulate state

# load balance outgoing udp and icmp traffic from internal network
#### pass in on $int_if route-to \
{ ($ext_if1 $ext_gw1), ($ext_if2 $ext_gw2) } round-robin \
proto { udp, icmp } from $lan_net to any keep state
############

pass in on $int_if route-to ($ext_if1 $ext_gw1) \
proto udp from $lan_net to any port 53 keep state

pass in quick on $int_if route-to ($ext_if2 $ext_gw2) \
proto icmp from $lan_net to keep state

pass in quick on $int_if route-to ($ext_if1 $ext_gw1) \
proto icmp from $lan_net to any keep state


# general "pass out" rules for external interfaces
pass out on $ext_if1 proto tcp from any to any flags S/SA modulate state
pass out on $ext_if1 proto { udp, icmp } from any to any keep state
pass out on $ext_if2 proto tcp from any to any flags S/SA modulate state
pass out on $ext_if2 proto { udp, icmp } from any to any keep state

# route packets from any IPs on $ext_if1 to $ext_gw1 and the same for
# $ext_if2 and $ext_gw2
pass out on $ext_if1 route-to ($ext_if2 $ext_gw2) from $ext_if2 to 《表名》
pass out on $ext_if2 route-to ($ext_if1 $ext_gw1) from $ext_if1 to any



昨天晚上还看了一篇在 Route OS 上做双线的文章,它的优势是可以检测线路状态,当一条线路断掉了,就把双线并成一条线路来走。这个我想也可以写成一个脚本来实现。但是今天没时间了。

发表在这里的文字中的尖括号会被过滤,所以请以理解的方式阅读。Sorry。

星期五, 五月 25, 2007

Policy Routing

Policy Routing

Policy routing is the process of forcing packets to take a certain route, often different from the default route, based on certain packet attributes (source, type of packets, interface, etc.).

The need for policy routing arises for multi-homed hosts (hosts having two network connections to different ISPs), that cannot use a single default route. Having a central Internet connection for multiple private networks can require policy routing. It is most useful in case you have multiple networks connected behind a FreeBSD host with more than one connection to the Internet, when each network needs to use a different outgoing route.

Also, policy routing should be employed when you need to separate traffic by certain criteria, such as source, destination or protocol

When Not to Use Policy Routing
Policy routing can be extremely useful, but it is not always needed. A frequent case of misuse is when configuring a tunnel as a default route. Instead of using the first gateway as the default, then injecting all the other traffic in the tunnel, use more specific routes. For example, if the tunnel ends at 10.10.10.10, the ip of the other end inside the tunnel is 1.2.3.4, and the gateway your provider gave you (and don't actually want to use) is at 2.2.2.2, you can use these routes in /etc/rc.conf:

static_routes=“tunnel_end”
route_tunnel_end=“-host 10.10.10.10 2.2.2.2”
defaultrouter=“1.2.3.4”Since policy routing does involve a certain overhead on the system, do think of a different solution first. Specific routes can be very useful, but policy routing is the only solution for certain cases.

Configuring Policy Routing
The easiest way of doing policy routing with FreeBSD is by using IPFilter. It comes by default with all recent versions of FreeBSD, and it can be easily enabled by adding this line to /etc/rc.conf:

ipfilter_enable=“YES”Be advised that the IP addresses used in this article are fictional, and I have mixed public IP addresses with private ones (see RFC1918). You might find those in private networks, but they will almost never be assigned to you by an ISP.

Example 1 - Multi-homed Host

Suppose you have a host that is connected to two networks, via two interfaces: fxp0, with an IP address of 192.168.100.100, and fxp1, with an IP address of 192.168.200.200, both with the default classful netmask of 255.255.255.0. On both those networks, the gateways are located at 192.168.*.1. I'll assume that the default route is out fxp0.


Now suppose the host receives a ping (an ICMP echo request packet) from host 1.1.1.1, to its IP address 192.168.200.200. The reply will be generated with a source address of 192.168.200.200, and sent to 1.1.1.1. But if the host has no specific route to 1.1.1.1, it will use the default route out fxp0, and try to send the reply via the gateway at 192.168.100.1. If a stateful firewall is in place on the gateway, the packet will most probably be dropped, as the request came via the other gateway (in the 200 network). Also, if egress filtering (filtering of outbound traffic) is configured on the 100 network gateway, the reply will be blocked because it is coming from a different network (and possibly logged as a spoofing attempt). This will also affect other types of packets, like TCP and UDP.

The solution for this problem is rather simple: use policy routing to force packets from the 192.168.200.200 address to leave via the network they belong to. This is line in /etc/ipf.rules will do just as I have described:

pass out quick on fxp0 to fxp1:192.168.200.1 from 192.168.200.200 to any This rule says “force packets from my fxp1 address to exit via the gateway on fxp1 (not my default gateway on fxp0)”.

Example 2 - Asymmetric Traffic

This is similar to Example 1, but with a different purpose. Let's assume that one of the links, fxp0, is an ADSL link with a static IP address. The fxp1 link is a cable modem, with a dynamic IP. You want to have a web server, so you put it on the static IP. But the cable link has better bandwidth, so you want to take advantage of that.

Web traffic in inherently asymmetric, with a small request from the client to the server, and a larger reply from the server to the client. So receiving the request on the ADSL link will not hurt, and it has the added benefit of having a static IP address. So you decide to send the replies via the bigger bandwidth link.

What you need to do is allow requests to the web server on your static IP address to come in via the ADSL link, but policy route the reply, diverting it to the cable link. Here is a configuration that does that:

pass in quick on fxp0 proto tcp from any to 192.168.100.100
pass out quick on fxp0 to fxp1:192.168.200.1 proto tcp from 192.168.100.100 port = 80 to any The gateway on fxp1 (192.168.200.1 in this example) is assigned by DHCP, and you can find it out by running this command:

# grep routers /var/db/dhclient.leasesThis will not work if your ISP on the cable link implements egress filtering. For a web request to complete successfully, the reply must come from the host the request went to. Since you will be sending the reply via another link (possibly belonging to a different ISP than the one who owns the fixed IP address), the cable ISP might choose not to forward your packets, and make this setup inoperable.

Example 3 - Routing for Multiple Networks

Another scenario is a network that has access to two different ISPs, and has assigned addresses from each of those. The interfaces connecting to those ISPs are fxp0 at 10.0.0.2, using the gateway at 10.0.0.1, and fxp1 at 20.0.0.2, using the gateway at 20.0.0.1. The networks assigned by those two ISPs are 192.168.100.0/24, and 192.168.200.0/24. Traffic originating from the 100 network belongs to the 10.0.0.1 ISP, and the other network to the 20.0.0.1 ISP. The interfaces connecting those two nets are de0 and de1.


This needs a simple configuration in /etc/ipf.rules. But we do have to take care and not shoot packets out to the ISP that are intended for the FreeBSD machine (which we'll suppose is at .254 on both those networks).

# accept packets to us, don't forward them
pass in quick on de0 from 192.168.100.0/24 to 192.168.100.254
pass in quick on de1 from 192.168.200.0/24 to 192.168.200.254

# other packets should be handled by their respective ISP
# ISP1
pass in quick on de0 to fxp0:10.0.0.1 from 192.168.100.0/24 to any
# ISP2
pass in quick on de1 to fxp1:20.0.0.1 from 192.168.200.0/24 to anyAdditional Resources
Egress filtering - Keeping the Internet Safe from Your Systems
Anatomy of a Stateful Firewall
- Alex