bianbian coding life

便便代码人生: 关注技术, 翻译文档, 偶尔动动手

bianbian.org

[原]ARP欺骗及防治

Posted by bianbian on 2006-09-21 23:35


本文Tags: ,

今天和danny一起试了一下p2pOver(网络执法官也属于此类),一开始都觉得很奇怪:交换机不像hub,已经不广播了,怎么还能控制别的机器的流量呢。。。好玩,研究一下。用数据截取软件(wireshark)查看了一下,其他都正常,却发现狂发了N多ARP(Address Resolution Protocol、地址解析协议)包。看来问题就出在这里。
ARP欺骗原理
再仔细看了一下ARP数据包,终于恍然大悟欺骗原理。
是这样的,为了能和其他机器通讯,局域网上的各个机器都缓存了ARP列表(ARP列表可以简单理解成“一个IP地址对应一个MAC地址”)。机器要通过网关和其他机器通讯,其实是在局域网内发了查询ARP请求(可以简单理解成“网关啊,请把你的MAC地址告诉我好吗?”);网关收到此类请求后,就会发送ARP回应报文,回应网关的MAC。这样,某个机器就会把通讯数据发到网关的MAC上。
那么运行了p2pOver之类的软件后是怎么欺骗的呢?简单起见,我们设使用了p2pOver的机器为”A”,”A”的MAC地址为”M”。
首先,”A”通过ARP查询得到真实的网关MAC,和不停地轮询局域网上其他主机(IP)及其MAC。
其次,”A”不停地给局域网上其他主机发送伪造的ARP回应报文:告诉他们网关的MAC是”M”;
同时,”A”也不停给交换机发送伪造的ARP回应报文:告诉真正的网关局域网上所有主机的MAC地址为”M”。
因为是不停地发送报文,到了最后:局域网上的其他主机以为网关就是”A”,真正的网关以为局域网上的所有通讯只来自”A”。也就是”A”变成了事实上的中转中心:不仅可以截取其他主机的流量和数据,还能随心所欲地截断网络通讯。
ARP欺骗防治
从欺骗原理,不难推出防治关键就是想办法不接收错误的ARP回应报文:
1) 使用智能交换机,绑定网内所有IP-MAC。这样也就不需要ARP查询才能知道MAC。
2) 还有一个办法,就是在网内所有机器上绑定死网关的MAC(下面适用于WinXP):
在网络正常情况下:arp -a 网关IP(如192.168.1.1),查询到正确的网关MAC
然后绑定网关MAC:arp -s 网关IP 网关MAC
在执行arp -a,看到网关IP和MAC是静态(Static)的,就可以了:
arp

标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Technology, Windows | No Comments »

[原]杀了个816.exe木马

Posted by bianbian on 2006-09-21 00:03


本文Tags:

从来不装杀毒软件,我也从来不乱装东西,乱看网页。基本上没事。不装杀毒软件是因为这个不仅会拖慢系统,而且是个马后炮,真正厉害的病毒来了大家一起挂;而且现在杀毒软件越来越像个病毒了。。。。
寒,机器被谁用了下,就被装了个木马。因为我的机器做了个代理,访问网站是有日志的。发现系统最近老是去下载某个叫816.exe的文件。感觉不对。
首先看了下任务管理器,没有奇怪的进程--肯定注入到其他进程里了(基本上是可怜的Explorer.exe)。
Sysinternals Process Explorer看了下,果然,Explorer.exe所有使用的DLL里有个DLMon.dll,是个奇怪的东西。google了一下,果然是个盗QQ密码的木马。
于是用Sysinternals Process Explorer杀了Explorer.exe的进程,运行cmd,cd C:\windows\system32,del DLMon.dll,居然提示没找到--肯定又用了attrib的伎俩,那可是高中DOS时代的法宝--于是先 attrib *Mon.dll -s -h,del DLMon.dll,这下干净了。同时system32还有一个DLMain.dll,也要删除。
再运行Explorer.exe,没有奇怪的附加DLL,基本上可以了。然后regedit,搜RunOnce,把RunOnce里和Run里莫名奇妙的一些exe启动项(包括指定的文件)给删了:
C:\windows\system32\intenet.exe (Windows正常的是internet.exe,少了个r)
C:\windows\816.exe (还有系统的temp里肯定也有)
C:\windows\Program Files\Intel\rundll32.exe (寒Intel)
OK了。如果能抓到写这些垃圾软件的,一定要大家一起动手打一顿。

