Apple push notification doen't reach in prod - iphone

I prepared an iphone application that gets push notification messages. I can send push message using with 2195 port , gateway.sandbox.push.apple.com and local p12 file
My application in appstore, now i'm using gateway.push.apple.com and distribution p12 file, but messages cannot reach to real application (in appstore)
Device ids are different in local and prod version, I know this so i'm trying to send new device id from .net
Same codes works in local and i can send messages but when i send push message to real application, no message reach to iphone with the same codes. I have no error during this period.
What can i do?
my c# code like below. How can i solve my problem? There is no error but message cannot reach to devices with distribution cert.
int port = 2195;
String hostname = "gateway.push.apple.com";
String certificatePath = HttpContext.Current.Server.MapPath("distribution.p12");
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "xxx", X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, true);
}
catch (Exception e)
{
throw (e);
client.Close();
return;
}
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0); //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)
//String deviceID = "f1430c99 910d292d 2f756294 f2f6b348 153bc215 d5404447 16b294eb fdb9496c";
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"" + Mesaj + "\",\"badge\":0,\"sound\":\"default\"}}";
writer.Write((byte)0);
writer.Write((byte)payload.Length);
byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();

After enabled your push notification in your profile appid.
Then only you can able to get device token from the running device. Based on the device token you may send notification.
development process : gateway.sandbox.push.apple.com port 2195.
distribution process : gateway.push.apple.com port 2195.
refer from this links: https://stackoverflow.com/a/10045210/510814
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html

Related

UWP - StreamSocket connection error for some connections

We have 2 UWP apps. One app shares data to the other app through StreamSocket. The server app will send data to client app. There will be 30-40 or more devices running the client app and connecting to the server's socket to receive data.
When we test with one client app, all the data sharing happens without any issue. But when we started testing with about 10 devices using the client app, sometimes some apps don't receive data. And there seems to be an error saying A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
In general it get shared to most of the devices, but few fails sometimes randomly. What could be the reason for this? Is there a connection limit to connect to a socket with given IP and port using Stream Socket?
Here is some parts of our code. Please let me know what we have to correct here to avoid getting that error.
Server side
public async Task StartServer(string serverIp, string serverPort)
{
try
{
HostName serverAddress = new HostName(serverIp);
//Create a StreamSocketListener to start listening for TCP connections.
StreamSocketListener socketListener = new StreamSocketListener();
//Hook up an event handler to call when connections are received.
socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
//Start listening for incoming TCP connections on the specified port.
await socketListener.BindEndpointAsync(serverAddress, serverPort);
}
catch (Exception e)
{
}
}
private async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
await Task.Run(() => ShareFile(args.Socket));
}
catch (Exception e)
{
}
}
Client side
public async Task ServerConnect(string serverIP, string serverPort)
{
try
{
HostName serverAddress = new HostName(serverIP);
StreamSocket socket = new StreamSocket();
socket.Control.KeepAlive = false;
// Connect to the server.
await socket.ConnectAsync(serverAddress, serverPort, SocketProtectionLevel.PlainSocket);
}
catch (Exception e)
{
}
}
Also would like to get these clarified
-What is the difference between BindServiceNameAsync and BindEndpointAsync? Most examples seems to use the first one. When should we use the second one?
-If we call sender.Dispose(); in SocketListener_ConnectionReceived, will that affect the other clients trying to join the same socket?
-In the ShareFile() function, if we close args.Socket() after sending data, can it close the socket before the client actually read the data from that side?

PDF File size of 50kb increases dramatically up to 9mb after signing it with previously using Itext Java Application

