protected void LogWarning(string message, params object[] args)
        {
#if ENABLE_DEBUG
            message = string.Format("[{0}] {1}", hash_, message);
#endif
            FunDebug.LogWarning(message, args);
        }
        public bool Remove(string name)
        {
            lock (lock_)
            {
                List <T> list = list_.FindAll(predicate(name));
                if (list.Count > 0)
                {
                    if (list.Count > 1)
                    {
                        FunDebug.LogWarning("There are too many items with the same name as '{0}'.", name);
                    }

                    list.ForEach(t => { t.isDone = true; });
                    return(true);
                }

                int count = pending_.RemoveAll(predicate(name));
                if (count > 0)
                {
                    if (count > 1)
                    {
                        FunDebug.LogWarning("There are too many items with the same name as '{0}'.", name);
                    }
                    return(true);
                }
            }

            return(false);
        }
        public void StartDownload()
        {
            lock (lock_)
            {
                if (state_ != State.Ready)
                {
                    FunDebug.LogWarning("Downloader.StartDownload - You must call GetDownloadList() first " +
                                        "or wait until ready to download.");
                    return;
                }

                if (partial_downloading_)
                {
                    FunDebug.Log("[Downloader] Ready to download {0} file(s) ({1})",
                                 partial_download_list_.Count, getSizeString(partial_download_size_));
                }
                else if (total_download_count_ > 0)
                {
                    FunDebug.Log("[Downloader] Ready to download {0} file(s) ({1})",
                                 total_download_count_, getSizeString(total_download_size_));
                }

                state_ = State.Downloading;
                retry_download_count_ = 0;
                download_time_.Start();

                // Starts download
                downloadResourceFile();
            }
        }
Example #4
0
        public void StartDownload()
        {
            mutex_.WaitOne();

            try
            {
                if (state_ != State.Ready)
                {
                    FunDebug.LogWarning("Downloader.StartDownload - You must call GetDownloadList() first " +
                                        "or wait until ready to download.");
                    return;
                }

                if (total_download_count_ > 0)
                {
                    FunDebug.Log("Downloader - Ready to download {0} files ({1})",
                                 total_download_count_, getSizeString(total_download_size_));
                }

                state_ = State.Downloading;
                retry_download_count_ = 0;
                download_time_.Start();

                // Deletes files
                deleteLocalFiles();

                // Starts download
                downloadResourceFile();
            }
            finally
            {
                mutex_.ReleaseMutex();
            }
        }
        public bool LeaveChannel(string channel_id)
        {
            if (!Connected)
            {
                FunDebug.LogWarning("Multicast.LeaveChannel - Multicast is not connected.\n" +
                                    "If you are trying to leave a channel in which you were, " +
                                    "connect first while preserving the session id you used for join.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Multicast.LeaveChannel - You are not in the '{0} channel.", channel_id);
                    return(false);
                }
            }

            lock (channel_lock_)
            {
                channels_.Remove(channel_id);
            }

            sendLeaveMessage(channel_id);
            onUserLeft(channel_id, sender_);

            return(true);
        }
Example #6
0
        public bool Remove(uint uid)
        {
            lock (lock_)
            {
                if (dict_.ContainsKey(uid))
                {
                    dict_[uid].abort = true;
                    return(true);
                }

                List <FunapiRpcPeer> finds = pending_.FindAll(predicate(uid));
                if (finds.Count > 0)
                {
                    foreach (FunapiRpcPeer peer in finds)
                    {
                        peer.abort = true;
                        pending_.Remove(peer);
                    }

                    if (finds.Count > 1)
                    {
                        FunDebug.LogWarning("There are too many peers with the same uid as '{0}'.", uid);
                    }

                    return(true);
                }
            }

            return(false);
        }
Example #7
0
        void onRequestFailed(Request request)
        {
            request.failed = true;

            if (request.command == CmdVersion)
            {
                FunDebug.LogWarning("Failed to check a dedicated server version. Please check the host manager.");
#if UNITY_EDITOR
                UnityEditor.EditorApplication.Exit(0);
#else
                Application.Quit();
#endif
                return;
            }
            else if (request.command == "heartbeat")
            {
                FunDebug.LogWarning("Failed to request heartbeat.");
                heartbeat_timeout_count_++;
                if (heartbeat_timeout_count_ >= heartbeat_retry_threshold_)
                {
                    if (DisconnectedCallback != null && isActive)
                    {
                        DisconnectedCallback();
                        isActive = false;
                    }
                }
            }
            else
            {
                webRequestCallback(request);
            }
        }
