GCM ERROR 404 - Native socket https connection over openssl without gcm class - c

I want to connect to the gcm service without a gcm class (only native socket with openssl).
The ssl handshake works fine. But when I send the post request to https
server i got the http 404 error.
If I uncomment the line
"//strcat(FormBuffer1, "Host: gcm-http.googleapis.com\r\n");", the server returns nothing and the connection seems to hang.
I tried gcm-http.googleapis.com and android.googleapis.com.
Is there anywhere an https post example for GCM? I found only code sample which use gcm classes.
Thanks for your answers!
My C source:
//gcc -lssl -lcrypto sock.c -o sock.o
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/time.h>
#include <stdlib.h>
#include <memory.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <stdarg.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
int main(int argc, char *argv[]){
int sd;
struct hostent *host;
struct sockaddr_in addr;
BIO *outbio = NULL;
SSL_METHOD *method;
SSL_CTX *ctx;
SSL *ssl;
char *req;
int req_len;
char hostname[] = "gcm-http.googleapis.com"; // https://gcm-http.googleapis.com/gcm/send
//char hostname[] = "www.gmx.de"; // https://gcm-http.googleapis.com/gcm/send
char certs[] = "/etc/ssl/certs/ca-certificates.crt";
int port = 443;
int bytes;
char buf[1];
char FormBuffer1[1024];
char FormBuffer2[1024];
int ContentLength;
char ContentLengthBuffer[10];
// added this to test
char dest_url[] = "https://gcm-http.googleapis.com/gcm/send";
BIO *certbio = NULL;
X509 *cert = NULL;
X509_NAME *certname = NULL;
BIO *outbio2 = NULL;
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
SSL_load_error_strings();
outbio = BIO_new(BIO_s_file());
outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
if(SSL_library_init() < 0){
BIO_printf(outbio, "Could not initialize the OpenSSL library !\n");
}
method = SSLv23_client_method();
ctx = SSL_CTX_new(method);
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
host = gethostbyname(hostname);
sd = socket(AF_INET, SOCK_STREAM, 0);
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) == -1 ) {
BIO_printf(outbio, "%s: Cannot connect to host %s [%s] on port %d.\n", argv[0], hostname, inet_ntoa(addr.sin_addr), port);
}
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sd);
SSL_connect(ssl);
// try something here
/* Get the remote certificate into the X509 structure */
printf("SSL_get_peer_certificate(ssl) \n");
cert = SSL_get_peer_certificate(ssl);
if (cert == NULL)
printf("Error: Could not get a certificate from: %s.\n", dest_url);
else
printf("Retrieved the server's certificate from: %s.\n", dest_url);
printf("\n");
/* extract various certificate information */
certname = X509_NAME_new();
certname = X509_get_subject_name(cert);
/* display the cert subject here */
BIO_printf(outbio, "Displaying the certificate subject data:\n");
X509_NAME_print_ex(outbio, certname, 0, 0);
BIO_printf(outbio, "\n\n");
/*
Format:
Content-Type:application/json
Authorization:key=....
{
"to" : ".......",
"data" : {
...
},
}*/
//req = "GET / HTTP/1.1\r\n Host: gcm-http.googleapis.com/gcm/send\r\n\r\n";
// header
strcpy(FormBuffer2, "{\"to\" : \"/topics/global\", \n \"data\": { \"message\" : \"Test123\", },\n }\n\r\n");
ContentLength = strlen(FormBuffer2);
sprintf(ContentLengthBuffer, "%d", ContentLength);
strcpy(FormBuffer1, "POST ");
strcat(FormBuffer1, "/gcm/send");
strcat(FormBuffer1, " HTTP/1.1\r\n");
//strcat(FormBuffer1, "Host: gcm-http.googleapis.com\r\n");
//strcat(FormBuffer1, "Host: android.googleapis.com\r\n ");
strcat(FormBuffer1, "Content-length: ");
strcat(FormBuffer1, ContentLengthBuffer);
strcat(FormBuffer1, "\r\nContent-Type:application/json\r\n");
strcat(FormBuffer1, "Authorization:key=AIzaSyA.....\r\n");
//strcat(FormBuffer, ContentLengthBuffer); // size of actual content
//strcat_s(FormBuffer, "\n\n");
req_len = strlen(FormBuffer1);
SSL_write(ssl, FormBuffer1, req_len);
req_len = strlen(FormBuffer2);
SSL_write(ssl, FormBuffer2, req_len);
memset(buf, '\0', sizeof(buf));
bytes = SSL_read(ssl, buf, sizeof(buf));
while(bytes > 0){
write(STDOUT_FILENO, buf, bytes);
memset(buf, '\0', sizeof(buf));
bytes = SSL_read(ssl, buf, sizeof(buf));
}
SSL_free(ssl);
close(sd);
SSL_CTX_free(ctx);
}
HTTP Answer:
SSL_get_peer_certificate(ssl)
Retrieved the server's certificate from: https://gcm-http.googleapis.com/gcm/send.
Displaying the certificate subject data:
C=US, ST=California, L=Mountain View, O=Google Inc, CN=*.googleapis.com
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Content-Length: 1569
Date: Sat, 21 Nov 2015 20:26:47 GMT
Server: GFE/2.0
Connection: close
<!DOCTYPE html>
<html lang=en>
<meta charset=utf-8>
<meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
<title>Error 404 (Not Found)!!1</title>
<style>
*{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}#media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}#media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}#media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
</style>
<a href=//www.google.com/><span id=logo aria-label=Google></span></a>
<p><b>404.</b> <ins>That’s an error.</ins>
<p>The requested URL <code>/gcm/send</code> was not found on this server. <ins>That’s all we know.</ins>