I was a using a custom build itext based java application for digitally signing pdf files.
Every thing was working fine for last one year but recently the size of the output signed pdf file drastically increasing up to 10 MB for just a 50kb source pdf file.
Earlier for a 50 kb file ,the output was less than 300 kb.
Kindly find the code snippets
public void sign(String src, String dest,
Certificate[] chain, PrivateKey pk,
String digestAlgorithm, String provider, MakeSignature.CryptoStandard subfilter,
String reason, String location,
Collection<CrlClient> crlList,
OcspClient ocspClient,
TSAClient tsaClient,
int estimatedSize)
throws GeneralSecurityException, IOException, DocumentException {
// Creating the reader and the stamper
PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
ExternalDigest digest = new BouncyCastleDigest();
MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
}
public PrivateKey getPrivateKey(String DLL,String PIN,String usage) throws GeneralSecurityException, IOException {
LoggerFactory.getInstance().setLogger(new SysoLogger());
String config = "name=eToken\n" + "library=" + DLL + "\n";
ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
Provider providerPKCS11 = new SunPKCS11(bais);
Security.addProvider(providerPKCS11);
//System.out.println(providerPKCS11.getName());
BouncyCastleProvider providerBC = new BouncyCastleProvider();
Security.addProvider(providerBC);
PrivateKey pk = null;
KeyStore ks = KeyStore.getInstance("PKCS11");
try{
ks.load(null, PIN.toCharArray());
String alias = (String)ks.aliases().nextElement();
java.util.Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
//System.out.println(alias);
X509Certificate c = (X509Certificate) ks.getCertificate(alias);
final boolean[] keyUsage = c.getKeyUsage();
if(usage=="0" &&(keyUsage[0] || keyUsage[1]))
{
//System.out.println("Digital Signature");
pk = (PrivateKey)ks.getKey(alias, PIN.toCharArray());
this.providerPKCS11 = providerPKCS11.getName();
this.pub_key = c;
this.chain = ks.getCertificateChain(alias);
for (int i = 0; i < this.chain.length; i++) {
// System.out.println(chain[i]);
X509Certificate cert = (X509Certificate)chain[i];
String tsaUrl = CertificateUtil.getTSAURL(cert);
if (tsaUrl != null) {
tsaClient = new TSAClientBouncyCastle(tsaUrl);
break;
}
}
crlList.add(new CrlClientOnline(chain));
}
else if(usage=="2" &&keyUsage[2])
{
//System.out.println("Encryption");
pk = (PrivateKey)ks.getKey(alias, PIN.toCharArray());
this.pub_key = c;
}
//alias1=alias;
}
}
catch(Exception e)
{
System.out.println("Key Store Not loaded .. PIN entered may be incorrect");
}
return pk;
}
Main function is
token.sign("D:\\15 SAMPLE PDF FILES\\15 SAMPLE PDF FILES\\"+listOfFiles[i].getName(), "D:\\15 SAMPLE PDF FILES\\15 SAMPLE PDF FILES\\sign\\singn_"+listOfFiles[i].getName(), token.chain, PK_sign, DigestAlgorithms.SHA256, token.providerPKCS11, MakeSignature.CryptoStandard.CMS,
"Sign", "Kottayam", token.crlList, token.ocspClient, token.tsaClient, 0);
Last week our firewall changed. Is that the problem?
If the process of signing a PDF suddenly results in much bigger files than before, the reason often is related to embedded validation related information, in particular to embedded CRLs (certificate revocation lists) which may be very large.
The cause might be purely inside the PKI. E.g. if lots of certificates suddenly are revoked after the associated signature creation devices have been found to be insecure, a formerly small CRL may suddenly become very large.
It might also be a matter of connectivity. For example
if the OCSP responder of the PKI was accessible before but suddenly isn't anymore, the signing process might use the CRL instead; or
if the revocation information was not accessible at all before and suddenly is, the signing process also might start using the CRL.
As it turned out, the latter was the case here, as the OP reported:
It was because of the firewall change. Initially the server will not look for crl url and so it doesnt embedd crl since it is not connecting to internet because of the firewall authentication. Unfortunately the firewall change cleared all the authentication and hence the server got the internet access and crl embedds in the signature.
Something like this can be prevented by disallowing use of CRLs. In the case at hand, the Collection<CrlClient> crlList parameter of the sign method can simply be left empty.
Essentially, if you don't want to include CRLs or OCSP responses, don't provide the signing process with means to request them.

