001    package railo.runtime.type.scope;
002    
003    import java.net.InetAddress;
004    import java.net.UnknownHostException;
005    import java.util.Enumeration;
006    import java.util.Iterator;
007    
008    import javax.servlet.http.HttpServletRequest;
009    
010    import railo.commons.io.res.util.ResourceUtil;
011    import railo.commons.lang.StringUtil;
012    import railo.runtime.PageContext;
013    import railo.runtime.dump.DumpData;
014    import railo.runtime.dump.DumpProperties;
015    import railo.runtime.op.Caster;
016    import railo.runtime.security.ScriptProtect;
017    import railo.runtime.type.Collection;
018    import railo.runtime.type.KeyImpl;
019    import railo.runtime.type.ReadOnlyStruct;
020    import railo.runtime.type.Struct;
021    import railo.runtime.type.StructImpl;
022    import railo.runtime.type.it.KeyIterator;
023    import railo.runtime.type.util.KeyConstants;
024    import railo.runtime.type.util.StructUtil;
025    import railo.runtime.util.ApplicationContext;
026    
027    /**
028     *
029     *
030     * To change the template for this generated type comment go to
031     * Window - Preferences - Java - Code Generation - Code and Comments
032     */
033    public final class CGIImpl extends ReadOnlyStruct implements CGI,ScriptProtected {
034            
035            private static final String[] keys={
036                            "auth_password", "auth_type", "auth_user", "cert_cookie", "cert_flags", "cert_issuer"
037                            , "cert_keysize", "cert_secretkeysize", "cert_serialnumber", "cert_server_issuer", "cert_server_subject", "cert_subject"
038                            , "cf_template_path", "content_length", "content_type", "gateway_interface", "http_accept", "http_accept_encoding"
039                            , "http_accept_language", "http_connection", "http_cookie", "http_host", "http_user_agent", "http_referer"
040                            , "https", "https_keysize", "https_secretkeysize", "https_server_issuer", "https_server_subject", "path_info"
041                            , "path_translated", "query_string", "remote_addr", "remote_host", "remote_user", "request_method"
042                            , "script_name", "server_name", "server_port", "server_port_secure", "server_protocol", "server_software"
043                , "web_server_api", "context_path"
044                , "local_addr", "local_host"
045            };
046    
047            public static final Collection.Key SCRIPT_NAME = KeyImpl.intern("script_name");
048            public static final Collection.Key PATH_INFO = KeyImpl.intern("path_info");
049            public static final Collection.Key HTTP_IF_MODIFIED_SINCE = KeyImpl.intern("http_if_modified_since");
050            public static final Collection.Key AUTH_TYPE = KeyImpl.intern("auth_type");
051            public static final Collection.Key CF_TEMPLATE_PATH = KeyImpl.intern("cf_template_path");
052            public static final Collection.Key REMOTE_USER = KeyImpl.intern("remote_user");
053            public static final Collection.Key REMOTE_ADDR = KeyImpl.intern("remote_addr");
054            public static final Collection.Key REMOTE_HOST = KeyImpl.intern("remote_host");
055            public static final Collection.Key REQUEST_METHOD = KeyImpl.intern("request_method");
056            public static final Collection.Key REQUEST_URI = KeyImpl.intern("request_uri");
057            public static final Collection.Key REDIRECT_URL = KeyImpl.intern("REDIRECT_URL");
058            public static final Collection.Key REDIRECT_QUERY_STRING = KeyImpl.intern("REDIRECT_QUERY_STRING");
059            
060            
061            
062            public static final Collection.Key LOCAL_ADDR = KeyImpl.intern("local_addr");
063            public static final Collection.Key LOCAL_HOST = KeyImpl.intern("local_host");
064            public static final Collection.Key SERVER_NAME = KeyImpl.intern("server_name");
065            public static final Collection.Key SERVER_PROTOCOL = KeyImpl.intern("server_protocol");
066            public static final Collection.Key SERVER_PORT = KeyImpl.intern("server_port");
067            public static final Collection.Key SERVER_PORT_SECURE = KeyImpl.intern("server_port_secure");
068            public static final Collection.Key PATH_TRANSLATED = KeyImpl.intern("path_translated");
069            public static final Collection.Key QUERY_STRING = KeyImpl.intern("query_string");
070            public static final Collection.Key CONTEXT_PATH = KeyImpl.intern("context_path");
071            public static final Collection.Key LAST_MODIFIED = KeyImpl.intern("last_modified");
072            
073            
074            private static Struct staticKeys=new StructImpl();
075            static{
076                    for(int i=0;i<keys.length;i++){
077                            staticKeys.setEL(KeyImpl.getInstance(keys[i]),"");
078                    }
079            }
080            
081            private static String localAddress="";
082            private static String localHost="";
083            
084            static {
085                    try {
086                            InetAddress addr = InetAddress.getLocalHost();
087                            localAddress=addr.getHostAddress();
088                            localHost=addr.getHostName();
089                    }
090                    catch(UnknownHostException uhe) {}
091            }
092            
093            private HttpServletRequest req;
094            private boolean isInit;
095            //private String strBaseFile="fsfd";
096            private PageContext pc;
097            private Struct https;
098            private Struct headers;
099            private int scriptProtected;
100            
101            
102            public CGIImpl(){
103                    this.setReadOnly(true);
104            }
105            
106    
107            /**
108             * @see railo.runtime.type.StructImpl#containsKey(railo.runtime.type.Collection.Key)
109             */
110            public boolean containsKey(Key key) {
111                    return staticKeys.containsKey(key);
112            }
113            
114            /**
115             * @see railo.runtime.type.StructImpl#containsValue(java.lang.Object)
116             */
117            public boolean containsValue(Object value) {
118                    // TODO Auto-generated method stub
119                    return super.containsValue(value);
120            }
121            /**
122             * @see railo.runtime.type.StructImpl#duplicate(boolean)
123             */
124            public Collection duplicate(boolean deepCopy) {
125                    Struct sct=new StructImpl();
126                    copy(this,sct,deepCopy);
127                    return sct;
128            }
129            
130            
131            /**
132             * @see railo.runtime.type.Collection#size()
133             */
134            public int size() {
135                    return keys.length;
136            }
137            /**
138             * @see railo.runtime.type.Collection#keysAsString()
139             */
140            public String[] keysAsString() {
141                    return keys;
142            }
143    
144            public Collection.Key[] keys() {
145                    return StructUtil.toCollectionKeys(keys);
146            }
147            
148            /**
149             *
150             * @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key, java.lang.Object)
151             */
152            public Object get(Collection.Key key, Object defaultValue) {
153    
154                    if(req==null) {
155                            req=pc. getHttpServletRequest();
156                            
157                            https=new StructImpl();
158                            headers=new StructImpl();
159                            String k,v;
160                            try {
161                                    Enumeration e = req.getHeaderNames();
162                            
163                                    while(e.hasMoreElements()) {
164                                    k = (String)e.nextElement();
165                                    v = req.getHeader(k);
166                                    //print.err(k.length()+":"+k);
167                                    headers.setEL(KeyImpl.init(k),v);
168                                    headers.setEL(KeyImpl.init(k=k.replace('-','_')),v);
169                                    https.setEL(KeyImpl.init("http_"+k),v); 
170                            }
171                            }
172                            catch(Throwable t){t.printStackTrace();}
173                    }
174                    String lkey=key.getLowerString();
175            
176                
177            if(lkey.length()>7) {
178                char first=lkey.charAt(0);
179                if(first=='a') {
180                    if(key.equals(AUTH_TYPE)) return toString(req.getAuthType());
181                }
182                else if(first=='c') {
183                    if(key.equals(CONTEXT_PATH))return toString(req.getContextPath());
184                    if(key.equals(CF_TEMPLATE_PATH)) {
185                                            try {
186                                                    return toString(ResourceUtil.getResource(pc, pc.getBasePageSource()));
187                                            } catch (Throwable t) {
188                                                    return "";
189                                            }
190                    }
191                }
192                else if(first=='h') {
193                    if(lkey.startsWith("http_")){
194                            Object o = https.get(key,null);
195                        if(o==null && key.equals(HTTP_IF_MODIFIED_SINCE))
196                            o = https.get(LAST_MODIFIED,null);
197                        if(o!=null)return doScriptProtect((String)o);
198                }
199                }
200                else if(first=='r') {
201                    if(key.equals(REMOTE_USER))             return toString(req.getRemoteUser());
202                    if(key.equals(REMOTE_ADDR))             return toString(req.getRemoteAddr());
203                    if(key.equals(REMOTE_HOST))             return toString(req.getRemoteHost());
204                    if(key.equals(REQUEST_METHOD))          return req.getMethod();
205                    if(key.equals(REQUEST_URI))             return toString(req.getAttribute("javax.servlet.include.request_uri"));
206                    if(key.getUpperString().startsWith("REDIRECT_")){
207                            // from attributes (key sensitive)
208                            Object value = req.getAttribute(key.getString());
209                            if(!StringUtil.isEmpty(value)) return toString(value);
210                            
211                            // from attributes (key insensitive)
212                            Enumeration<String> names = req.getAttributeNames();
213                            String k;
214                            while(names.hasMoreElements()){
215                                    k=names.nextElement();
216                                    if(k.equalsIgnoreCase(key.getString())) {
217                                            return toString(req.getAttribute(k));
218                                    }
219                            }
220                    }
221                }
222                
223                
224                else if(first=='l') {
225                    if(key.equals(LOCAL_ADDR))              return toString(localAddress);
226                    if(key.equals(LOCAL_HOST))              return toString(localHost);
227                }
228                else if(first=='s') {
229                    if(key.equals(SCRIPT_NAME)) 
230                                    return StringUtil.emptyIfNull(req.getContextPath())+StringUtil.emptyIfNull(req.getServletPath());
231                            if(key.equals(SERVER_NAME))             return toString(req.getServerName());
232                    if(key.equals(SERVER_PROTOCOL)) return toString(req.getProtocol());
233                    if(key.equals(SERVER_PORT))             return Caster.toString(req.getServerPort());
234                    if(key.equals(SERVER_PORT_SECURE))return req.isSecure()?"1":"0";
235                    
236                }
237                else if(first=='p') {
238                    if(key.equals(KeyConstants._path_info)) {
239                            String pathInfo = Caster.toString(req.getAttribute("javax.servlet.include.path_info"),null);
240                            if(StringUtil.isEmpty(pathInfo)) pathInfo = Caster.toString(req.getHeader("xajp-path-info"),null);
241                            if(StringUtil.isEmpty(pathInfo)) pathInfo = req.getPathInfo();
242                        
243                            if(!StringUtil.isEmpty(pathInfo,true)) return pathInfo;
244                        return "";
245                    }
246                    if(key.equals(PATH_TRANSLATED)) {
247                            try {
248                                                    return toString(ResourceUtil.getResource(pc, pc.getBasePageSource()));
249                                            } catch (Throwable t) {
250                                                    return "";
251                                            }//toString(req.getServletPath());
252                    }
253                }
254                else if(first=='q') {
255                    if(key.equals(QUERY_STRING))return doScriptProtect(toString(req.getQueryString()));
256                }
257            }
258            
259            // check header
260            String headerValue = (String) headers.get(key,null);//req.getHeader(key.getString());
261                if(headerValue != null) return doScriptProtect(headerValue);
262                
263            return other(key,defaultValue);
264            }
265            
266            private Object other(Collection.Key key, Object defaultValue) {
267                    if(staticKeys.containsKey(key)) return "";
268                    return defaultValue;
269            }
270            
271            private String doScriptProtect(String value) {
272                    if(isScriptProtected()) return ScriptProtect.translate(value);
273                    return value;
274            }
275            
276            private String toString(Object str) {
277                    return StringUtil.toStringEmptyIfNull(str);
278            }
279            
280            /**
281             *
282             * @see railo.runtime.type.StructImpl#get(railo.runtime.type.Collection.Key)
283             */
284            public Object get(Collection.Key key) {
285                    Object value=get(key,"");
286                    if(value==null)value= "";
287                    return value;
288            }
289            
290            /**
291             * @see railo.runtime.type.Collection#keyIterator()
292             */
293            public Iterator keyIterator() {
294                    return new KeyIterator(keys());
295            }
296            
297            /**
298             * @see railo.runtime.type.Scope#isInitalized()
299             */
300            public boolean isInitalized() {
301                    return isInit;
302            }
303            
304            /**
305             * @see railo.runtime.type.Scope#initialize(railo.runtime.PageContext)
306             */
307            public void initialize(PageContext pc) {
308                    isInit=true;
309                    this.pc=pc;
310    
311            if(scriptProtected==ScriptProtected.UNDEFINED) {
312                            scriptProtected=((pc.getApplicationContext().getScriptProtect()&ApplicationContext.SCRIPT_PROTECT_CGI)>0)?
313                                            ScriptProtected.YES:ScriptProtected.NO;
314                    }
315            }
316            
317            /**
318             * @see railo.runtime.type.Scope#release()
319             */
320            public void release() {
321                    isInit=false;
322                    this.req=null;
323                    scriptProtected=ScriptProtected.UNDEFINED; 
324                    pc=null;
325                    https=null;
326                    headers=null;
327            }
328            
329            /**
330             * @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int)
331             */
332            public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
333                    return StructUtil.toDumpTable(this, "CGI Scope", pageContext, maxlevel, dp);
334            }
335        
336        /**
337         * @see railo.runtime.type.Scope#getType()
338         */
339        public int getType() {
340            return SCOPE_CGI;
341        }
342        
343        /**
344         * @see railo.runtime.type.Scope#getTypeAsString()
345         */
346        public String getTypeAsString() {
347            return "cgi";
348        }
349        
350            public boolean isScriptProtected() {
351                    return scriptProtected==ScriptProtected.YES;
352            }
353            
354            public void setScriptProtecting(boolean scriptProtecting) {
355                    scriptProtected=scriptProtecting?ScriptProtected.YES:ScriptProtected.NO;
356            }
357    
358            public static String getCurrentURL(HttpServletRequest req) { // DIFF 23
359                    StringBuffer sb=new StringBuffer();
360                    sb.append(req.isSecure()?"https://":"http://");
361                    sb.append(req.getServerName());
362                    sb.append(':');
363                    sb.append(req.getServerPort());
364                    if(!StringUtil.isEmpty(req.getContextPath()))sb.append(req.getContextPath());
365                    sb.append(req.getServletPath());
366                    return sb.toString();
367            }
368            
369            public static String getDomain(HttpServletRequest req) { // DIFF 23
370                    StringBuffer sb=new StringBuffer();
371                    sb.append(req.isSecure()?"https://":"http://");
372                    sb.append(req.getServerName());
373                    sb.append(':');
374                    sb.append(req.getServerPort());
375                    if(!StringUtil.isEmpty(req.getContextPath()))sb.append(req.getContextPath());
376                    return sb.toString();
377            }
378            
379            
380            
381    }