标签:

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Technology, Windows | 1 Comment »

[原]PostgreSQL complex query(PostgreSQL的复杂查询)

Posted by bianbian on 2006-09-19 14:27


本文Tags: ,

试了一会儿,先记下来。省得以后忘掉。

Well, the tables are: (tag的表情况,usertags表记录了每个用户的tag(一行记录一个tag),usersites表记录了每个url对应的多个tags,urltags表记录了一个usersiteid对应多个usertagid(反过来也是一个usertagid对应多个usersiteid))

  1. usertags                  usersites                       urltags
  2. =======================================================================
  3. id tagname userid      id url title userid tags      id usersiteid usertagid

now we need to get all tagnames, tagid, and used times of a tag, sorted by used times, how to do it? (现在我们需要一次查询得到所有的tagname、每个tag对应的tagid和使用次数并按使用次数排序)
SQL 语句如下:

  1. SELECT count(t.usersiteid) AS count, t.usertagid, n.tagname
  2.   FROM urltags t, usertags n
  3.     WHERE t.usertagid=n.id
  4.     AND usertagid in ( select DISTINCT on (usertagid) usertagid from urltags )
  5.   group by t.usertagid,n.tagname
  6.   order by count DESC

中间的子查询“select DISTINCT on (usertagid) usertagid from urltags ”查询出所有对照表里的usertagid,其中DISTINCT on(usertagid)表示只查询出usertagid字段不重复的记录(即多个相同的usertagid值的话只取一个)。DISTINCT的写法可能只是postgreSQL的特殊函数,不过相信其他数据库应该也有不同写法的支持。
执行结果截图,应该是对的吧。。。。呵呵:
Postgresql_query

标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Database, Technology | No Comments »

[原]推荐一个eclipse插件:aptana

Posted by bianbian on 2006-09-17 23:55


本文Tags: , ,

update地址: http://update.aptana.com/update/
编写css和js和htm的插件
css和js不仅会语法提示,还用图标指示了IE/Firefox适用否
唯一的缺点(优点?)是更新太频繁,老是要update….

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Technology | 3 Comments »

[原]Delphi调用ShellAPI删除整个目录(我觉得是最快的方法)

Posted by bianbian on 2006-09-16 15:28


本文Tags: ,

  1. var
  2.   S: string;
  3.   T: TSHFileOpStruct;
  4. begin
  5.     S := '目录名';
  6.     with T do
  7.     begin
  8.       Wnd := 0;
  9.       wFunc := FO_DELETE;
  10.       pFrom := PChar(S);
  11.       pTo := nil;
  12.       fFlags := FOF_ALLOWUNDO + FOF_NOCONFIRMATION + FOF_NOERRORUI;
  13.       //标志表明允许恢复,无须确认并不显示出错信息
  14.       hNameMappings := nil;
  15.       lpszProgressTitle := '正在删除文件夹';
  16.       fAnyOperationsAborted := False;
  17.     end;
  18.     SHFileOperation(T);
  19. end;
标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Delphi, Technology | No Comments »

[译]Koda 1.6.0.0发布

Posted by bianbian on 2006-09-14 20:57


本文Tags: ,

原帖地址:http://www.autoitscript.com/fileman/users/lookfar/formdesign.html
我翻译了一下,做了简体中文的语言文件。见:AutoIt 3的GUI生成工具Koda。繁体中文可以参考这里:Koda 1.6.0.0 正體中文化

After long period of development and testing, new release 1.6.0.0 is finally here! Thanks to all who support us and help done this work!

Most significant changes from previous release:
New, more fast and reliable form read/write routines.
Rewritten form list handling code
Menus support (with visual editor)
Obj support (with visual browser)
Templates-based code generation
Generating event-based code
Help file (unfinished)

标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in AutoIt3, Technology | No Comments »

[原]Memory/logger leak with multiple VelocityEngine instances

Posted by bianbian on 2006-09-12 15:32


本文Tags:

之前有问过这个奇怪的问题,日志一直报错:
log4j:ERROR Attempted to append to closed appender named [null].

原来是velocity的bug,目前为止所有release都有这个bug (velocity的网站上说1.5版会fix这个bug)
> Key: VELOCITY-193
> URL: http://issues.apache.org/jira/browse/VELOCITY-193
> Project: Velocity
> Type: Bug
When creating and then releasing to garbage collection multiple VelocityEngine instances, the
instances are apparently not closing out or otherwise letting go of their logger instances. As a
result, code that needs to create and destroy several VelocityEngine instances will eventually choke and die. This happens with either Avalon Logkit or Log4j, although the exact nature of the choking differs. This test program isolates the problem:

