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.config.NullSupportHelper;
014    import railo.runtime.dump.DumpData;
015    import railo.runtime.dump.DumpProperties;
016    import railo.runtime.listener.ApplicationContext;
017    import railo.runtime.net.http.ReqRspUtil;
018    import railo.runtime.op.Caster;
019    import railo.runtime.security.ScriptProtect;
020    import railo.runtime.type.Collection;
021    import railo.runtime.type.KeyImpl;
022    import railo.runtime.type.ReadOnlyStruct;
023    import railo.runtime.type.Struct;
024    import railo.runtime.type.StructImpl;
025    import railo.runtime.type.it.EntryIterator;
026    import railo.runtime.type.it.KeyIterator;
027    import railo.runtime.type.it.StringIterator;
028    import railo.runtime.type.util.KeyConstants;
029    import railo.runtime.type.util.StructUtil;
030    
031    /**
032     *
033     *
034     * To change the template for this generated type comment go to
035     * Window - Preferences - Java - Code Generation - Code and Comments
036     */
037    public final class CGIImpl extends ReadOnlyStruct implements CGI,ScriptProtected {
038            
039            private static final long serialVersionUID = 5219795840777155232L;
040    
041            private static final Collection.Key[] keys={
042                    KeyConstants._auth_password, KeyConstants._auth_type, KeyConstants._auth_user, KeyConstants._cert_cookie, KeyConstants._cert_flags, 
043                    KeyConstants._cert_issuer, KeyConstants._cert_keysize, KeyConstants._cert_secretkeysize, KeyConstants._cert_serialnumber, 
044                    KeyConstants._cert_server_issuer, KeyConstants._cert_server_subject, KeyConstants._cert_subject,KeyConstants._cf_template_path, 
045                    KeyConstants._content_length, KeyConstants._content_type, KeyConstants._gateway_interface, KeyConstants._http_accept, 
046                    KeyConstants._http_accept_encoding, KeyConstants._http_accept_language, KeyConstants._http_connection, KeyConstants._http_cookie, 
047                    KeyConstants._http_host, KeyConstants._http_user_agent, KeyConstants._http_referer, KeyConstants._https, KeyConstants._https_keysize, 
048                    KeyConstants._https_secretkeysize, KeyConstants._https_server_issuer, KeyConstants._https_server_subject, KeyConstants._path_info,
049                    KeyConstants._path_translated, KeyConstants._query_string, KeyConstants._remote_addr, KeyConstants._remote_host, KeyConstants._remote_user, 
050                    KeyConstants._request_method, KeyConstants._request_url, KeyConstants._script_name, KeyConstants._server_name, KeyConstants._server_port, KeyConstants._server_port_secure,
051                    KeyConstants._server_protocol, KeyConstants._server_software, KeyConstants._web_server_api, KeyConstants._context_path, KeyConstants._local_addr, 
052                    KeyConstants._local_host
053            };
054            private static Struct staticKeys=new StructImpl();
055            static{
056                    for(int i=0;i<keys.length;i++){
057                            staticKeys.setEL(keys[i],"");
058                    }
059            }
060            
061            private static String localAddress="";
062            private static String localHost="";
063            
064            static {
065                    try {
066                            InetAddress addr = InetAddress.getLocalHost();
067                            localAddress=addr.getHostAddress();
068                            localHost=addr.getHostName();
069                    }
070                    catch(UnknownHostException uhe) {}
071            }
072            
073            private HttpServletRequest req;
074            private boolean isInit;
075            //private String strBaseFile="fsfd";
076            private PageContext pc;
077            private Struct https;
078            private Struct headers;
079            private int scriptProtected;
080            
081            
082            public CGIImpl(){
083                    this.setReadOnly(true);
084            }
085            
086    
087            @Override
088            public boolean containsKey(Key key) {
089                    return staticKeys.containsKey(key);
090            }
091            
092            @Override
093            public boolean containsValue(Object value) {
094                    // TODO Auto-generated method stub
095                    return super.containsValue(value);
096            }
097            @Override
098            public Collection duplicate(boolean deepCopy) {
099                    Struct sct=new StructImpl();
100                    copy(this,sct,deepCopy);
101                    return sct;
102            }
103            
104            
105            @Override
106            public int size() {
107                    return keys.length;
108            }
109    
110            public Collection.Key[] keys() {
111                    return keys;
112            }
113            
114            @Override
115            public Object get(Collection.Key key, Object defaultValue) {
116                    
117                    if(req==null) {
118                            req=pc.getHttpServletRequest();
119                            https=new StructImpl();
120                            headers=new StructImpl();
121                            String k,v;
122                            try {
123                                    Enumeration e = req.getHeaderNames();
124                            
125                                    while(e.hasMoreElements()) {
126                                    k = (String)e.nextElement();
127                                    v = req.getHeader(k);
128                                    //print.err(k.length()+":"+k);
129                                    headers.setEL(KeyImpl.init(k),v);
130                                    headers.setEL(KeyImpl.init(k=k.replace('-','_')),v);
131                                    https.setEL(KeyImpl.init("http_"+k),v); 
132                            }
133                            }
134                            catch(Throwable t){t.printStackTrace();}
135                    }
136                    String lkey=key.getLowerString();
137            
138                
139            if(lkey.length()>7) {
140                char first=lkey.charAt(0);
141                if(first=='a') {
142                    if(key.equals(KeyConstants._auth_type)) return toString(req.getAuthType());
143                }
144                else if(first=='c') {
145                    if(key.equals(KeyConstants._context_path))return toString(req.getContextPath());
146                    if(key.equals(KeyConstants._cf_template_path)) {
147                                            try {
148                                                    return toString(ResourceUtil.getResource(pc, pc.getBasePageSource()));
149                                            } catch (Throwable t) {
150                                                    return "";
151                                            }
152                    }
153                }
154                else if(first=='h') {
155                    if(lkey.startsWith("http_")){
156                            Object o = https.get(key,NullSupportHelper.NULL());
157                        if(o==NullSupportHelper.NULL() && key.equals(KeyConstants._http_if_modified_since))
158                            o = https.get(KeyConstants._last_modified,NullSupportHelper.NULL());
159                        if(o!=NullSupportHelper.NULL())return doScriptProtect((String)o);
160                }
161                }
162                else if(first=='r') {
163                    if(key.equals(KeyConstants._remote_user))               return toString(req.getRemoteUser());
164                    if(key.equals(KeyConstants._remote_addr))               return toString(req.getRemoteAddr());
165                    if(key.equals(KeyConstants._remote_host))               return toString(req.getRemoteHost());
166                    if(key.equals(KeyConstants._request_method))            return req.getMethod();
167                    if(key.equals(KeyConstants._request_url))               return ReqRspUtil.getRequestURL( req, true );
168                    if(key.equals(KeyConstants._request_uri))               return toString(req.getAttribute("javax.servlet.include.request_uri"));
169                    if(key.getUpperString().startsWith("REDIRECT_")){
170                            // from attributes (key sensitive)
171                            Object value = req.getAttribute(key.getString());
172                            if(!StringUtil.isEmpty(value)) return toString(value);
173                            
174                            // from attributes (key insensitive)
175                            Enumeration<String> names = req.getAttributeNames();
176                            String k;
177                            while(names.hasMoreElements()){
178                                    k=names.nextElement();
179                                    if(k.equalsIgnoreCase(key.getString())) {
180                                            return toString(req.getAttribute(k));
181                                    }
182                            }
183                    }
184                }
185                
186                
187                else if(first=='l') {
188                    if(key.equals(KeyConstants._local_addr))                return toString(localAddress);
189                    if(key.equals(KeyConstants._local_host))                return toString(localHost);
190                }
191                else if(first=='s') {
192                    if(key.equals(KeyConstants._script_name)) 
193                            return ReqRspUtil.getScriptName(req);
194                                    //return StringUtil.emptyIfNull(req.getContextPath())+StringUtil.emptyIfNull(req.getServletPath());
195                            if(key.equals(KeyConstants._server_name))               return toString(req.getServerName());
196                    if(key.equals(KeyConstants._server_protocol))   return toString(req.getProtocol());
197                    if(key.equals(KeyConstants._server_port))               return Caster.toString(req.getServerPort());
198                    if(key.equals(KeyConstants._server_port_secure))return req.isSecure()?"1":"0";
199                    
200                }
201                else if(first=='p') {
202                    if(key.equals(KeyConstants._path_info)) {
203                            String pathInfo = Caster.toString(req.getAttribute("javax.servlet.include.path_info"),null);
204                            if(StringUtil.isEmpty(pathInfo)) pathInfo = Caster.toString(req.getHeader("xajp-path-info"),null);
205                            if(StringUtil.isEmpty(pathInfo)) pathInfo = req.getPathInfo();
206                            if(StringUtil.isEmpty(pathInfo)) {
207                                    pathInfo = Caster.toString(req.getAttribute("requestedPath"),null);
208                                    if(!StringUtil.isEmpty(pathInfo,true)) {
209                                            String scriptName = ReqRspUtil.getScriptName(req);
210                                            if ( pathInfo.startsWith(scriptName) )
211                                                    pathInfo = pathInfo.substring(scriptName.length());
212                                    }
213                            }
214                        
215                            if(!StringUtil.isEmpty(pathInfo,true)) return pathInfo;
216                        return "";
217                    }
218                    if(key.equals(KeyConstants._path_translated))   {
219                            try {
220                                                    return toString(ResourceUtil.getResource(pc, pc.getBasePageSource()));
221                                            } catch (Throwable t) {
222                                                    return "";
223                                            }//toString(req.getServletPath());
224                    }
225                }
226                else if(first=='q') {
227                    if(key.equals(KeyConstants._query_string))return doScriptProtect(toString(ReqRspUtil.getQueryString(req)));
228                }
229            }
230            
231            // check header
232            String headerValue = (String) headers.get(key,null);//req.getHeader(key.getString());
233                if(headerValue != null) return doScriptProtect(headerValue);
234                
235            return other(key,defaultValue);
236            }
237            
238            private Object other(Collection.Key key, Object defaultValue) {
239                    if(staticKeys.containsKey(key)) return "";
240                    return defaultValue;
241            }
242            
243            private String doScriptProtect(String value) {
244                    if(isScriptProtected()) return ScriptProtect.translate(value);
245                    return value;
246            }
247            
248            private String toString(Object str) {
249                    return StringUtil.toStringEmptyIfNull(str);
250            }
251            
252            @Override
253            public Object get(Collection.Key key) {
254                    Object value=get(key,"");
255                    if(value==null)value= "";
256                    return value;
257            }
258            
259            @Override
260            public Iterator<Collection.Key> keyIterator() {
261                    return new KeyIterator(keys());
262            }
263        
264        @Override
265            public Iterator<String> keysAsStringIterator() {
266            return new StringIterator(keys());
267        }
268            
269            @Override
270            public Iterator<Entry<Key, Object>> entryIterator() {
271                    return new EntryIterator(this, keys());
272            }
273            
274            @Override
275            public boolean isInitalized() {
276                    return isInit;
277            }
278            
279            @Override
280            public void initialize(PageContext pc) {
281                    isInit=true;
282                    this.pc=pc;
283                    
284            if(scriptProtected==ScriptProtected.UNDEFINED) {
285                            scriptProtected=((pc.getApplicationContext().getScriptProtect()&ApplicationContext.SCRIPT_PROTECT_CGI)>0)?
286                                            ScriptProtected.YES:ScriptProtected.NO;
287                    }
288            }
289            
290            @Override
291            public void release() {
292                    isInit=false;
293                    this.req=null;
294                    scriptProtected=ScriptProtected.UNDEFINED; 
295                    pc=null;
296                    https=null;
297                    headers=null;
298            }
299            
300            @Override
301            public void release(PageContext pc) {
302                    isInit=false;
303                    this.req=null;
304                    scriptProtected=ScriptProtected.UNDEFINED; 
305                    pc=null;
306                    https=null;
307                    headers=null;
308            }
309            
310            @Override
311            public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) {
312                    return StructUtil.toDumpTable(this, "CGI Scope", pageContext, maxlevel, dp);
313            }
314        
315        @Override
316        public int getType() {
317            return SCOPE_CGI;
318        }
319        
320        @Override
321        public String getTypeAsString() {
322            return "cgi";
323        }
324        
325            public boolean isScriptProtected() {
326                    return scriptProtected==ScriptProtected.YES;
327            }
328            
329            @Override
330            public void setScriptProtecting(ApplicationContext ac,boolean scriptProtecting) {
331                    scriptProtected=scriptProtecting?ScriptProtected.YES:ScriptProtected.NO;
332            }
333    
334            
335            public static String getDomain(HttpServletRequest req) { // DIFF 23
336                    StringBuffer sb=new StringBuffer();
337                    sb.append(req.isSecure()?"https://":"http://");
338                    sb.append(req.getServerName());
339                    sb.append(':');
340                    sb.append(req.getServerPort());
341                    if(!StringUtil.isEmpty(req.getContextPath()))sb.append(req.getContextPath());
342                    return sb.toString();
343            }
344    
345    }