Example #8
0
        public void SetId(object obj)
        {
            lock (lock_)
            {
                if (obj is SessionId)
                {
                    SessionId sid = obj as SessionId;
                    id_string_ = sid.id_string;
                    id_array_  = new byte[sid.id_array.Length];
                    Buffer.BlockCopy(sid.id_array, 0, id_array_, 0, sid.id_array.Length);
                }
                else if (obj is string)
                {
                    string str = obj as string;
                    id_string_ = str;
                    id_array_  = Encoding.UTF8.GetBytes(str);
                }
                else if (obj is byte[])
                {
                    id_string_ = ToString(obj);

                    byte[] array = obj as byte[];
                    id_array_ = new byte[array.Length];
                    Buffer.BlockCopy(array, 0, id_array_, 0, array.Length);
                }
                else
                {
                    FunDebug.LogWarning("SessionId.SetId - Wrong object type for session id. obj:{0}", obj);
                }
            }
        }
        public void GetDownloadList(string url, string target_path, string file_path = "")
        {
            lock (lock_)
            {
                if (ReadyCallback == null)
                {
                    FunDebug.LogError("Downloader.GetDownloadList - You must register the ReadyCallback first.");
                    return;
                }

                if (IsDownloading)
                {
                    FunDebug.LogWarning("The resource file is being downloaded. (Url: {0})\n" +
                                        "Please try again after the download is completed.", url);
                    return;
                }

                state_ = State.Start;

                string host_url = url;
                if (host_url[host_url.Length - 1] != '/')
                {
                    host_url += "/";
                }
                host_url_ = host_url;
                FunDebug.Log("[Downloader] Download from {0}", host_url_);

                target_path_ = target_path;
                if (target_path_[target_path_.Length - 1] != '/')
                {
                    target_path_ += "/";
                }
                target_path_ += kRootPath + "/";
                FunDebug.Log("[Downloader] Save to {0}", target_path_);

                cur_download_count_    = 0;
                cur_download_size_     = 0;
                total_download_count_  = 0;
                total_download_size_   = 0;
                partial_download_size_ = 0;

                setMonoListener();
                loadCachedList();

                // Gets list file
                string request_url = host_url_;
                if (!string.IsNullOrEmpty(file_path))
                {
                    if (file_path[0] == '/')
                    {
                        file_path = file_path.Substring(1);
                    }

                    request_url += file_path;
                }

                downloadListFile(request_url);
            }
        }
Example #10
0
        protected void LogWarning(string message, params object[] args)
        {
#if ENABLE_LOG && (LOG_LEVEL_1 || LOG_LEVEL_2 || LOG_LEVEL_3)
#if LOG_LEVEL_3
            message = string.Format("[{0}] {1}", hash_, message);
#endif
            FunDebug.LogWarning(message, args);
#endif
        }
Example #11
0
        public override Int64 Decrypt(ArraySegment <byte> src, ArraySegment <byte> dst, string in_header)
        {
            if (in_header.Length > 0)
            {
                FunDebug.LogWarning("EncryptorAes128.Decrypt - Wrong encryptor header.");
                return(-1);
            }

            return(decrypt(src, dst));
        }
        // Picture-related functions

        // start: index at which the range starts.
        public void RequestPictures(List <UserInfo> list, int start, int count)
        {
            if (list == null || list.Count <= 0)
            {
                FunDebug.LogWarning("SocialNetwork.RequestPictures - Invalid list.");
                return;
            }

            StartCoroutine(RequestPictures(list));
        }
Example #13
0
        public void Add(List <HostAddr> list)
        {
            if (list == null || list.Count <= 0)
            {
                FunDebug.LogWarning("ConnectList.Add - You must pass a list of HostAddr as a parameter.");
                return;
            }

            addr_list_.AddRange(list);
        }