import org.apache.velocity.app.VelocityEngine;
public class IsolateVelocityBug {
static public void main( String[] args ) {
int repCount = Integer.parseInt( args[0] );
for( int i = 0; i < repCount; i++ ) {
System.out.println( "Test repetition " + i + "..." );
try {
final VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.init();
} catch( Exception e ) {
throw new Error( e );
}
}
}
}

Run the program with an integer command-line argument specifying the number of times to cycle through the loop, and make sure velocity-1.3.1.jar, commons-collections.jar, and either an Avalon Logkit or Log4j JAR are on your classpath. (I tested with logkit-1.0.1.jar and log4j-1.1.3.jar.) What *should* happen is that the program completes its specified number of loops, doing nothing but writing “Test repetition” over and over with an incrementing number. What *does* happen, at least on my machine, depends on which logging package is provided for Velocity.

Using Avalon Logkit 1.0.1, the program runs fine for 252 iterations; on the 253nd, it aborts with
the following message:

“PANIC : Error configuring AvalonLogSystem : java.io.FileNotFoundException: /Users/ibeatty/
Development/javaDev/VelocityBugIsolator/velocity.log (Too many open files)”

Using Log4j 1.1.3, the program runs fine for only one iteration; on the second and any subsequent iterations, it continues but prints out a whole mess of

“log4j:ERROR Attempted to append to closed appender named [null].
log4j:WARN Not allowed to write to a closed appender.”

That happens for as long as I care to let it run (95 iterations, with something over 800 lines of
such errors per iteration by the end).

To me, it sure looks like Velocity is leaving dangling loggers behind as VelocityEngine instances
are created and discarded, and that the two logging systems respond differently to this but both have problems.

Why, might you ask, should anyone care about making many VelocityEngine instances? I ran into it when developing a major web app using JUnit to build comprehensive test suites. To run
independently, every test has to start from scratch, which means getting its own VelocityEngine.
Many tests means many instances, and the logging problem kicks in. Running JUnit test suites
within Intellij IDEA and using Log4j, the ERROR/WARN messages were more than a nuicanse;
eventually, I’d start getting out-of-memory errors, too. These went away when I changed the tests to use a shared VelocityEngine instance (which caused its own set of problems).

Using binary download of Velocity 1.3.1, which claims to have been created on 2003-04-01.

I find it hard to believe nobody else has tripped over this before, so maybe it’s sensitive to the OS or something. It happened whether I compiled the test code with Javac or Jikes. Using Java
1.4.1_01.

标签:

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Java, Technology | No Comments »

[原]Create Tree menu from HHC file automatically (HHC转为树形菜单)

Posted by bianbian on 2006-09-08 02:16


本文Tags: , ,

最近写了自动把HHC代码(HHC是CHM帮助文件过程中的目录结构描述文件)生成树形菜单,方便提供在线帮助手册;否则还得手动编写在线帮助的目录结构。支持IE和Firefox、Opera,其他浏览器未测试。使用也很简单,将下载的文件解压到images目录里,然后将HHC文件后缀改为htm(我们拿dir.htm举例),并添加两行代码既可:

sorry for my poor English: I wrote a script to change a HHC file(providing tree index file structure used by CHM-help-format) to tree menu. It's useful when providing online help after having produced CHM help, or you must produce a index-page manually - it's tedious, right? I tested it under IE 6.0, firefox 1.5, and Opera 0.9. It's also easy to use: you only need unzip it to "images" directory, change *.HHC file to *.HTM(dir.htm e.g.), and add two simple lines:

  1. <link type="text/css" rel="stylesheet" href="images/hhc_tree.css" />
  2. <script src="images/hhc_tree.js"></script>

当然了,你得增加个框架,左边引用dir.htm,右边是其他帮助文件。(我的代码会自动找到宽度最大的框架,并把树形菜单里的链接target指向这个框架,所以不用担心框架的命名问题,只要命名过就可以)。像这样:

sorry again: Certainly, you need add a frame page, dir.htm on left maybe, rightside is main help area. My script will set the links' target of tree menu with the frame's name which has the maximized width. So needn't care about the name of frames-but you must set one. like this:

  1. <html>
  2. <head><title>Online Help</title></head>
  3. <frameset cols="200,600">
  4.   <frame src="dir.htm" name="index">
  5.   <frame src="main.htm" name="main">
  6. </frameset>
  7. <body>
  8. <!--let search-engine work :)-->
  9. Your browser does not support frames: <a href="dir.htm">Index</a> <a href="main.htm">Main</a>
  10. </body>
  11. </html>

没有版权,随意使用,代码内的作者不要删掉就可以。:)

sorry last: Copyleft, as long as the author-line remains unchanged.
download here: HHC to Tree Menu (2.5K)

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | 2 Comments »

[原] IE和Firefox在DOM解析childNodes上的不同

Posted by bianbian on 2006-09-07 18:25


本文Tags: , ,

一个问题困扰我,涉及到firstChild和lastChild的代码工作不正常。为了简单,我把问题抽象到下面这个代码,你猜点击按钮后的结果是什么?

  1. <html><body>
  2. <UL id="main">
  3.   <LI>1</LI>
  4.   <LI>2</LI>
  5. </UL>
  6. <input type=button value="click me!"
  7.   onclick="alert(document.getElementById('main').childNodes.length)">
  8. </body></html>

呵呵,在IE里提示2,在Firefox里提示5,这是怎么回事呢?UL下明明只有两个子节点,Firefox为什么提示5个子节点呢?通过查看IE和firefox的DOM结构,发现了问题的所在:
IE:IE Firefox:firefox
你也应该发现了吧?“#text”表示文本(实际是无意义的空格和换行等)在Firefox里也会被解析成一个节点,在IE里只有有实际意义的文本才会解析成“#text”。所以对firefox而言,上例中UL的fistChild并不是第一个LI,而是#text(UL和第一个LI之间的无意义文本),lastChild也并不是最后一个LI,而是最后一个LI和/UL之间的无意义文本。

解决办法是先用 .getElementsByTagName(”LI”) 得到所有LI的节点。我觉得firefox这样处理比较令程序员头痛,也没有必要。

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | 4 Comments »

[原] 解决UltraEdit在UTF-8编码上的bug

Posted by bianbian on 2006-09-06 16:50


本文Tags: , , , ,

我一直喜欢用UltraEdit,包括写JavaScript、HTML、python、C、JSP等等。不过UltraEdit在UTF-8的处理上有个奇怪的bug。不信你可以试一下:在记事本里输入

  1. <%@page language="java" contentType="text/html;charset=UTF-8">
  2. 测试一下中文,English,呵呵
  3. welcome to <a href="http://bianbian.org">http://bianbian.org</a>

保存,比如test.jsp。上面是很正常的一个JSP文件,现在用UltraEdit打开,你发现什么了?
我试了各种各样版本的UltraEdit,中文都是乱码。这是怎么回事呢?
后来我想了一下,用记事本保存的文件默认是ANSI格式的,也就是我们的test.jsp实际并不是UTF-8格式的;而第一行的“charset=UTF-8”只是告诉java我们输出的是UTF-8格式。可怜的UltraEdit看了这行字以为文件也是UTF-8格式的,所以显示都是乱码。我觉得很搞笑,文件格式当然要根据实际文件存储格式来确定,怎么可以反过来呢?所以我觉得是UltraEdit的bug,并写信给UltraEdit。他们的效率真高,我第二天早上就收到回信了,并解决了我这个问题(虽然我觉得他们不默认提供这个设置真是搞笑)。冲着他们的效率,我决定以后买个正版。。。。嗯,跑题了

解决办法就是打开UltraEdit安装路径下的Uedit32.ini(如果没有这个文件,那说明你的UltraEdit版本的ini不是放在安装路径下的,得去C:\Documents and Settings\(登录用户名,默认是Administrator)\Application Data\IDMComp\UltraEdit里面找一下),在[Settings]里加上一句“Detect UTF-8 String=0”即可(bianbian补充:在UltraEdit某版本之后,这个字符串改成了“Auto Detect UTF-8 String=0”;你可以两个都试一下,或者都填上去),意思是禁止UltraEdit检测可能标记UTF-8的字符串,这个选项在“配置”里是没有的(不然我也不会去找他们了,呵呵)。我也建议他们以后在配置里加上这个选项,他们说会考虑,不知道现在的版本里是否已经有了,呵呵。附信件:

Dear Yuelinniao,