Related

Using a simple C program how to load HTTPS web page

I am using a C web page loading program. When I ask for a page with an"http://" prefix it loads successfully. However, when I ask for "https://" it crashes. If I remove the "s" then I receive:
Host: a.b.c
nr 90 (90)
Full Buffer header HTTP/1.1 301 Moved Permanently
Date: Mon, 17 Oct 2022 10:02:05 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Mon, 17 Oct 2022 11:02:05 GMT
Location: https://a.b.c/ViewDocument.aspx?fileid=12345678
Server: cloudflare
This "moved" location is the original URL that I am requesting.
When this address is used in a browser it will automatically download a PDF file - which is the ultimate aim of this code.
Some relevant coding:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include <unistd.h>
#include "stdint.h"
#ifdef __linux
#include "netinet/in.h"
#include "sys/socket.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#endif
...
void receive(char *ip, char *domain, char *page){
int sockfd, portno;
struct sockaddr_in server_addr;
char header[512];
portno = 80;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1){
printf("error opening socket\n");
return;
}else{
printf("socket opened\n");
}
memset((char *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portno);
#ifdef __WIN32
server_addr.sin_addr.s_addr = inet_addr(ip);
#else
inet_pton(AF_INET, ip, &(server_addr.sin_addr) );
#endif
int err = 0;
if( (err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) ) < 0){
printf("failed to connect %d\n", err);
return;
}else{
printf("connection successful\n");
}
snprintf(header, 512, "GET %s HTTP/1.1\r\nHost: %s\r\n\r\n", page, domain);
printf("Header %s\n", header);
int nr = send(sockfd, header, tec_string_length(header), 0);
if(nr){
printf("nr %d (%u)\n", nr, tec_string_length(header));
}
char *buf;
buf = (char *) malloc(BUF_SIZE_INC * sizeof(char));
memset(buf, 0, BUF_SIZE_INC);
ssize_t bytes_received = recv(sockfd, buf, BUF_SIZE, 0);
int size = 0;
char *new_buffer = process_header(buf, &size);
memmove(buf, new_buffer, BUF_SIZE_INC - (new_buffer - buf) );
load_body(sockfd, buf, size);
puts("*****");
#ifdef __WIN32
closesocket(sockfd);
WSACleanup();
#else
close(sockfd);
#endif
}//receive*/
The code is from https://gitlab.com/greggink/youtube_episode_loading_webpage (using the main_final.c file).
Ubuntu 20.04
Thank you.

TCP socket hangs when reading response from custom HTTP request - C

