Index: trunk/SimpleJavaProxy/src/simplejavaproxy/Main.java
===================================================================
--- trunk/SimpleJavaProxy/src/simplejavaproxy/Main.java	(revision 5)
+++ trunk/SimpleJavaProxy/src/simplejavaproxy/Main.java	(revision 6)
@@ -17,6 +17,6 @@
     public static void main(String[] args) {
         // TODO code application logic here
-        //SimpleProxy.main(new String[]{"9999","127.0.0.1","8888"});
-        SimpleProxy.main(new String[]{"9999"});
+        SimpleProxy.main(new String[]{"9999","127.0.0.1","8888"});
+        //SimpleProxy.main(new String[]{"9999"});
     }
 
Index: trunk/SimpleJavaProxy/src/simplejavaproxy/SimpleProxy.java
===================================================================
--- trunk/SimpleJavaProxy/src/simplejavaproxy/SimpleProxy.java	(revision 5)
+++ trunk/SimpleJavaProxy/src/simplejavaproxy/SimpleProxy.java	(revision 6)
@@ -55,7 +55,10 @@
 import java.net.*;
 import java.lang.reflect.Array;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
 public class SimpleProxy extends Thread {
-
     public static final int DEFAULT_PORT = 8080;
     private ServerSocket server = null;
@@ -64,8 +67,9 @@
     private int fwdPort = 0;
     private int ptTimeout = ProxyThread.DEFAULT_TIMEOUT;
-    private int debugLevel = 0;
+    private int debugLevel = 1;
     private PrintStream debugOut = System.out;
     //FMG>>
     public static String safariKey = "";
+    public static Map cookieMap = new ConcurrentHashMap();
 
 
@@ -226,5 +230,4 @@
  */
 class ProxyThread extends Thread {
-
     private Socket pSocket;
     private String fwdServer = "";
@@ -352,5 +355,5 @@
             // keep in mind that because we're using threads, the output won't
             // necessarily be synchronous
-            if (debugLevel > 0) {
+            if (debugLevel > 5) {
                 long endTime = System.currentTimeMillis();
                 debugOut.println("Request from " + pSocket.getInetAddress().getHostAddress()
@@ -362,5 +365,5 @@
                 debugOut.flush();
             }
-            if (debugLevel > 1) {
+            if (debugLevel > 10) {
                 debugOut.println("REQUEST:\n" + (new String(request)));
                 debugOut.println("RESPONSE:\n" + (new String(response)));
@@ -416,4 +419,5 @@
         int pos = -1;
         int byteCount = 0;
+        String originalCookies = null;
 
         try {
@@ -457,7 +461,6 @@
 
                 //**************************************************************
-                //FMG>>: cookie al, Cookie: ya da Set-Cookie: header'larını al.
-                //Cookie içindeki Safari->key değerini olması gerekenle değiştir (safariKey)
-                //Set-Cookie ile gelen Safari->key değerini güncelle (safariKey)
+                //FMG>>: simulate browser (User Agent) cookie behaviour
+                //We want the server beleive that we are a single browser.
 
                 //Set-Cookie: Safari=cookieversion=2&portal=my&key=E894F897E4A4912E6D683D6939BE74D192731C8F4191A3ACAB6B3FEE16588D2954DBF3B9BF495294EE68A4477E3D772EAA5B0E89433D9926603960942389D153574A4D8BAB4095687832999AECDC2C751104CB8D1A30141A9BCD769E3A126390FFDD02DA9C28307232CD000C64D4F0C3D2993A357CCBED2A19E0467900E3884D71&sessionid=1a923806-a923-4442-9579-325c77ae39db&ref=Google&logged=true&oref=http%3a%2f%2fwww.google.com.tr%2furl%3fsa%3dt%26source%3dweb%26ct%3dres%26cd%3d1%26ved%3d0CAYQFjAA%26url%3dhttp%253A%252F%252Fmy.safaribooksonline.com%252F%26rct%3dj%26q%3dsafari%2bbook%26ei%3d2ZHNS_XcBIX0ObjplcwP%26usg%3dAFQjCNFeqvBpwDvMtcrCBnfHPPiUQofzPA; Path=/; Domain=my.safaribooksonline.com
@@ -468,46 +471,27 @@
                 if (pos >= 0) {
                     String setCookie = data.substring(pos + 11).trim();
-                    int safariKeyIndexStart = setCookie.indexOf("&key=") + 5;
-                    int safariKeyIndexEnd = setCookie.indexOf("&", safariKeyIndexStart);
-
-                    if (safariKeyIndexStart >= 5) { //YAP: add extra controls, key cookie may be present in other sites as well. may be limit this to safari host
-                        //get the key from response header
-                        String key = setCookie.substring(safariKeyIndexStart, safariKeyIndexEnd);
-                        SimpleProxy.safariKey = key;
-                        System.out.println("Safari Key in the set-cookie is: " + SimpleProxy.safariKey);
-                    }
-                }
-
-                // check for the Cookie header
+                    handleSetCookie(setCookie);
+                }
+
+                //YAP: cookie headerını iptal et, aşağıda biz gönderiyoruz çünkü
                 pos = data.toLowerCase().indexOf("cookie:");
                 if (pos >= 0) {
-                    boolean logged = false;
-
-                    int loggedStart = data.indexOf("&logged=") + 8;
-                    int loggedEnd = data.indexOf("&", loggedStart);
-                    if (loggedStart >= 8) {
-                        logged = data.substring(loggedStart, loggedEnd).equals("true");
-                    }
-
-                    int safariKeyIndexStart = data.indexOf("&key=") + 5;
-                    int safariKeyIndexEnd = data.indexOf("&", safariKeyIndexStart);
-
-                    if (logged && (safariKeyIndexStart >= 5)) { //YAP: add extra controls, key cookie may be present in other sites as well. may be limit this to safari host
-                        //replace the key in the cookie with safariKey
-                        String cookie1 = data.substring(0, safariKeyIndexStart); //first part
-                        String cookie2 = data.substring(safariKeyIndexEnd); //remaining part
-
-                        System.out.println("Old cookie:        '" + data + "'");
-                        data = (cookie1 + SimpleProxy.safariKey + cookie2);
-                        System.out.println("Changed cookie to: '" + data + "'");
-                    }
+                    //we do not send original cookies
+                    originalCookies = data.substring(pos + 7);
+                } else {
+                    header.append(data + "\r\n");
                 }
 
                 //<<FMG
                 //**************************************************************
-
-                header.append(data + "\r\n");
-                data = "";
-            }
+            }
+
+            //FMG>>
+            //lastly send cookie if applicable for this host
+            String cookie = getCookiesForHost(host.toString());
+            if (cookie != null) header.append(cookie + "\r\n");
+            if (originalCookies != null) System.out.println("\t _ookie:" + originalCookies);
+            if (cookie == null && originalCookies != null) header.append("Cookie: " + originalCookies + "\r\n");
+            //<<FMG
 
             // add a blank line to terminate the header info
@@ -584,5 +568,5 @@
                     break;
                 } else {
-                    data.append((char) c);
+                    data.append((char)c);
                 }
             }
@@ -605,3 +589,86 @@
         return data.toString();
     }
+
+    //FMG>>
+    //We are simulating the User Agent role as in RFC2965
+    //the cookies coming from server, for a host
+    private void handleSetCookie(String setCookie) {
+        //global cookie map for each domain
+        Map cookieMap = SimpleProxy.cookieMap;
+
+        //parsed attribute value pair for setCookie (we should not send Domain, Path, Expires cookies back to server, so remove them)
+        Map cookieValues = parseCookies(setCookie);
+        String domain = (String)cookieValues.remove("Domain");
+        if (domain == null) domain = (String)cookieValues.remove("domain");
+        if (domain == null) domain = "";
+        cookieValues.remove("Path");
+        cookieValues.remove("Expires");
+        cookieValues.remove("path");
+        cookieValues.remove("expires");
+
+        //get cookies for this domain
+        Map cookiesForDomain = (Map)cookieMap.get(domain);
+        //create if not exists
+        if (cookiesForDomain == null) cookiesForDomain = new ConcurrentHashMap();
+        //put & override the existing values
+        cookiesForDomain.putAll(cookieValues);
+        //set cookies for this host
+        cookieMap.put(domain, cookiesForDomain);
+
+        if (debugLevel > 0) {
+            System.out.println(">>>> Got new cookie for domain: '" + domain);
+            Iterator it = cookiesForDomain.keySet().iterator();
+            while (it.hasNext()) {
+                String key = (String)it.next();
+                System.out.print("\tKey: " + key);
+                System.out.println("  Value: " + cookiesForDomain.get(key));
+            }
+        }
+
+    }
+
+    private Map parseCookies(String cookies) {
+        Map result = new HashMap();
+        String[] cookieArray = cookies.split(";");
+        for (int i = 0; i < cookieArray.length; i++) {
+            String attributeValue = cookieArray[i];
+            int eqIndex = attributeValue.indexOf("=");
+            if (eqIndex == -1) continue;
+            String attribute = attributeValue.substring(0, eqIndex);
+            String value = attributeValue.substring(eqIndex + 1);
+            result.put(attribute.trim(), value.trim());
+        }
+
+        return result;
+    }
+
+    //returns the cookies to be sent for a host
+    private String getCookiesForHost(String host) {
+        //global cookie map for each domain
+        Map cookieMap = SimpleProxy.cookieMap;
+
+        //get cookies for this domain
+        Map cookiesForDomain = (Map)cookieMap.get(host);
+        if (cookiesForDomain == null) return null;
+
+        StringBuffer cookie = new StringBuffer();
+        cookie.append("Cookie: ");
+
+        Iterator it = cookiesForDomain.keySet().iterator();
+        while (it.hasNext()) {
+            String key = (String)it.next();
+            cookie.append(key);
+            cookie.append("=");
+            cookie.append(cookiesForDomain.get(key));
+            if (it.hasNext()) cookie.append(";");
+        }
+
+        if (debugLevel > 0) {
+            System.out.println("Sending cookie for host: " + host);
+            System.out.println("\t " + cookie.toString());
+        }
+
+
+        return cookie.toString();
+    }
 }