Thanks for your message. If you don’t want the charset declaration to be
used to determine whether or not a file is in UTF-8 format there is a
setting you can add to your uedit32.ini file to help with this. If you
open the uedit32.ini file you may add this under the [Settings] section:

Detect UTF-8 String = 0

This will prevent the referenced line from determining if a file is
recognized as being in UTF-8 format. I believe this will help.

Thanks, Troy

bianbian wrote:

> Dear support,
>
> I write to report a bug, which is making me inconvenient.
>
> When I edit a jsp file, first line is like this:
> <%@page language="java" contentType="text/html;charset=UTF-8">
> ~~~~~~
> but the file is saved on disk in ANSI format. Ultraedit maybe thinks
> the file is in UTF-8 format, and all the Chinese words of the file is
> in a state of disorder.
>
> When I take the property “Auto recognize UTF-8 format” off, the file
> is showed correctly. But when I edit another really UTF-8 format file(
> the file
> saved on disk in UTF-8 format), it is wrong again.
>
> So maybe there is a bug when Ultraedit recognizing UTF-8 format (not
> depending on the really format saved on disk)?
>
> Sorry for my poor English.
>
> Best wishes.
> Yours,
> yuelinniao

标签: , , , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Technology, Windows | 15 Comments »

[原]AutoIt 3的GUI生成工具Koda

Posted by bianbian on 2006-09-06 03:00


本文Tags: , , ,

原来已经有这样的GUI工具了,界面跟我设想的居然一模一样:http://www.autoitscript.com/fileman/users/lookfar/formdesign.html
5555,真是郁闷,这个可能也参考了Handel,Handel真是牛X。
只好花了一点点时间把Koda汉化了一下(下载后存成lang_zhcn.xml到Koda的Language目录)。第一次翻译,大家见笑。
不过我用JavaScript做了把HHC文件(微软生成chm帮助文档时的目录结构文件)直接生成树状目录结构的网页,这样AutoIt3的在线文档就不会那么丑了。等完善一下再贴上来。

标签: , , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in AutoIt3, Technology | 2 Comments »

[原]AutoIt 3简介,决定翻译并开发GUI工具

Posted by bianbian on 2006-09-04 02:54


本文Tags: ,

http://www.autoitscript.com/autoit3/
用AutoIt 3花了4个小时,写了一个游戏的自动登录脚本(包括服务器端设置用户名/密码和客户端读取并解析用户名密码并自动登录)。第一次接触,感觉还不错,大部分时间花在GUI的位置调整上(感觉回到了调用WinAPI的年代,呵呵)。决定翻译并开发GUI工具。先开始翻译吧。^_^

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on 95, 98, ME, NT4, 2000, XP, 2003 out of the box with no annoying “runtimes” required! You can even make compiled executable scripts that can run without AutoIt being installed!

AutoIt was initially designed for PC “roll out” situations to reliably configure thousands of PCs, but with the arrival of v3 it has become a powerful language able to cope with most scripting needs.

AutoIt can:

  • Provide a general-purpose scripting language for all Windows versions
  • Simulate keystrokes (supports most keyboard layouts)
  • Simulate mouse movements and clicks
  • Move, resize and manipulate windows
  • Interact directly with “controls” on a window (set/get text from edit controls, check boxes and radio buttons, select items in drop-down lists, etc.)
  • Create complex user interfaces (GUIs)
  • Work with the clipboard to cut/paste text items
  • Provide a scriptable RunAs function for Windows 2000/XP/2003
标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in AutoIt3, Technology | No Comments »

[原]利用HttpServletResponseWrapper获取jsp输出内容

Posted by bianbian on 2006-08-29 19:17


本文Tags:

有时候我们需要得到某个jsp的输出内容。比如说在servlet里处理了Module Controller后,需要不同的jsp页面来展示view;又或者得到不同的模板内容(jsp本身可以作为模板语言)并将其缓冲到内存里。
利用 javax.servlet.http.HttpServletResponseWrapper 可以很好地实现我们所需要的功能。下面是使用方法:

  1. ....
  2. public static String getJspOutput(String jsppath, HttpServletRequest request, HttpServletResponse response)
  3.     throws Exception
  4. {
  5.     WrapperResponse wrapperResponse = new WrapperResponse(response);
  6.     request.getRequestDispatcher(jsppath).include(request, wrapperResponse);
  7.     return wrapperResponse.getContent();
  8. }