Example #14
0
        public bool JoinChannel(string channel_id, string token, ChannelMessage handler)
        {
            if (!Connected)
            {
                FunDebug.LogWarning("Multicast.JoinChannel - Multicast is not connected.\n" +
                                    "Please connect first before join a multicast channel.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Multicast.JoinChannel - Already joined the '{0} channel.", channel_id);
                    return(false);
                }

                channels_.Add(channel_id, handler);
            }

            if (encoding_ == FunEncoding.kJson)
            {
                Dictionary <string, object> mcast_msg = new Dictionary <string, object>();
                mcast_msg[kChannelId] = channel_id;
                mcast_msg[kSender]    = sender_;
                mcast_msg[kJoin]      = true;

                if (token != null && token.Length > 0)
                {
                    mcast_msg[kToken] = token;
                }

                session_.SendMessage(kMulticastMsgType, mcast_msg);
            }
            else
            {
                FunMulticastMessage mcast_msg = new FunMulticastMessage();
                mcast_msg.channel = channel_id;
                mcast_msg.sender  = sender_;
                mcast_msg.join    = true;

                if (token != null && token.Length > 0)
                {
                    mcast_msg.token = token;
                }

                FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast_msg, MessageType.multicast);
                session_.SendMessage(kMulticastMsgType, fun_msg);
            }

            FunDebug.Log("Multicast - Request to join '{0}' channel", channel_id);

            return(true);
        }
Example #15
0
        public override Int64 Decrypt(ArraySegment <byte> src, ArraySegment <byte> dst, string in_header)
        {
            if (in_header.Length > 0)
            {
                FunDebug.LogWarning("Wrong encryptor header.");
                return(-1);
            }

            string out_header = "";

            return(Encrypt(src, dst, ref out_header));
        }
Example #16
0
        public override Int64 Decrypt(ArraySegment <byte> src, ArraySegment <byte> dst, string in_header)
        {
            FunDebug.Assert(state == State.kEstablished);

            if (in_header.Length > 0)
            {
                FunDebug.LogWarning("Wrong encryptor header.");
                return(-1);
            }

            return(decrypt(src, dst));
        }
Example #17
0
        public void GetDownloadList(string url, string target_path)
        {
            mutex_.WaitOne();

            try
            {
                if (ReadyCallback == null)
                {
                    FunDebug.LogError("You must register the ReadyCallback first.");
                    return;
                }

                if (IsDownloading)
                {
                    FunDebug.LogWarning("The resource file is being downloaded. (Url: {0})\n"
                                        + "Please try again after the download is completed.", url);
                    return;
                }

                state_ = State.Start;

                string host_url = url;
                if (host_url[host_url.Length - 1] != '/')
                {
                    host_url += "/";
                }
                host_url_ = host_url;
                FunDebug.Log("Download url: {0}", host_url_);

                target_path_ = target_path;
                if (target_path_[target_path_.Length - 1] != '/')
                {
                    target_path_ += "/";
                }
                target_path_ += kRootPath + "/";
                FunDebug.Log("Download path: {0}", target_path_);

                cur_download_count_   = 0;
                cur_download_size_    = 0;
                total_download_count_ = 0;
                total_download_size_  = 0;

                createUpdater();
                loadCachedList();

                // Gets list file
                downloadListFile(host_url_);
            }
            finally
            {
                mutex_.ReleaseMutex();
            }
        }
Example #18
0
        public bool refresh()
        {
            ip_list_ = Dns.GetHostAddresses(host);
            if (ip_list_ == null || ip_list_.Length == 0)
            {
                FunDebug.LogWarning("HostIP - Can't get any host address from '{0}'.", host);
                return(false);
            }

            index_ = 0;
            inet_  = ip_list_[0].AddressFamily;

            return(true);
        }
Example #19
0
        public void UpdateList(int max_count)
        {
            if (web_client_ == null || string.IsNullOrEmpty(host_url_))
            {
                FunDebug.LogWarning("Announcement.UpdateList - You must call Init() function first.");
                onResult(AnnounceResult.kNeedInitialize);
                return;
            }

            // Request a list of announcements.
            string url = host_url_ + kAnnouncementsUrl + "?count=" + max_count;

            web_client_.DownloadDataAsync(new Uri(url));
        }