UWP DatagramsSocket doesn't not fire MessageReceived

I'm working on a UWP application which should communicate via TCP/UDP to a remote device. My issue is that the UWP app successfully sends UDP messages to the remote device, but does not receive the replies.
Here follows the code extracted from the app (simplified):
async Task TestUdpIP()
{
// Writer to the DatagramSocket
DataWriter writer;
using (var udpClient = new DatagramSocket())
{
try
{
// UDP Socket binding
udpClient.MessageReceived += UdpClient_MessageReceived;
var controllerName = new Windows.Networking.HostName(controllerIpAddress.ToString());
await udpClient.BindEndpointAsync(controllerName, controllerIpPort.ToString());
var remoteHostName = new Windows.Networking.HostName(hostIpAddres.ToString());
await udpClient.ConnectAsync(remoteHostName, remoteHostPort.ToString());
// Create a message to send
string message = "Some message";
// Reset the counter of messages received back from the remote robot
messagesReceived = 0;
// Send the message
writer = new DataWriter(udpClient.OutputStream);
writer.WriteString(message);
await writer.StoreAsync();
// Wait for robot status messages
await Task.Delay(5000);
}
catch
{
}
}
}
void UdpClient_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
// Just increment the number of messages received
messagesReceived++;
}
However the UdpClient_MessageReceived handler does not fire. I'm sure that UDP messages are correctly sent from the UWP app and that the remote device replies back as shown in the following screenshot from Wireshark (the test has been taken on the same PC where the UWP app is running)
.
(IP Address, Port) details are shown in the following list to better explain the picture above
UWP application: (192.168.1.108, 19000) to send and receive.
Remote device: (192.168.1.152, 15999) to receive and (192.168.1.152, 54697) to send
Note: this is a similar question, where the answer says that for whatever reason the DatagramSocket should fire some messages before being able to receive. In my example a message is sent out however the message received handler does not fire anyway.
Note: The UWP app has been granted the internet (client) and the internet (client and server) capabilities
Note: I've tried also this (more readable) approach to bind the inbound/outbound datagram socket on the UWP app obtaining the same results:
// UDP Socket binding
var controllerName = new HostName(controllerIpAddress.ToString());
var remoteHostName = new HostName(hostIpAddres.ToString());
EndpointPair endpointpar = new EndpointPair(controllerName,
controllerIpPort.ToString(),
remoteHostName,
remoteHostPort.ToString());
udpClient.MessageReceived += UdpClient_MessageReceived;
await udpClient.ConnectAsync(endpointpar);
Where is the issue? Many thanks!
Please try to also add the Private Networks (Client & Server) capability in your app's manifest.
On other hand, you can try the Official DatagramSocket sample to see whether the both devices can communicate with each other.
After some experimenting, I came out with the idea of using two different DatagramSocket instances: one to send out UDP messages, and one to listen for incoming messages. With this code, I've been able to send UDP messages to the remote device (as before) and also I've been able to receive UDP messages from the remote device.
async Task TestUdpIP_DifferentPorts()
{
// Writer to the DatagramSocket
DataWriter writer;
// Inbound and outbound DatagramSocket
DatagramSocket udpListener = new DatagramSocket();
DatagramSocket udpSender = new DatagramSocket();
try
{
// String containing the serializaed message
string serializedMessage = "Some message";
var controllerName = new HostName(controllerIpAddress.ToString());
var remoteHostName = new HostName(hostIpAddres.ToString());
// Bind listener
udpListener.MessageReceived += UdpClient_MessageReceived;
await udpListener.BindEndpointAsync(controllerName, controllerIpPort.ToString());
// Connect sender
await udpSender.ConnectAsync(remoteHostName, remoteHostPort.ToString());
// Reset the counter of messages received back from the remote robot
messagesReceived = 0;
// Send the message
writer = new DataWriter(udpSender.OutputStream);
writer.WriteString(JsonConvert.SerializeObject(message));
await writer.StoreAsync();
// Wait for robot status messages
await Task.Delay(1000);
}
catch (Exception ex)
{
// Some exception handling
}
udpSender.Dispose();
udpListener.Dispose();
}
void UdpClient_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
{
// Just increment the number of messages received
messagesReceived++;
}
With this approach only the IP port (or service name) of the inbound listener needs to be specified. The framework will choose the next available outbound IP port.
Note: If I understand well the DatagramSocket.ConnectAsync(EndpointPair) documentation, the same DatagramSocket instance can be used to send and listen for incoming message, so I could not figure out the need for two different instances. From the documentation:
This ConnectAsync(EndPointPair) method on a DatagramSocket is used to define the local and remote endpoint where datagrams will be sent when using the OutputStream property. This method also restricts remote IP addresses of packets that will be accepted to the remote hostname in the endpointPair parameter. Only incoming packets that match the remote endpoint in the endpointPair parameter will trigger the MessageReceived event on the DatagramSocket.