可以看到,使用起来还是挺方便的。getJspOutput(”/view/header.jsp”, request, response) 就完成了对”/view/header.jsp”的输出内容获取,之后可以进行其他操作。
附WrapperResponse类代码:

  1. import java.io.ByteArrayOutputStream;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.io.UnsupportedEncodingException;
  5.  
  6. import javax.servlet.ServletOutputStream;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpServletResponseWrapper
  9. /**
  10. * @see http://bianbian.sunshow.net/
  11. * @author dannyzhu, bianbian
  12. * @version 1.0
  13. */
  14. public class WrapperResponse extends HttpServletResponseWrapper
  15. {
  16.     private PrintWriter tmpWriter;
  17.     private ByteArrayOutputStream output;
  18.     private ByteArrayServletOutputStream servletOutput;
  19.  
  20.     public WrapperResponse(HttpServletResponse httpServletResponse)
  21.     {
  22.         super(httpServletResponse);
  23.         output = new ByteArrayOutputStream();
  24.         tmpWriter = new PrintWriter(output);
  25.         servletOutput = new ByteArrayServletOutputStream(output);
  26.     }
  27.  
  28.     public void finalize() throws Throwable
  29.     {
  30.         super.finalize();
  31.         servletOutput.close();
  32.         output.close();
  33.         tmpWriter.close();
  34.     }
  35.  
  36.     public String getContent()
  37.     {
  38.         try{
  39.             String s = output.toString("UTF-8");
  40.             reset();
  41.             return s;
  42.         } catch(UnsupportedEncodingException e) {
  43.             return "UnsupportedEncoding";
  44.         }
  45.     }
  46.  
  47.     public PrintWriter getWriter() throws IOException
  48.     {
  49.         // return servletResponse.getWriter();
  50.         return tmpWriter;
  51.     }
  52.  
  53.     public ServletOutputStream getOutputStream() throws IOException
  54.     {
  55.         return servletOutput;
  56.     }
  57.  
  58.     public byte[] toByteArray()
  59.     {
  60.         return output.toByteArray();
  61.     }
  62.  
  63.     public void flushBuffer() throws IOException
  64.     {
  65.         tmpWriter.flush();
  66.         servletOutput.flush();
  67.     }
  68.  
  69.     public void reset()
  70.     {
  71.         output.reset();
  72.     }
  73.  
  74.     public void close() throws IOException
  75.     {
  76.         tmpWriter.close();
  77.     }
  78.  
  79.     private static class ByteArrayServletOutputStream extends ServletOutputStream
  80.     {
  81.  
  82.         ByteArrayOutputStream baos;
  83.  
  84.         public ByteArrayServletOutputStream(ByteArrayOutputStream baos)
  85.         {
  86.             this.baos = baos;
  87.         }
  88.  
  89.         public void write(int i) throws IOException
  90.         {
  91.             baos.write(i);
  92.         }
  93.  
  94.     }
  95. }
标签:

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in Java, Technology | No Comments »

[原]利用JavaScript解析UBB标签生成HTML

Posted by bianbian on 2006-08-27 18:11


本文Tags: , ,

UBB标签作为HTML标签的安全替代,在网络上应用已经十分广泛。常规的做法是服务器端解析,这类代码几乎泛滥,我就不贴了。唯一的问题是比较耗服务器的CPU(字符串匹配、正则匹配),其实这种活我都喜欢让客户端做。