I have the following code that I have written which is suppose to send a simple http request over a TCP socket, I get a response but as soon as I try to read in the loop it hangs, in the 2nd read operation (tried it manually)
if anyone has an idea of why this might fail I will appreciate it a lot
attached below is the entire code
I am running the program like this: ./http_client yahoo.com
I get this response text at first:
HTTP/1.1 301 Moved Permanently
Date: Sat, 06 Aug 2022 08:07:11 GMT
Connection: keep-alive
Server: ATS
Cache-Control: no-store, no-cache
Content-Type: text/html
Content-Language: en
X-Frame-Options: SAMEORIGIN
Location: https://www.yahoo.com/
Content-Length: 8
redirect
and then it hangs and closes the socket, it shouldn't hang at all, it should run and exit without a delay or anything
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in cli_name;
struct sockaddr_in *saddr;
char *hostname;
struct addrinfo *res;
int port = 80;
if (argc != 2) {
perror("Usage: establish tcp connection to: <hostname>\n");
exit(1);
}
hostname = argv[1];
printf("Client is alive and establishing socket connection %s.\n", hostname);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("Error opening channel");
close(sockfd);
exit(1);
}
if (0 != getaddrinfo(hostname, NULL, NULL, &res)) {
fprintf(stderr, "Error in resolving hostname %s\n", hostname);
exit(1);
}
bzero(&cli_name, sizeof(cli_name));
cli_name.sin_family = AF_INET;
saddr = (struct sockaddr_in *) res->ai_addr;
cli_name.sin_addr.s_addr = inet_addr(inet_ntoa(saddr->sin_addr));
cli_name.sin_port = htons(port);
fflush(stdout);
if (connect(sockfd, (struct sockaddr *) &cli_name, sizeof(cli_name)) < 0) {
perror("Error establishing communications");
close(sockfd);
exit(1);
}
char header[100];
int cx;
char buf[2056];
size_t byte_count = 0;
size_t sent_byte_count = 0;
cx = snprintf(header, 100, "GET / HTTP/1.1\r\nHost: %s:%d\r\n\r\n", hostname, port);
size_t total = strlen(header);
size_t sent = 0;
do {
sent_byte_count = write(sockfd, header + sent, total - sent);
if (sent_byte_count < 0)
printf("ERROR writing message to socket");
if (sent_byte_count == 0)
break;
sent += sent_byte_count;
} while (sent < total);
memset(buf,0,sizeof(buf));
while ((byte_count = read(sockfd, buf, 2054)) > 0) {
buf[byte_count] = '\0';
printf("%s", buf); // <-- give printf() the actual data size
fflush(stdout);
}
printf("Exiting now.\n");
close(sockfd);
exit(0);
}

No able to get client certificate in ssl/tls

