首页 > 编程 > .NET > 正文

asp.net防盗链源码

2024-07-10 13:12:18
字体:
来源:转载
供稿:网友
国内最大的酷站演示中心!


/**//*
 * 
 * 防盗链ihttphandler
 * 
 * 
 * 增加了对文件关键字的选择(即仅对文件名存在某些关键字或不存在某些关键字进行过滤)
 * 设置web.config中<appsettings>节以下值
 * string ewebapp_nolink    如果文件名符合该正确表态式将进行过滤(不设置对所有进行过滤)
 * string ewebapp_allowlink            如果文件名符合该正确表态式将不进行过滤(优先权高于allowlink,不设置则服从allowlink)
 * bool ewebapp_ allowonlyfile        如果为false,(默认true)则不允许用户直接对该文件进行访问建议为true
 * 
 * 
 * :)以下设置均可省略,设置只是为了增加灵活性与体验
 * ewebapp_nolink_message    错误信息提示:默认为link from:域名
 * ewebapp_error_width        错误信息提示图片宽
 * ewebapp_error_height        错误信息提示图片高
 * 
 * 
 * 
 * 垃圾猪 2005-9-11 创建
 * http://ewebapp.net 
 */


using system;
using system.web;
using system.drawing;
using system.drawing.imaging;
using system.io;
using system.configuration;
using system.text.regularexpressions;

