Flash中有两个提供低层网络通信功能的类,Socket,XMLSocket . XMLSocket传输的是文本形式的xml字符串数据,每个数据单元以 0 结束. Socket可以传输任意类型的数据.
Flash 的安全模型下,缺省情况下,Socket 和XMLSocket只能连接到和swf文件同一个域上的大于1024的端口,但有些应用需要访问webserver之外的服务器上的端口,或者访问小于1024的端口,为了达到这种目的,需要使用安全策略文件,并在服务器端使用XMLSocket的协议提供这个安全策略文件.flash 在连接目标端口之前会先向策略服务端口发送一个请求:
“<policy-file-request/>”,策略服务接收到这个请求后需要返回一个策略文档,最后以0结束,当flash接收到 0时,会自动切断与策略服务的连接,并根据策略文件中的规则决定是否允许与目标端口连接.安全策略文件是一个xml格式的文档,例如:
- <SPAN style="FONT-SIZE: small"><cross-domain-policy>
- <allow-access-from domain="*" to-ports="507" />
- <allow-access-from domain="*.example.com" to-ports="507,516" />
- <allow-access-from domain="*.example.org" to-ports="516-523" />
- <allow-access-from domain="adobe.com" to-ports="507,516-523" />
- <allow-access-from domain="192.0.34.166" to-ports="*" />
- </cross-domain-policy>
- </SPAN>
并且flash安全策略规定,如果这个文档是在小于1024的端口上提供,那么可以授权对所有端口的访问权限,如果在大于1024的端口上提供,则只能授权对大于1024的端口的访问权限.因此如果我们想要访问某台服务器上的任意端口的话,就需要在该服务器某个小于1024的端口上以XMLSocket的方式提供一个安全策略文件.
网上google了一把,发现没有类似功能的组件,于是自己动手写了一个,使用的网络框架是mina2.0m1,感谢mina提供的强大功能,我们只需要两个java类,数十行代码就可以完成一个简单的安全策略服务器.(本来xml文档识别的代码应该作为一个mina 的codec来开发,但因为这个例子的功能很简单,所以就偷了个懒,直接在IoHandler中处理了).代码如下:
XmlSocketServer.java
- <SPAN style="FONT-SIZE: small">package net.mudfan.xmlsocket;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import org.apache.mina.common.DefaultIoFilterChainBuilder;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
- import org.apache.mina.transport.socket.SocketAcceptor;
- import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
- /**
- *
- * @author yunchang Yuan
- */
- public class XmlSocketServer {
- private static final int PORT = 888;
- public static void main(String[] args) throws Exception{
- SocketAcceptor acceptor = new NioSocketAcceptor();
- DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
- acceptor.setHandler(new XmlSocketHandler());
- acceptor.bind(new InetSocketAddress(PORT));
- System.out.println("Listening on port " + PORT);
- }
- }
- </SPAN>
package net.mudfan.xmlsocket;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
/**
*
* @author yunchang Yuan
*/
public class XmlSocketServer {
private static final int PORT = 888;
public static void main(String[] args) throws Exception{
SocketAcceptor acceptor = new NioSocketAcceptor();
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
acceptor.setHandler(new XmlSocketHandler());
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Listening on port " + PORT);
}
}
XmlSocketHandler.java
- <SPAN style="FONT-SIZE: small">package net.mudfan.xmlsocket;
- import java.io.UnsupportedEncodingException;
- import org.apache.mina.common.IdleStatus;
- import org.apache.mina.common.IoBuffer;
- import org.apache.mina.common.IoHandlerAdapter;
- import org.apache.mina.common.IoSession;
- import org.dom4j.Document;
- import org.dom4j.DocumentHelper;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- /**
- *
- * @author yunchang Yuan
- */
- public class XmlSocketHandler extends IoHandlerAdapter{
- static Logger logger = LoggerFactory.getLogger(XmlSocketHandler.class);
- static String security_req = "<policy-file-request/>";
- static String allow_all = "<cross-domain-policy>/n"+
- " <allow-access-from domain=/"*/" to-ports=/"*/" />/n"+
- "</cross-domain-policy>";
- @Override
- public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
- super.exceptionCaught(arg0, arg1);
- }
- @Override
- public void messageReceived(IoSession arg0, Object arg1) throws Exception {
- IoBuffer buf = (IoBuffer)arg1;
- IoBuffer processBuf = (IoBuffer)arg0.getAttribute("processBuf");
- processBuf.put(buf);
- processBuf.flip();
- String req = getReq(processBuf);
- if(req!=null){
- if(security_req.equals(req)){
- logger.info("get security req,now send policy file");
- byte[] reps = allow_all.getBytes("UTF-8");
- IoBuffer wb = IoBuffer.allocate(reps.length+1);
- wb.put(reps);
- wb.put((byte)0x0);
- wb.flip();
- arg0.write(wb);
- arg0.setAttribute("policySend", true) ;
- }
- }
- }
- @Override
- public void messageSent(IoSession arg0, Object arg1) throws Exception {
- logger.info("messageSent");
- arg0.close();
- }
- @Override
- public void sessionClosed(IoSession arg0) throws Exception {
- logger.info("sessionClosed");
- super.sessionClosed(arg0);
- arg0.removeAttribute("processBuf");
- }
- @Override
- public void sessionCreated(IoSession arg0) throws Exception {
- super.sessionCreated(arg0);
- IoBuffer processBuf = IoBuffer.allocate(64);
- arg0.setAttribute("processBuf", processBuf);
- }
- @Override
- public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
- super.sessionIdle(arg0, arg1);
- }
- @Override
- public void sessionOpened(IoSession arg0) throws Exception {
- super.sessionOpened(arg0);
- }
- private String getReq(IoBuffer buf) {
- IoBuffer reqbuf = IoBuffer.allocate(64);
- boolean found = false;
- for(int i=0;i<buf.limit();i++){
- byte data = buf.get();
- if(data!=0){
- reqbuf.put(data);
- }else{
- found = true;
- break;
- }
- }
- if(found){
- logger.info("get xml document");
- reqbuf.flip();
- buf.compact();
- try {
- byte[] strbuf = new byte[reqbuf.limit()];
- reqbuf.get(strbuf,0,reqbuf.limit());
- String req = new String(strbuf, "UTF-8");
- logger.info("req is :"+req);
- return req;
- } catch (UnsupportedEncodingException ex) {
- logger.error("encoding error");
- return null;
- }
- }else{
- return null;
- }
- }
- }
- </SPAN>
package net.mudfan.xmlsocket;
import java.io.UnsupportedEncodingException;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author yunchang Yuan
*/
public class XmlSocketHandler extends IoHandlerAdapter{
static Logger logger = LoggerFactory.getLogger(XmlSocketHandler.class);
static String security_req = "<policy-file-request/>";
static String allow_all = "<cross-domain-policy>/n"+
" <allow-access-from domain=/"*/" to-ports=/"*/" />/n"+
"</cross-domain-policy>";
@Override
public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
super.exceptionCaught(arg0, arg1);
}
@Override
public void messageReceived(IoSession arg0, Object arg1) throws Exception {
IoBuffer buf = (IoBuffer)arg1;
IoBuffer processBuf = (IoBuffer)arg0.getAttribute("processBuf");
processBuf.put(buf);
processBuf.flip();
String req = getReq(processBuf);
if(req!=null){
if(security_req.equals(req)){
logger.info("get security req,now send policy file");
byte[] reps = allow_all.getBytes("UTF-8");
IoBuffer wb = IoBuffer.allocate(reps.length+1);
wb.put(reps);
wb.put((byte)0x0);
wb.flip();
arg0.write(wb);
arg0.setAttribute("policySend", true) ;
}
}
}
@Override
public void messageSent(IoSession arg0, Object arg1) throws Exception {
logger.info("messageSent");
arg0.close();
}
@Override
public void sessionClosed(IoSession arg0) throws Exception {
logger.info("sessionClosed");
super.sessionClosed(arg0);
arg0.removeAttribute("processBuf");
}
@Override
public void sessionCreated(IoSession arg0) throws Exception {
super.sessionCreated(arg0);
IoBuffer processBuf = IoBuffer.allocate(64);
arg0.setAttribute("processBuf", processBuf);
}
@Override
public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
super.sessionIdle(arg0, arg1);
}
@Override
public void sessionOpened(IoSession arg0) throws Exception {
super.sessionOpened(arg0);
}
private String getReq(IoBuffer buf) {
IoBuffer reqbuf = IoBuffer.allocate(64);
boolean found = false;
for(int i=0;i<buf.limit();i++){
byte data = buf.get();
if(data!=0){
reqbuf.put(data);
}else{
found = true;
break;
}
}
if(found){
logger.info("get xml document");
reqbuf.flip();
buf.compact();
try {
byte[] strbuf = new byte[reqbuf.limit()];
reqbuf.get(strbuf,0,reqbuf.limit());
String req = new String(strbuf, "UTF-8");
logger.info("req is :"+req);
return req;
} catch (UnsupportedEncodingException ex) {
logger.error("encoding error");
return null;
}
}else{
return null;
}
}
}
上面代码中用到的外部库,mina 2.0m1, sl4j1.5. 上述代码运行后在服务器的888端口上等待策略文件的请求,在flash代码中socket.connect() 调用之前加上 :
Security.loadPolicyFile("xmlsocket://host:888”); 这样,就可以让服务器上的所有端口被flash 连接了.如果要进行某种限制,修改策略文件即可. 当然也可以在此基础上扩展,从外部读取策略配置.
以上适用as3 的所有环境,包括flash 9+,flex2,flex3