예제 #1
0
        private void button1_Click(object sender, EventArgs e)
        {
            BT_GTS.Enabled = false;
            if (!BGW_GTS.IsBusy)
            {
                LB_GTS_Log.Items.Add(DateTime.Now.ToLongTimeString() + ": Sending command: Start GTS");
                LB_GTS_Log.SelectedIndex = LB_GTS_Log.Items.Count - 1;
                currentDataFileName      = "";
                if (CB_GTS_SendPKMN.Checked && RB_GTS_SendFolder.Checked)
                {
                    if (!Directory.Exists(TB_GTS_SendPKMN.Text))
                    {
                        MessageBox.Show("The folder you have selected does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        BT_GTS.Enabled = true;
                        return;
                    }
                    PKMfromFolder = new List <string>();
                    PKMfromFolder.AddRange(Directory.GetFiles(TB_GTS_SendPKMN.Text));
                    CountPKMfromFolder = PKMfromFolder.Count;
                    if (PKMfromFolder.Count > 0)
                    {
                        FileInfo FI = new FileInfo(PKMfromFolder[0]);
                        LB_GTS_Log.Items.Add(DateTime.Now.ToLongTimeString() + ": " + "Next Pkm (1 of " + CountPKMfromFolder + "): " + FI.Name);
                        LB_GTS_Log.SelectedIndex = LB_GTS_Log.Items.Count - 1;
                    }
                    else
                    {
                        MessageBox.Show("There are no .pkm-files in the folder.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        CB_GTS_SendPKMN.Checked = false;
                        TB_GTS_SendPKMN.Text    = "";
                    }
                }
                if (CB_GTS_SendPKMN.Checked && RB_GTS_SendOne.Checked && !File.Exists(TB_GTS_SendPKMN.Text))
                {
                    MessageBox.Show("The file you have selected does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    BT_GTS.Enabled = true;
                    return;
                }
                BT_GTS.Text = "STOP GTS";

                CB_GTS_SendPKMN.Enabled = CB_GTS_Reject.Enabled = CB_GTS_SendAfterReceive.Enabled = RB_GTS_SendOne.Enabled = RB_GTS_SendFolder.Enabled = false;
                TB_GTS_SendPKMN.Enabled = BT_GTS_SendPKMN.Enabled = false;
                BGW_GTS.RunWorkerAsync();
                LA_GTS_Status.Text      = "GTS running";
                LA_GTS_Status.BackColor = Color.Green;
                BT_GTS.Enabled          = true;
            }
            else
            {
                BGW_GTS.ReportProgress(1, "Sending command: Stop GTS");
                BGW_GTS.CancelAsync();
            }
        }
        private byte[] GetBin(string currentDataFileName)
        {
            byte[] bin = null;
            if (File.Exists(currentDataFileName))
            {
                byte[] pkm = null;


                //currentDataFileName = TB_GTS_SendPKMN.Text;
                //pkm = File2PKMBytes(currentDataFileName);
                pkm = File.ReadAllBytes(currentDataFileName);
                bin = Pokemon.EncryptPokemon((byte[])(pkm.Clone()));

                if (pkm.Length < 236)
                {
                    Array.Resize(ref pkm, 236);
                }
                else if (pkm.Length > 236)
                {
                    BGW_GTS.ReportProgress(1, "Error : incorrect file size !");

                    return(null);
                }

                byte[] binEnd = new byte[56];
                Array.Copy(pkm, 8, binEnd, 0, 2);
                //ID
                binEnd[2] = (byte)((pkm[64] & 4) > 0 ? 3 : (pkm[64] & 2) + 1);
                //Gender
                binEnd[3] = pkm[140];
                //Level
                Array.Copy(new byte[] { 0x1, 0x0, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0 }, 0, binEnd, 4, 8);
                //Requesting Bulba, either, any
                Array.Copy(pkm, 0x68, binEnd, 32, 16);
                //OT name
                Array.Copy(pkm, 0xc, binEnd, 48, 2);
                //OT ID
                Array.Resize(ref bin, 292);
                Array.Copy(binEnd, 0, bin, 236, 56);
            }
            return(bin);
        }
        private void PostSendChanger()
        {
            if (RB_GTS_SendFolder.Checked)
            {
                if (CB_RANDOMIZE.Checked == false)
                {
                    if ((CurrentPokemon) == PKMfromFolder.Count - 1)
                    {
                        CurrentPokemon = 0;
                    }
                    else
                    {
                        CurrentPokemon += 1;
                    }

                    currentDataFileName = PKMfromFolder[CurrentPokemon];
                    FileInfo FI = new FileInfo(currentDataFileName);
                    BGW_GTS.ReportProgress(0, "Next Pokemon will be: " + FI.Name);
                }
            }
        }
        private void asyncReq(Socket sk)
        {
            string ansStr = null;

            byte[]    ans   = { };
            ReqStruct reqst = default(ReqStruct);

            byte[] data = new byte[512];
            try
            {
                reqst = GetReq(ref sk);
            }
            catch (Exception ex)
            {
                BGW_GTS.ReportProgress(1, "Got wrong request, probably not from a DS. Error was : " + ex.Message);
                return;
            }

            Socket  sock = reqst.sock;
            Request req  = reqst.req;

            string pid = req.getvars["pid"];

            byte[] bin = null;
            if (!CB_GTS_SendPKMN.Checked)
            {
                currentDataFileName = "";
            }
            else
            {
            }
            //bin = GetBin(currentDataFileName);
            if (req.getvars.Count == 1)
            {
                ansStr = RandStr(32);
            }
            else
            {
                byte[] encrypted_data = System.Convert.FromBase64String(req.getvars["data"].Replace("-", "+").Replace("_", "/"));
                data = Decrypt_data(encrypted_data);
                data = data.ToList().GetRange(4, data.Length - 4).ToArray();

                switch (req.action)
                {
                case "info":
                    BGW_GTS.ReportProgress(1, sk.RemoteEndPoint.ToString() + " has entered the GTS.");
                    ans = new byte[] { 1, 0 };

                    break;

                case "setProfile":
                    ans = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
                    BGW_GTS.ReportProgress(1, "Profile from " + sk.RemoteEndPoint.ToString());
                    break;

                case "result":
                    if (currentDataFileName == string.Empty)
                    {
                        Randomizer();
                    }
                    if (File.Exists(currentDataFileName))
                    {
                        ans = GetBin(currentDataFileName);
                        //BGW_GTS.ReportProgress(1, "Result - True");
                    }
                    else
                    {
                        Randomizer();
                        ans = GetBin(currentDataFileName);
                        //ans = new byte[] { 4, 0 }; // * A Pokémon is present in the GTS.
                        //BGW_GTS.ReportProgress(1, "Result - False");
                        //ans = new byte[] { 5, 0 }; // * There is no Pokémon stored.
                    }
                    break;

                case "get":
                    if (File.Exists(currentDataFileName))
                    {
                        ans = File.ReadAllBytes(currentDataFileName);
                        BGW_GTS.ReportProgress(1, "Get");
                    }
                    break;

                case "return":
                    BGW_GTS.ReportProgress(1, "Return");
                    break;

                case "delete":
                    if (File.Exists(currentDataFileName))
                    {
                        if (currentDataFileName == string.Empty)
                        {
                            Randomizer();
                        }


                        bin = GetBin(currentDataFileName);
                        FileInfo fi        = new FileInfo(currentDataFileName);
                        string   pkmSpecie = Pokemon.dPKMSpecies[BitConverter.ToUInt16(bin, 236)];
                        BGW_GTS.ReportProgress(1, " * Sending " + pkmSpecie + " ( " + fi.Name + " )  to " + sk.RemoteEndPoint.ToString());

                        Randomizer();
                        PostSendChanger();
                    }
                    break;

                case "post":
                    ans = new byte[] { 0xc, 0 };
                    break;

                case "post_finish":
                    ans = new byte[] { 1, 0 };
                    break;

                case "search":
                    Pokemon.InitializeDictionaries();
                    byte[] postdata = data.ToList().GetRange(0, 2).ToArray();
                    UInt16 pkmnnr   = BitConverter.ToUInt16(postdata, 0);
                    string pkmnname = Pokemon.dPKMSpecies[pkmnnr];
                    BGW_GTS.ReportProgress(1, "Searched for: #" + pkmnnr + " " + pkmnname);
                    break;
                }
                Encoding E = Encoding.GetEncoding("iso-8859-1");
                ansStr = E.GetString(ans);
            }

            SendResp(ref sock, ansStr);
        }
        private void BGW_GTS_DoWork(object sender, DoWorkEventArgs e)
        {
            BGW_GTS.ReportProgress(1, "GTS started...");
            Socket serv = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            serv.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            try
            {
                serv.Bind(new IPEndPoint(IPAddress.Any, 80));
            }
            catch (System.Net.Sockets.SocketException)
            {
                BGW_GTS.ReportProgress(1, "Server could not be started (Port 80 already used)");
                return;
            }

            serv.Listen(50);
            List <Socket> clients = new List <Socket>();

            SocketAsyncEventArgs saea  = new SocketAsyncEventArgs();
            bool readyToContinueAccept = true;
            EventHandler <SocketAsyncEventArgs> clientAccepted = (sendr, eventargs) => // True Async request handling.
            {
                readyToContinueAccept = true;                                          // AcceptAsync finished.
                if (eventargs.SocketError != SocketError.Success)
                {
                    return;                             // did the AcceptAsync succeed? if not, quit.
                }
                Socket client = eventargs.AcceptSocket; // get the new Socket (duh)

                ThreadPool.QueueUserWorkItem(si =>
                {
                    try
                    {
                        clients.Add(client);
                        asyncReq(client);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        if (clients.Contains(client))
                        {
                            clients.Remove(client);
                        }
                        client.Close();
                    }
                });
            };

            saea.Completed += clientAccepted;
            Action continueAccept = () =>
            {
                saea.AcceptSocket = null;
                if (!serv.AcceptAsync(saea))
                {   // AcceptAsync completed synchronously, call ClientAccepted
                    clientAccepted(null, saea);
                }
            };

            while (true)
            {
                if (!BGW_GTS.CancellationPending)
                {
                    if (readyToContinueAccept) // has the previous AcceptAsync finished?
                    {
                        // if yes, launch another
                        readyToContinueAccept = false;
                        continueAccept();
                    } // if not, wait 30 ms and check again
                }
                else
                {
                    // cancellation pending
                    break; // let's quit
                }

                Thread.Sleep(30);
            }
            foreach (Socket client in clients)
            {
                if (client.Connected)
                {
                    client.Close();
                }
            }
            serv.Close(); // this will call clientAccepted with saea.SocketError != SocketError.Success. It will do nothing.
        }
예제 #6
0
        private void asyncReq(Socket sk)
        {
            string ansStr = null;

            byte[]    ans   = { };
            ReqStruct reqst = default(ReqStruct);

            byte[] data = new byte[512];

            try
            {
                reqst = GetReq(ref sk);
            }
            catch (Exception ex)
            {
                BGW_GTS.ReportProgress(1, "Got wrong request, probably not from a DS. Error was : " + ex.Message);
                return;
            }

            Socket  sock = reqst.sock;
            Request req  = reqst.req;

            string pid = req.getvars["pid"];

            //BGW_GTS.ReportProgress(1, "Client " + sock.RemoteEndPoint.ToString());
            //BGW_GTS.ReportProgress(1, "Requesting : " + req.RequestedPage());


            byte[] bin = null;
            if (!CB_GTS_SendPKMN.Checked)
            {
                currentDataFileName = "";
            }
            else
            {
                if (CB_GTS_SendPKMN.Checked && RB_GTS_SendOne.Checked && currentDataFileName == "")
                {
                    currentDataFileName = TB_GTS_SendPKMN.Text;
                }
                else
                if (CB_GTS_SendPKMN.Checked && RB_GTS_SendFolder.Checked)
                {
                    do
                    {
                        if (PKMfromFolder.Count > 0)
                        {
                            currentDataFileName = PKMfromFolder[0];
                            if (!File.Exists(currentDataFileName))
                            {
                                PKMfromFolder.RemoveAt(0);
                                BGW_GTS.ReportProgress(1, "The file doesn't exist any more: " + currentDataFileName);
                            }
                            //FileInfo FI = new FileInfo(currentDataFileName);
                        }
                        else
                        {
                            currentDataFileName = "";
                            BGW_GTS.ReportProgress(3);
                        }
                    } while (!File.Exists(currentDataFileName) && PKMfromFolder.Count > 0);
                }
            }
            bin = GetBin(currentDataFileName);

            if (req.getvars.Count == 1)
            {
                ansStr = RandStr(32);
            }
            else
            {
                byte[] encrypted_data = System.Convert.FromBase64String(req.getvars["data"].Replace("-", "+").Replace("_", "/"));
                data = Decrypt_data(encrypted_data);
                data = data.ToList().GetRange(4, data.Length - 4).ToArray();

                switch (req.action)
                {
                case "info":
                    BGW_GTS.ReportProgress(1, "Someone has entered the GTS...");
                    ans = new byte[] { 1, 0 };

                    break;

                case "setProfile":
                    ans = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };

                    break;

                case "result":
                    if (File.Exists(currentDataFileName))
                    {
                        //ans = File.ReadAllBytes(currentDataFileName);
                        ans = bin;
                        //ans = new byte[] { 4, 0 }; // * A Pokémon is present in the GTS.
                    }
                    else
                    {
                        //ans = new byte[] { 4, 0 }; // * A Pokémon is present in the GTS.

                        ans = new byte[] { 5, 0 };     // * There is no Pokémon stored.
                    }
                    break;

                case "get":
                    if (File.Exists(currentDataFileName))
                    {
                        ans = File.ReadAllBytes(currentDataFileName);
                    }
                    break;

                case "return":
                case "delete":
                    if (File.Exists(currentDataFileName))
                    {
                        string pkmSpecie = Pokemon.dPKMSpecies[BitConverter.ToUInt16(bin, 236)];
                        BGW_GTS.ReportProgress(1, " * Sending " + pkmSpecie + " back to the game...");
                        //File.Delete(currentDataFileName);
                        if (CB_GTS_SendPKMN.Checked && RB_GTS_SendFolder.Checked && PKMfromFolder.Contains(currentDataFileName))
                        {
                            PKMfromFolder.Remove(currentDataFileName);
                            do
                            {
                                if (PKMfromFolder.Count > 0)
                                {
                                    currentDataFileName = PKMfromFolder[0];
                                    FileInfo FI       = new FileInfo(currentDataFileName);
                                    int      actCount = (CountPKMfromFolder - PKMfromFolder.Count) + 1;
                                    BGW_GTS.ReportProgress(1, "Next Pkm (" + actCount + " of " + CountPKMfromFolder + "): " + FI.Name);
                                    if (!File.Exists(currentDataFileName))
                                    {
                                        BGW_GTS.ReportProgress(1, "The file doesn't exist any more: " + currentDataFileName);
                                        PKMfromFolder.RemoveAt(0);
                                    }
                                }
                                else
                                {
                                    currentDataFileName = "";
                                    BGW_GTS.ReportProgress(1, "All pokemon from the folder have been sent.");
                                    BGW_GTS.ReportProgress(3);
                                }
                            } while (!File.Exists(currentDataFileName) && PKMfromFolder.Count > 0);
                        }
                    }

                    ans = new byte[] { 1, 0 };

                    break;

                case "post":

                    try
                    {
                        byte[] binData  = data.ToList().GetRange(0, 236).ToArray();
                        byte[] postData = data.ToList().GetRange(236, data.Length - 236).ToArray();

                        byte[] pkmData       = Pokemon.DecryptPokemon(binData);
                        string pkmSpecie     = Pokemon.dPKMSpecies[BitConverter.ToUInt16(postData, 0)];
                        byte   pkmLevel      = postData[3];
                        string pkmGenderName = null;
                        switch (postData[2])
                        {
                        case 1:
                            pkmGenderName = "male";

                            break;

                        case 2:
                            pkmGenderName = "female";

                            break;

                        default:
                            pkmGenderName = "genderless";
                            break;
                        }

                        string filename = Application.StartupPath + "\\PKMs\\" + DateTime.Now.Ticks + "_" + pkmSpecie + "_" + pid + ".pkm";
                        File.WriteAllBytes(filename, pkmData);
                        //File.WriteAllBytes("Current\current_" & pid & ".pkm", pkmData)
                        //File.WriteAllBytes(currentDataFileName, data);

                        BGW_GTS.ReportProgress(1, " * A " + pkmSpecie + " (lvl " + pkmLevel + ", " + pkmGenderName + ") was deposited and converted to .pkm.");
                        BGW_GTS.ReportProgress(1, " * Filename : " + filename);
                        if (CB_GTS_SendAfterReceive.Checked)
                        {
                            BGW_GTS.ReportProgress(2, filename);
                            //TB_GTS_SendPKMN.Text = filename;
                            currentDataFileName = filename;
                        }
                        currentDataFileName = filename;
                        bin = GetBin(currentDataFileName);
                        if (!CB_GTS_Reject.Checked)
                        {
                            ans = new byte[] { 1, 0 }
                        }
                        ;
                        else
                        {
                            ans = new byte[] { 0xc, 0 }
                        };
                    }
                    catch
                    {
                        BGW_GTS.ReportProgress(1, "Error, sending '0xc'.");
                        ans = new byte[] { 0xc, 0 };
                    }


                    break;

                case "post_finish":
                    ans = new byte[] { 1, 0 };
                    break;

                case "search":
                    Pokemon.InitializeDictionaries();
                    byte[] postdata = data.ToList().GetRange(0, 2).ToArray();
                    UInt16 pkmnnr   = BitConverter.ToUInt16(postdata, 0);
                    string pkmnname = Pokemon.dPKMSpecies[pkmnnr];
                    BGW_GTS.ReportProgress(1, "Searched for: #" + pkmnnr + " " + pkmnname);
                    break;
                }
                Encoding E = Encoding.GetEncoding("iso-8859-1");
                ansStr = E.GetString(ans);
            }

            SendResp(ref sock, ansStr);
        }