namespace ewebapp
...{
    /**//// <summary>
    /// 防盗链ihttphandler
    /// 参考http://www.softat.org/archiver/tid-52114.html
    /// 垃圾猪  2005-9-12 修正
    /// </summary>
    public class nolink : ihttphandler
    ...{
        private string ewebapp_nolink = string.empty;
        private string ewebapp_allowlink = string.empty;
        private bool ewebapp_allowonlyfile = true;

        private string ewebapp_nolink_message = string.empty;
        private bool error = false;

        public nolink()
        ...{
            //
            // todo: 在此处添加构造函数逻辑
            //
        }

        public void processrequest(httpcontext context)
        ...{
            ewebapp_nolink_message = configurationsettings.appsettings["ewebapp_nolink_message"];
            
            
            string mydomain = string.empty;

            error = errorlink(context,out mydomain);    

            if(empty(ewebapp_nolink_message)) 
            ...{
                ewebapp_nolink_message = "link from :" + mydomain;
            }

 

            if(error)
            ...{
                //jpg(context.response,ewebapp_nolink_message);
                jpg(context.response,ewebapp_nolink_message);
            }
            else
            ...{
                 real(context.response,context.request);
            }

        }

        public bool isreusable
        ...{
            get

            ...{
                return true;
            }
        }


        /**//// <summary>
        /// 输出错误信息
        /// </summary>
        /// <param name="response"></param>
        /// <param name="_word"></param>
        private void jpg(httpresponse response,string _word) 
        ...{


            int myerrorwidth = _word.length*15;
            int myerrorheight = 16;
            try
            ...{
                int _myerrorwidth = convert.toint32(configurationsettings.appsettings["ewebapp_error_width"]);
                if(_myerrorwidth > 0 )
                ...{
                    myerrorwidth = _myerrorwidth;
                }

            }
            catch
            ...{

            }
            try
            ...{
                int _myerrorheight = convert.toint32(configurationsettings.appsettings["ewebapp_error_height"]);
                if(_myerrorheight  > 0 )
                ...{
                    myerrorheight = _myerrorheight;
                }
            }
            catch
            ...{

            }
            bitmap img=null;
            graphics g=null;
            memorystream ms=null;
            img=new bitmap(myerrorwidth,myerrorheight);
            g=graphics.fromimage(img);
            g.clear(color.white);
            font f=new font("arial",9);
            solidbrush s=new solidbrush(color.red);
            g.drawstring(_word,f,s,3,3);
            ms=new memorystream();
            img.save(ms,imageformat.jpeg);
            response.clearcontent(); 
            response.contenttype="image/gif";
            response.binarywrite(ms.toarray());
            g.dispose();
            img.dispose();
            response.end();
        }

        /**//// <summary>
        /// 输出真实文件
        /// </summary>
        /// <param name="response"></param>
        /// <param name="context"></param>
        private void real(httpresponse response,httprequest request)
        ...{
            fileinfo file = new system.io.fileinfo(request.physicalpath);

            response.clear();

            response.addheader("content-disposition", "filename=" + file.name);

            response.addheader("content-length", file.length.tostring());

            string fileextension = file.extension.tolower();


            //这里选择输出的文件格式
            //可以参考http://ewebapp.cnblogs.com/articles/234756.html增加对更多文件格式的支持.

            
            switch (fileextension)
            ...{

                case "mp3":
                    response.contenttype = "audio/mpeg3";
                    break;

                case "mpeg":

                    response.contenttype = "video/mpeg";
                    break;

                case "jpg":

                    response.contenttype = "image/jpeg";
                    break;

                case "bmp":

                    response.contenttype = "image/bmp";
                    break;

                case "gif":

                    response.contenttype = "image/gif";
                    break;

                case "doc":

                    response.contenttype = "application/msword";

                    break;
                case "css":

                    response.contenttype = "text/css";
                    break;

                default:

                    response.contenttype = "application/octet-stream";
                    break;

            }
            

            response.writefile(file.fullname);

            response.end();
        }


        /**//// <summary>
        /// 确认字符串是否为空
        /// </summary>
        /// <param name="_value"></param>
        /// <returns></returns>
        private bool empty(string _value)
        ...{
            if(_value == null | _value == string.empty | _value == "")
            ...{
                return true;
            }
            else
            ...{
                return false;
            }
        }


        /**//// <summary>
        /// 检查是否是非法链接
        /// </summary>
        /// <param name="context"></param>
        /// <param name="_mydomain"></param>
        /// <returns></returns>
        private bool errorlink(httpcontext context,out string _mydomain)
        ...{
            httpresponse response = context.response;
            string mydomain = context.request.servervariables["server_name"];
            _mydomain = mydomain ;
            string mydomainip = context.request.userhostaddress;


            ewebapp_nolink = configurationsettings.appsettings["ewebapp_nolink"];
            ewebapp_allowlink = configurationsettings.appsettings["ewebapp_allowlink"];

            try
            ...{
                ewebapp_allowonlyfile = convert.toboolean(configurationsettings.appsettings["ewebapp_allowonlyfile"]);
            }
            catch
            ...{
                ewebapp_allowonlyfile = true;
            }


            if(context.request.urlreferrer != null)
            ...{

                
                //判定referdomain是否存在网站的ip或域名
                string referdomain = context.request.urlreferrer.absoluteuri.replace(context.request.urlreferrer.absolutepath,"");
                string mypath  = context.request.rawurl;

                if(referdomain.indexof(mydomainip) >=0 | referdomain.indexof(mydomain)>=0)
                ...{
                    return false;
                }
                else
                ...{
                    //这里使用正则表达对规则进行匹配
                    try
                    ...{
                        regex myregex ;

                        //检查允许匹配
                        if(!empty(ewebapp_allowlink))
                        ...{
                            
                            myregex = new regex(ewebapp_allowlink);

                            if(myregex.ismatch(mypath))
                            ...{
                                return false;
                            }

                        }


                        //检查禁止匹配
                        if(!empty(ewebapp_nolink))
                        ...{

                            myregex = new regex(ewebapp_nolink);
                            if(myregex.ismatch(mypath))
                            ...{
                                return true;
                            }
                            else
                            ...{
                                return false;
                            }

                        }

                        return true;

                    }
                    catch
                    ...{
                        //如果匹配出错,链接错误
                        return true;
                    }
                }
            }
            else
            ...{
                //是否允许直接访问文件
                if(ewebapp_allowonlyfile)
                ...{
                    return false;
                }
                else
                ...{
                    return true;
                }
            }

        }

    }

}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表