I'm going to try TLS with mutual authentication using openssl.
However, as shown in the output results below, the client can receive a server certificate and output it, but the server has not received the client certificate
The details of my work are as follows.
Server and client certificate generation (without certificate signing through CA, just self-signing)
(1) Generating the server key and certificate.
$ openssl genrsa -des3 -out server.key 2048
$ openssl req -new -key server.key -out server.csr
$ cp server.key server.key.origin
$ openssl rsa -in server.key.origin -out server.key
$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
(2) Generating the client key and certificate.
$ openssl genrsa -des3 -out client.key 2048
$ openssl req -new -key client.key -out client.csr
$ cp client.key client.key.origin
$ openssl rsa -in client.key.origin -out client.key
$ openssl x509 -req -days 365 -in client.csr -signkey client.key -out client.crt
server.c
#define CHK_NULL(x) if((x) == NULL) exit(1);
#define CHK_ERR(err, s) if((err) == -1) { perror(s); exit(1); }
#define CHK_SSL(err) if((err) == -1) { ERR_print_errors_fp(stderr); exit(2); }
int main(void) {
int err;
int listen_sd;
int sd;
struct sockaddr_in sa_serv;
struct sockaddr_in sa_cli;
size_t client_len;
SSL_CTX *ctx;
SSL *ssl;
X509 *client_cert;
char *str;
char buf[4096];
SSL_METHOD *meth;
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
meth = TLSv1_2_server_method();
ctx = SSL_CTX_new(meth);
if(!ctx) {
ERR_print_errors_fp(stderr);
exit(2);
}
if(SSL_CTX_use_certificate_file(ctx, CERTF, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(3);
}
if(SSL_CTX_use_PrivateKey_file(ctx, KEYF, SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(4);
}
if(!SSL_CTX_check_private_key(ctx)) {
fprintf(stderr, "Private key does not match the certificate public keyn");
exit(5);
}
listen_sd = socket(AF_INET, SOCK_STREAM, 0);
CHK_ERR(listen_sd, "socket");
memset(&sa_serv, 0x00, sizeof(sa_serv));
sa_serv.sin_family = AF_INET;
sa_serv.sin_addr.s_addr = INADDR_ANY;
sa_serv.sin_port = htons(1111);
err = bind(listen_sd, (struct sockaddr*)&sa_serv, sizeof(sa_serv));
CHK_ERR(err, "bind");
err = listen(listen_sd, 5);
CHK_ERR(err, "listen");
client_len = sizeof(sa_cli);
sd = accept(listen_sd, (struct sockaddr*)&sa_cli, &client_len);
CHK_ERR(sd, "accept");
close(listen_sd);
ssl = SSL_new(ctx);
CHK_NULL(ssl);
SSL_set_fd(ssl, sd);
// to request client's certificate
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
err = SSL_accept(ssl);
CHK_SSL(err);
printf("SSL connection using %s \n", SSL_get_cipher(ssl));
client_cert = SSL_get_peer_certificate(ssl);
if(client_cert != NULL) {
printf("Client certificate: \n");
str = X509_NAME_oneline(X509_get_subject_name(client_cert), 0, 0);
CHK_NULL(str);
printf("\t subject: %s\n", str);
OPENSSL_free(str);
str = X509_NAME_oneline(X509_get_issuer_name(client_cert), 0, 0);
CHK_NULL(str);
printf("\t issuer: %s\n", str);
OPENSSL_free(str);
X509_free(client_cert);
} else {
printf("Client does not have certificate. \n");
}
err = SSL_read(ssl, buf, sizeof(buf)-1);
CHK_SSL(err);
buf[err] = 0x00;
printf("Got %d chars: %s \n", err, buf);
err = SSL_write(ssl, "I hear you/", strlen("I hear you."));
CHK_SSL(err);
close(sd);
SSL_free(ssl);
SSL_CTX_free(ctx);
return(0);
}
// client.c
#include <stdio.h>
#include <memory.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define CHK_NULL(x) if((x) == NULL) exit(1);
#define CHK_ERR(err, s) if((err) == -1) { perror(s); exit(1); }
#define CHK_SSL(err) if((err) == -1) { ERR_print_errors_fp(stderr); exit(2); }
int main(void) {
int err;
int sd;
struct sockaddr_in sa;
SSL_CTX *ctx;
SSL *ssl;
X509 *server_cert;
char *str;
char buf[4096];
SSL_METHOD *meth;
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
meth = TLSv1_2_client_method();
ctx = SSL_CTX_new(meth);
CHK_NULL(ctx);
if(SSL_CTX_use_certificate_file(ctx, "./client.crt", SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(3);
}
if(SSL_CTX_use_PrivateKey_file(ctx, "./client.key", SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stderr);
exit(4);
}
if(!SSL_CTX_check_private_key(ctx)) {
fprintf(stderr, "Private key does not match the certificate public keyn");
exit(5);
}
CHK_SSL(err);
sd = socket(AF_INET, SOCK_STREAM, 0);
CHK_ERR(sd, "socket");
memset(&sa, 0x00, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
sa.sin_port = htons(1111);
err = connect(sd, (struct sockaddr*)&sa, sizeof(sa));
CHK_ERR(err, "connect");
ssl = SSL_new(ctx);
CHK_NULL(ssl);
SSL_set_fd(ssl, sd);
err = SSL_connect(ssl);
CHK_NULL(err);
printf("SSL connection using %s \n", SSL_get_cipher(ssl));
server_cert = SSL_get_peer_certificate(ssl);
CHK_NULL(server_cert);
printf("Server certificate: \n");
str = X509_NAME_oneline(X509_get_subject_name(server_cert), 0, 0);
CHK_NULL(str);
printf("\t subject: %s \n", str);
OPENSSL_free(str);
str = X509_NAME_oneline(X509_get_issuer_name(server_cert), 0, 0);
CHK_NULL(str);
printf("\t issuer: %s \n", str);
OPENSSL_free(str);
X509_free(server_cert);
err = SSL_write(ssl, "Hello World!", strlen("Hello World!"));
CHK_SSL(err);
err = SSL_read(ssl, buf, sizeof(buf)-1);
CHK_SSL(err);
buf[err] = 0x0;
printf("Got %d chars: %s \n", err, buf);
SSL_shutdown(ssl);
close(sd);
SSL_free(ssl);
SSL_CTX_free(ctx);
return 0;
}
below is output results.
(1) server
$ ./server
SSL connection using ECDHE-RSA-AES256-GCM-SHA384
Client does not have certificate.
Got 12 chars: Hello World!
(2) client
$ ./client
SSL connection using ECDHE-RSA-AES256-GCM-SHA384
Server certificate:
subject: /C=IN/ST=WB/L=Kolkata/O=TEST-INFO-CLIENTA/OU=IT/CN=clienta.com/emailAddress=aaa#aaa.com
issuer: /C=IN/ST=WB/L=Kolkata/O=TEST-INFO-CLIENTA/OU=IT/CN=clienta.com/emailAddress=aaa#aaa.com
Got 11 chars: I hear you/
I don't know why the server's output says, "Client does not have certificate."
Although I added "SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL)" in server.c, the server does not receive the client's certificate.
ssl = SSL_new(ctx);
...
// to request client's certificate
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
You generate the SSL object from the context and after that you change the context. This has no effect on the created SSL object, which means that the server will not request the client certificate in the first place and thus the client will not provide a certificate.
Once you've put SSL_CTX_set_verify in the correct place you will notice that the server will not be able to verify the client certificate. This is because the certificate is not signed by a CA trusted by the server. See SSL_CTX_load_verify_locations for how to set the trusted root CA.

503 - Service temporarily unavailable

I need simple HTTP client on Raspberry PI zero with Raspbian. I used few example codes, but when i send about 7 requests then i can download just page with this error:
503 Service temporarily unavailable
There is no available fastcgi process to fullfill your request.
One of used codes:
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netdb.h>
#include <unistd.h>
#define SA struct sockaddr
#define MAXLINE 4096
#define MAXSUB 200
ssize_t process_http(int sockfd, char *host, char *page)
{
ssize_t n;
snprintf(sendline, MAXSUB,
"GET %s\r\n"
"Host: %s\r\n"
"Connection: close\n"
"\n", page, host);
write(sockfd, sendline, strlen(sendline));
while ((n = read(sockfd, recvline, MAXLINE)) > 0)
{
recvline[n] = '\0';
}
printf("%s", recvline);
return n;
}
and in main is this:
int sockfd;
struct sockaddr_in servaddr;
char **pptr;
char *hname = "plankter.cz";
char *page = "http://plankter.cz/iot/list.json";
char str[50];
struct hostent *hptr;
if ((hptr = gethostbyname(hname)) == NULL) {
fprintf(stderr, " gethostbyname error for host: %s: %s",
hname, hstrerror(h_errno));
exit(1);
}
printf("hostname: %s\n", hptr->h_name);
if (hptr->h_addrtype == AF_INET
&& (pptr = hptr->h_addr_list) != NULL) {
printf("address: %s\n",
inet_ntop(hptr->h_addrtype, *pptr, str,
sizeof(str)));
} else {
fprintf(stderr, "Error call inet_ntop \n");
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(80);
inet_pton(AF_INET, str, &servaddr.sin_addr);
connect(sockfd, (SA *) & servaddr, sizeof(servaddr));
process_http(sockfd, hname, page);
close(sockfd);
In this example i download json, but when i read php or txt, i have same problem. I tried some another example codes using sockets, example with happyhttp library and all give me same result after 7 requests. I think it doesn't close connection. I need to send http request and recieve data, and i need to do it few times in minute.
Thanks for all ideas.
You provide a full URI to the GET field:
char *page = "http://plankter.cz/iot/list.json";
...
snprintf(sendline, MAXSUB,
"GET %s\r\n"
"Host: %s\r\n"
"Connection: close\n"
"\n", page, host);
You should not include protocol and host name.
Try this instead:
char *page = "/iot/list.json";

Socket programming: Getting same response when request sent using openssl library

I am sending two different https header to different address on same host. I am getting the same response from both test() and test1() functions... It seems like something can be used only once.... thanks in advance :)
#include <iostream>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define FAIL -1
using namespace std;
SSL_CTX* InitCTX(void);
void test(SSL_CTX* ctx, int server);
void test1(SSL_CTX* ctx, int server);
int OpenConnection(char *hostname, int port);
int main()
{
SSL_CTX *ctx;
char *host = "academics.vit.ac.in";
char *port = "443";
SSL_library_init();
ctx = InitCTX();
int server = OpenConnection(host, atoi(port));
test(ctx, server);
test1(ctx, server);// Both functions prints exactly same data
return 0;
}
void test(SSL_CTX* ctx, int server)
{
char buf[9999];
int bytes;
SSL *ssl;
ssl = SSL_new(ctx);
SSL_set_fd(ssl, server);
if(SSL_connect(ssl) == FAIL)
{
ERR_print_errors_fp(stderr);
}
else
{
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
char*msg = "GET /student/captcha.asp HTTP/1.1\nHost: academics.vit.ac.in\nCookie: ASPSESSIONIDCUTRADAT=OMDEAOKCPOLOKCLJMPAALAJN\n\n";
SSL_write(ssl, msg, strlen(msg));
bytes = SSL_read(ssl, buf, sizeof(buf));
buf[bytes] = 0;
printf("%s",buf);
SSL_free(ssl);
}
}
void test1(SSL_CTX* ctx, int server)
{
char buf[9999];
int bytes;
SSL *ssl;
ssl = SSL_new(ctx);
SSL_set_fd(ssl, server);
if(SSL_connect(ssl) == FAIL)
{
ERR_print_errors_fp(stderr);
}
else
{
printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
char*msg = "GET / HTTP/1.1\nHost: academics.vit.ac.in\nCookie: ASPSESSIONIDCUTRADAT=OMDEAOKCPOLOKCLJMPAALAJN\n\n";
SSL_write(ssl, msg, strlen(msg));
bytes = SSL_read(ssl, buf, sizeof(buf));
buf[bytes] = 0;
printf("%s",buf);
SSL_free(ssl);
}
}
SSL_CTX* InitCTX(void)
{
const SSL_METHOD *method;
SSL_CTX *ctx;
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
method = SSLv3_client_method();
ctx = SSL_CTX_new(method);
if ( ctx == NULL )
{
ERR_print_errors_fp(stderr);
abort();
}
return ctx;
}
int OpenConnection(char *hostname, int port)
{
int sd;
struct hostent *host;
struct sockaddr_in addr;
if ( (host = gethostbyname(hostname)) == NULL )
{
perror(hostname);
abort();
}
sd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long*)(host->h_addr);
if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
{
close(sd);
perror(hostname);
abort();
}
return sd;
}
The response i am getting is
Connected with RC4-SHA encryption
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: image/bmp
Expires: Tue, 25 Jun 2013 08:27:30 GMT
Server: Microsoft-IIS/7.0
Content-Disposition: inline; filename=captcha.bmp
Set-Cookie: ASPSESSIONIDCUSTBBBT=BHEANFEAHBBCBIJDIBNOPDAI; secure; path=/
X-Powered-By: ASP.NET
Date: Tue, 25 Jun 2013 08:28:30 GMT
Connection: close
Connected with (NONE) encryption
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: image/bmp
Expires: Tue, 25 Jun 2013 08:27:30 GMT
Server: Microsoft-IIS/7.0
Content-Disposition: inline; filename=captcha.bmp
Set-Cookie: ASPSESSIONIDCUSTBBBT=BHEANFEAHBBCBIJDIBNOPDAI; secure; path=/
X-Powered-By: ASP.NET
Date: Tue, 25 Jun 2013 08:28:30 GMT
Connection: close

Resources