read port on server with socket programming

i have a trouble with my socket programming code.
when i use below:
var ipaddress = IPAddress.Parse("192.168.1.100");
IPAddress add = new IPAddress(ipaddress.GetAddressBytes());
TcpListener tcpListener = null;
tcpListener = new TcpListener(add, 53);
tcpListener.Start();
Console.WriteLine("Waiting for a connection...");
while (true)
{
Thread.Sleep(10);
TcpClient tcpClient = tcpListener.AcceptTcpClient();
//Read the data stream from the client.
byte[] bytes = new byte[512];
NetworkStream stream = tcpClient.GetStream();
stream.Read(bytes, 0, bytes.Length);
SocketHelper helper = new SocketHelper();
helper.processMsg(tcpClient, stream, bytes);
}
i receive this error:
Additional information: Only one usage of each socket address (protocol/network address/port) is normally permitted
but i changed my cod to below :
static Socket sktListener;
var ipaddress = IPAddress.Parse("192.168.1.100");
IPAddress add = new IPAddress(ipaddress.GetAddressBytes());
sktListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(add, 53);
sktListener.Connect(ipLocal);
if (sktListener.Connected)
{
byte[] bytes = new byte[512];
int i = sktListener.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
but it dose not any work. and stop on this line
int i = sktListener.Receive(bytes);
IPAddress.Parse() returns a new IPAddress object, you do not need to create a second IPAddress object from the first object's bytes:
IPAddress add = IPAddress.Parse("192.168.1.100");
Regarding the usage error in the first code, it means 192.168.1.100:53 is already in use by another socket.
Your second code is not creating a server, it is creating a client that connects to a server. Assuming these codes are meant to work together, then it makes sense why Receive() is blocking - your client is expecting to receive data that your server is not sending. Your server code is expecting a new client to send data, but your client is not sending anything.

Image Sending to a server using SocketCommunication

Using J2ME I need to send a JPEG image to a server using Socket Communication. Can anyone send me a sample code for my application?
Take a look at this article from Sun Developer Network. It has some minimalistic examples and should give you some ideas.
...
SocketConnection client = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
// set application-specific options on the socket. Call setSocketOption to set other options
client.setSocketOption(DELAY, 0);
client.setSocketOption(KEEPALIVE, 0);
InputStream is = client.openInputStream();
OutputStream os = client.openOutputStream();
// send something to server
os.write("some string".getBytes());
// read server response
int c = 0;
while((c = is.read()) != -1) {
// do something with the response
}
// close streams and connection
is.close();
os.close();
client.close();
...