作为演示,我下面的代码将解析[b]、[i]、[url]、[img]、[color]、[wma]、[flash]这几个常见的UBB标签。主要利用了JavaScript的正则表达式。正则表达式语法可以察看:正则表达式语法,下面代码的测试可以察看:测试UBB标签解析

  1. function text2html(s)
  2. {
  3.     if(s.indexOf("://") > 0)
  4.     {
  5.         //url
  6.         s = s.replace(/(^|[^\"\'\]])(http|ftp|mms|rstp|news|https)\:\/\/([^\s\033\[\]\"\']+)/gi, "$1[url]$2://$3[/url]");
  7.         //img
  8.         s = s.replace(/\[url\](http\:\/\/\S+\.)(gif|jpg|jpeg|png)\[\/url\]/gi, "[img]$1$2[/img]");
  9.     }
  10.     //ubb: 匹配[UBB]...[/UBB]形式
  11.     if(s.match(/\[(\w+)([^\[\]\s]*)\].*\[\/\1\]/))
  12.     {
  13.         s = s.replace(/\[url\](.+?)\[\/url\]/gi,"<a href=$1 target=_blank>$1</a>");
  14.         s = s.replace(/\[img\](.+?\.(?:gif|jpg|jpeg|png))\[\/img\]/gi, "<img src='$1' alt='$1'>");
  15.         s = s.replace(/\[flash\](.+?\.swf)\[\/flash\]/gi, "<embed src='$1' quality=high wmode=transparent type='application/x-shockwave-flash' width=400 height=300></embed><br> FLASH: <a href='$1' target=_blank>$1</a><br>");
  16.         s = s.replace(/\[wma\](.+?\.(?:wma|mp3))\[\/wma\]/gi, "<embed src='$1' height=40 AutoStart=0></embed><br> WMA: <a href='$1' target=_blank>$1</a><br>");
  17.         s = s.replace(/\[color=([#0-9a-zA-Z]{1,10})\](.+?)\[\/color\]/gi, "<font color='$1'>$2</font>");
  18.         s = s.replace(/\[b\](.+?)\[\/b\]/gi, "<b>$1</b>");
  19.         s = s.replace(/\[i\](.+?)\[\/i\]/gi, "<i>$1</i>");
  20.     }
  21.     return s;
  22. }

接下来的问题是怎样把文本传递到函数里,一个自己的经验是把待解析的文本放到textarea里,这样可以避免<和>等特殊符号的转义(即&lt;、&gt;),放到textarea里转义的工作就自动被浏览器做了。

唯一的也是比较严重的问题是待解析的文本里不能有“</textarea>”,否则浏览器会认为本文已经结束,其后的文本将被浏览器当成HTML代码——这是很危险的,想想看,用户输入“</textarea>”之后就可以插入任何HTML代码!解决的办法是服务器端输出文本内容的时候,将“</textarea”拆开,比如输出“< /textarea”或“</text area”都是可以的。要注意,不能整个搜寻替换“</textarea>”,因为有可能别有用心的用户会输入“</textarea >”,这会带来同样的问题(最近部分小百合用户的说明档被改就是因为这个漏洞)。也许你会问,这样不是服务器端每次生成页面的时候又进行字符串匹配了吗?对性能有什么提高呢?OK,我们可以在用户提交数据的时候进行这样的替换,“绝对不要相信客户端”,这是一个web程序员应该具有的基本观念。

标签: , ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | 2 Comments »

[原]小心使用JavaScript的局部和全局变量

Posted by bianbian on 2006-08-26 22:44


本文Tags: ,

一直以为自己对JavaScript已经很精通了,这次却犯了一个低级错误。这个错误带来的后果就是:如果你最近用浏览器上小百合的话,发现点击左边导航菜单的链接都会打开新窗口。。。其次的后果是害我调试了一下午加晚上。。。

先是这样的,为了DOM设置属性的方便,我自己写了个方法,省得每次都setAttribute:

  1. Net = {};
  2. Net.Dom = {};
  3. Net.Dom.setProperties = function(obj)
  4. {
  5.     for(var i=1; i<arguments.length; i++)
  6.     {
  7.         if(typeof arguments[i]=="object")
  8.         {
  9.             for(name in arguments[i])
  10.                 obj[name] = arguments[i][name];
  11.         }
  12.     }
  13. }
  14.  
  15. //这样原来:
  16. div.setAttribute("width", "100px");
  17. div.setAttribute("height", "100%");
  18. ......
  19. //就可以写成:
  20. Net.Dom.setProperties(div, {width:"100px", height: "100%"});

上面的setProperties代码里面有个错误,会导致改变window的name属性。因为window是可以省略的(直接打document其实是window.document),而“for(name in arguments[i])”的表示方法浏览器会解析成“for(window.name in arguments[i])”。也就是框架的name变了,这样左边设的target自然就失效了,导致链接都以新窗口打开。改成“for(var name in arguments[i])”就好了。

因为JavaScript相对比较自由,写变量一定要注意,而且这种错误比较隐蔽,难以发现。局部变量一定要以var申明,否则是全局变量;要用全局变量时候也要注意一下命名方法,以”g_”开头或者全大写都是可行的办法。

最后我们一起复习一下JavaScript的局部变量和全局变量:
Read the rest of this entry »

标签: ,

遵守创作共用协议,转载请链接形式注明来自http://bianbian.org 做人要厚道

相关日志

Posted in JavaScript, Technology | 1 Comment »

Page 13 of 14«1234567891011121314»