Beispiel #1
0
 private void button1_Click_1(object sender, EventArgs e)
 {
     BtnClick(bGetMrpStatus, delegate()
     {
         RepProtocol.MrpStatus r = repProtocol.GetMrpStatus();
         Invoke(delegate()
         {
             ObjectDumper.Write(r, 0, log);
         });
     });
 }
Beispiel #2
0
        private void button16_Click(object sender, EventArgs e)
        {
            string nfr = textNFR.Text;

            BtnClick(bSetNFR, delegate()
            {
                RepProtocol.MrpStatus status = repProtocol.GetMrpStatus();
                if (status.NFR.Length > 0)
                {
                    throw new Exception("NFR já cadastrada");
                }
                repProtocol.SetNFR(nfr);
            });
        }
        public string DoPostRequest(string uri, Dictionary <string, string> param, RepProtocol instance, RepProtocol.ErrorCodes[] notRetriableErrors = null, bool authenticate = true)
        {
            Exception e = new TimeoutException();

            for (int i = 0; i < Retries; i++)
            {
                try
                {
                    string rawParams    = "";
                    string bodyToDigest = "";
                    if (param != null)
                    {
                        foreach (KeyValuePair <string, string> kvp in param)
                        {
                            rawParams    += EscapeUrl(kvp.Key) + "=" + EscapeUrl(kvp.Value) + "&";
                            bodyToDigest += EscapeUrl(kvp.Value);
                        }
                        // NÃO descomentar a linha abaixo - o protocolo remoto depende do & no final para validar a assinatura corretamente!
                        //rawParams = rawParams.Substring(0, rawParams.Length - 1);
                    }
                    if (authenticate)
                    {
                        if (lastNfrChanged)
                        {
                            TimeSpan timeDiff = DateTime.Now - lastNsrTime;
                            if (timeDiff < NsrCooldown)
                            {
                                System.Threading.Thread.Sleep(NsrCooldown - timeDiff);
                            }
                            Trace.WriteLine("Getting MRP Status");
                            RepProtocol.MrpStatus mrpStatus = instance.GetMrpStatus();
                            nfrValue      = long.Parse(mrpStatus.NFR);
                            nfrLength     = mrpStatus.NFR.Length;
                            lastNsrValue  = long.Parse(mrpStatus.LastNSR);
                            lastNsrLength = mrpStatus.LastNSR.Length;
                            Trace.WriteLine("LastNfrChanged set to FALSE");
                        }
                        byte[] aesKey     = System.Security.Cryptography.SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(bodyToDigest));
                        string authString =
                            "GERTEC\n" +
                            "MARQUE PONTO G4\n" +
                            "NFR:" + nfrValue.ToString().PadLeft(nfrLength, '0') + "\n" +
                            "NSR:" + lastNsrValue.ToString().PadLeft(lastNsrLength, '0') + "\n" +
                            "SENHA:" + password
                        ;
                        // gerar digest criptografado de autenticação
                        Trace.WriteLine("**** AUTHENTICATED POST ****");
                        Trace.WriteLine("Post Data Str.:\n" + bodyToDigest);
                        Trace.WriteLine("Post Data Bin.:\n" + BitConverter.ToString(Utils.Encoding.GetBytes(bodyToDigest)).Replace("-", ""));
                        Trace.WriteLine("Auth Data Str.:\n" + authString);
                        Trace.WriteLine("Auth Data Bin.:\n" + BitConverter.ToString(Utils.Encoding.GetBytes(authString)).Replace("-", ""));
                        List <byte> b;
                        b = new List <byte>(SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(bodyToDigest)));
                        Trace.WriteLine("Post Data SHA1: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        b.RemoveRange(16, 4);
                        Trace.WriteLine("Post Data SHA1 16 MSB: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        byte[] rawParamsSha1Msb = b.ToArray();
                        b = new List <byte>(SHA1.Create().ComputeHash(Utils.Encoding.GetBytes(authString)));
                        Trace.WriteLine("Auth Data SHA1: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        b.RemoveRange(16, 4);
                        Trace.WriteLine("Auth Data SHA1 16 MSB: " + BitConverter.ToString(b.ToArray()).Replace("-", ""));
                        byte[]             authStringSha1Msb = b.ToArray();
                        SymmetricAlgorithm aes = Aes.Create();
                        aes.Mode    = CipherMode.ECB;
                        aes.KeySize = 128;
                        aes.Padding = PaddingMode.None;
                        ICryptoTransform t  = aes.CreateEncryptor(authStringSha1Msb, null);
                        MemoryStream     ms = new MemoryStream();
                        CryptoStream     cs = new CryptoStream(ms, t, CryptoStreamMode.Write);
                        cs.Write(rawParamsSha1Msb, 0, rawParamsSha1Msb.Length);
                        cs.FlushFinalBlock();
                        byte[] encAuth = ms.ToArray();
                        Trace.WriteLine("AES(Post Data SHA1 16 MSB, Auth Data SHA1 16 MSB): " + BitConverter.ToString(encAuth).Replace("-", ""));
                        cs.Close();
                        ms.Close();
                        string encAuthString = BitConverter.ToString(encAuth).Replace("-", "");
                        rawParams += "AUT=" + cpf + ";" + encAuthString;
                    }
                    Trace.WriteLine("Post body: " + rawParams);
                    // fazer request
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                    req.Method      = "POST";
                    req.Timeout     = Timeout;
                    req.ContentType = "application/x-www-form-urlencoded";
                    StreamWriter sw = new StreamWriter(req.GetRequestStream(), Utils.Encoding);
                    sw.Write(rawParams);
                    sw.Close();
                    HttpWebResponse resp         = (HttpWebResponse)req.GetResponse();
                    StreamReader    rsr          = new StreamReader(resp.GetResponseStream(), Utils.Encoding);
                    string          responseBody = rsr.ReadToEnd();
                    rsr.Close();
                    resp.Close();
                    lastNfrChanged = false;
                    ThrowIfError(responseBody);
                    lastNsrTime    = DateTime.Now;
                    lastNfrChanged = true;
                    Trace.WriteLine("Response ok. LastNfrChanged set to TRUE");
                    return(responseBody);
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.Timeout)
                    {
                        Trace.WriteLine("Timeout. Retrying...");
                        e = ex;
                    }
                    else
                    {
                        Trace.WriteLine("HTTP error. Retrying...");
                        throw ex;
                    }
                }
                catch (RepProtocolException ex)
                {
                    if (notRetriableErrors != null && notRetriableErrors.Contains(ex.ErrorCode))
                    {
                        Trace.WriteLine("Not retriable error.");
                        i = Retries;
                    }
                    if (ex.ErrorCode == RepProtocol.ErrorCodes.MT_RES_ERROR_INVALID_HASH_ADDRESS)
                    {
                        Trace.WriteLine("Auth error. Retrying...");
                    }
                    lastNfrChanged = true;
                    e = ex;
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Unknown error. Sleeping and retrying...");
                    System.Threading.Thread.Sleep(500);
                    e = ex;
                }
            }
            throw e;
        }