Example #20
0
        void onUserLeft(string channel_id, string sender)
        {
            if (sender == sender_)
            {
                lock (chat_channel_lock_)
                {
                    if (!chat_channels_.ContainsKey(channel_id))
                    {
                        FunDebug.LogWarning("You are not in the '{0}' channel.", channel_id);
                        return;
                    }

                    chat_channels_.Remove(channel_id);
                }
            }
        }
        List <UserInfo> getRangeOfList(List <UserInfo> list, int start, int count)
        {
            if (start < 0 || start >= list.Count || count < 0 || start + count > list.Count)
            {
                FunDebug.LogWarning("getRangeOfList - Invalid boundary index. " +
                                    "start:{0} count:{1} list:{2}", start, count, list.Count);
                return(null);
            }

            if (count == 0)
            {
                count = list.Count;
            }

            return(list.GetRange(start, count));
        }
Example #22
0
        public void Add(string hostname, UInt16 port)
        {
            IPAddress[] list = Dns.GetHostAddresses(hostname);
            if (list == null)
            {
                FunDebug.LogWarning("ConnectList.Add - Can't find any ip address with '{0}' host.", hostname);
                return;
            }

            FunDebug.DebugLog1("[{0}] Dns address count is {1}.", hostname, list.Length);

            foreach (IPAddress ip in list)
            {
                addr_list_.Add(new HostIP(hostname, ip, port));
                FunDebug.DebugLog1("  > {0} ({1})", ip, ip.AddressFamily);
            }
        }
Example #23
0
        void loadCachedList()
        {
            cached_list_.Clear();

            string path = target_path_ + kCachedFileName;

            if (!File.Exists(path))
            {
                return;
            }

            StreamReader stream = File.OpenText(path);
            string       data   = stream.ReadToEnd();

            stream.Close();

            if (data.Length <= 0)
            {
                FunDebug.LogWarning("Failed to get a cached file list.");
                return;
            }

            Dictionary <string, object> json = Json.Deserialize(data) as Dictionary <string, object>;
            List <object> list = json["list"] as List <object>;

            foreach (Dictionary <string, object> node in list)
            {
                DownloadFileInfo info = new DownloadFileInfo();
                info.path = node["path"] as string;
                info.size = Convert.ToUInt32(node["size"]);
                info.hash = node["hash"] as string;
                if (node.ContainsKey("front"))
                {
                    info.hash_front = node["front"] as string;
                }
                else
                {
                    info.hash_front = "";
                }

                cached_list_.Add(info);
            }

            FunDebug.DebugLog("Loads cached list : {0}", cached_list_.Count);
        }
Example #24
0
        bool setVersion(string version)
        {
            Regex regex = new Regex(@"^[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+$");

            if (!regex.IsMatch(version))
            {
                FunDebug.LogWarning("The dedicated server version must be 'x.x.x.x' format.");
                return(false);
            }

            Dictionary <string, object> json = new Dictionary <string, object>();

            json["version"] = version;

            version_ = json_helper_.Serialize(json);

            return(true);
        }
Example #25
0
        static bool certificateValidationCallback(System.Object sender, X509Certificate certificate,
                                                  X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
#if !NO_UNITY
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            for (int i = 0; i < chain.ChainStatus.Length; ++i)
            {
                if (chain.ChainStatus[i].Status == X509ChainStatusFlags.RevocationStatusUnknown)
                {
                    continue;
                }
                else if (chain.ChainStatus[i].Status == X509ChainStatusFlags.UntrustedRoot)
                {
                    if (!checkRootCertificate(chain))
                    {
                        FunDebug.LogWarning("MozRoots - Untrusted Root chain : {0}", certificate);
                        return(false);
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                    chain.ChainPolicy.RevocationMode      = X509RevocationMode.Online;
                    chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                    chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.NoFlag;
                    if (!chain.Build((X509Certificate2)certificate))
                    {
                        FunDebug.LogWarning("MozRoots - Invalid Certificate : {0}", certificate);
                        return(false);
                    }
                }
            }
#endif

            return(true);
        }
Example #26
0
        public static bool CertValidationCallback(System.Object sender, X509Certificate certificate,
                                                  X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return(true);
            }

            // The server address to connect is different from the server address in the certificate
            if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
            {
                return(false);
            }

            foreach (X509ChainStatus status in chain.ChainStatus)
            {
                if (!allowed_chain_status_.Contains(status.Status))
                {
                    return(false);
                }
            }

            // Verify that server certificate can be built from the root certificate in mozroots
            X509Chain ch = new X509Chain();

            for (int i = chain.ChainElements.Count - 1; i > 0; i--)
            {
                X509ChainElement chainElement = chain.ChainElements[i];
                ch.ChainPolicy.ExtraStore.Add(chainElement.Certificate);
            }
            ch.ChainPolicy.ExtraStore.AddRange(trusted_cerificates_);
            ch.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
            ch.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
            ch.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
            ch.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;
            X509Certificate2 cert = new X509Certificate2(certificate);

            if (!ch.Build(cert))
            {
                FunDebug.LogWarning("Invalid certificate : {0}", certificate);
                return(false);
            }
            return(true);
        }
        bool sendToChannel(string channel_id, object message)
        {
            if (message == null)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(channel_id))
            {
                FunDebug.LogWarning("[Multicast] can't send a message. invalid channel id.");
                return(false);
            }

            if (!Connected)
            {
                FunDebug.LogWarning("[Multicast] can't send a message. session is not connected.");
                return(false);
            }

            if (!InChannel(channel_id))
            {
                FunDebug.LogWarning("[Multicast] can't send a message. you aren't in '{0}' channel.", channel_id);
                return(false);
            }

            if (encoding_ == FunEncoding.kJson)
            {
                json_helper_.SetStringField(message, kSender, sender_);

                session_.SendMessage(kMulticastMsgType, message, protocol_);
            }
            else
            {
                FunMulticastMessage mcast = message as FunMulticastMessage;
                mcast.sender = sender_;

                FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast, MessageType.multicast);
                session_.SendMessage(kMulticastMsgType, fun_msg, protocol_);
            }

            return(true);
        }
Example #28
0
        public bool JoinChannel(string channel_id, string token, OnChatMessage handler)
        {
            if (!base.JoinChannel(channel_id, token, onReceived))
            {
                return(false);
            }

            lock (chat_channel_lock_)
            {
                if (chat_channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Already joined the '{0}' channel.", channel_id);
                    return(false);
                }

                chat_channels_.Add(channel_id, handler);
            }

            return(true);
        }
        void onError(string channel_id, FunMulticastMessage.ErrorCode code)
        {
            FunDebug.LogWarning("[Multicast] error occurred. channel:{0} error:{1}", channel_id, code);

            if (code == FunMulticastMessage.ErrorCode.EC_CLOSED)
            {
                // This error occurs when the server is closed.
                // If the session is connected, tries to rejoin the channel.

                if (Connected && InChannel(channel_id))
                {
                    string token = null;
                    lock (token_lock_)
                    {
                        if (tokens_.ContainsKey(channel_id))
                        {
                            token = tokens_[channel_id];
                        }
                    }

                    requestToJoin(channel_id, token);
                    return;
                }
            }

            if (code != FunMulticastMessage.ErrorCode.EC_ALREADY_JOINED)
            {
                lock (channel_lock_)
                {
                    if (channels_.ContainsKey(channel_id))
                    {
                        channels_.Remove(channel_id);
                    }
                }
            }

            if (ErrorCallback != null)
            {
                ErrorCallback(channel_id, code);
            }
        }
Example #30
0
        /// The 'channel_id' field is mandatory.
        /// The 'sender' must fill in the message.
        /// The message shouldn't include join and leave flags.
        public bool SendToChannel(FunMulticastMessage mcast_msg)
        {
            if (mcast_msg == null)
            {
                return(false);
            }

            FunDebug.Assert(!mcast_msg.join);
            FunDebug.Assert(!mcast_msg.leave);

            string channel_id = mcast_msg.channel;

            if (channel_id == "")
            {
                FunDebug.LogWarning("Multicast.SendToChannel - You should set a vaild channel id.");
                return(false);
            }

            lock (channel_lock_)
            {
                if (!Connected)
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - Multicast is not connected.\n" +
                                        "If you are trying to send a message in which you were, " +
                                        "connect first while preserving the session id you used for join.");
                    return(false);
                }
                if (!channels_.ContainsKey(channel_id))
                {
                    FunDebug.LogWarning("Multicast.SendToChannel - You are not in the '{0} channel.", channel_id);
                    return(false);
                }
            }

            mcast_msg.sender = sender_;

            FunMessage fun_msg = FunapiMessage.CreateFunMessage(mcast_msg, MessageType.multicast);

            session_.SendMessage(kMulticastMsgType, fun_msg);
            return(true);
        }