当前位置: 首页 > 工具软件 > Nghttp2 > 使用案例 >

使用nghttp2实现IOS 的 APNS的推送测试例子

子车芷阳
2023-12-01

能用代码就不废话

调用例子和代码

//调用示例:
int main(int argc , char**argv)
{
     testapns( "/path/to/your/ca",
              "/path/yourkey_cert.pem",
            "/path/yourkey_cert.pem",
              "api.push.apple.com",
              "/3/device/DB10092BAF5385B9AD58AB696DC7E8ECC6061F04AFD79E1387EB38D0E3712DCB",
              "alert",
             "com.company.game",
            "10",
            "0",
           "{ \"aps\" : { \"alert\" : \"Hello\" } }"
                                     
             );

      return 0;
}

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif /* HAVE_CONFIG_H */

#include <inttypes.h>
#include <stdlib.h>

# include <fcntl.h>

#include <sys/types.h>
#  include <sys/socket.h>
#  include <netdb.h>
#  include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>

#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>

#include <nghttp2/nghttp2.h>

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
  #include <unistd.h>

#include <string>

#include <iostream>


struct Connection {
  SSL *ssl;
  nghttp2_session *session;
  /* WANT_READ if SSL/TLS connection needs more input; or WANT_WRITE
     if it needs more output; or IO_NONE. This is necessary because
     SSL/TLS re-negotiation is possible at any time. nghttp2 API
     offers similar functions like nghttp2_session_want_read() and
     nghttp2_session_want_write() but they do not take into account
     SSL/TSL connection. */
  int want_io;
};


struct XRequest {
    const char *host;
    /* In this program, path contains query component as well. */
    const  char *path;
    /* This is the concatenation of host and port with ":" inbetween. */
    const  char *hostport;
    /* Stream ID for this request. */
    int32_t stream_id;
    uint16_t port;
    
    const char *pdata;
    const char *topic;
    const char *pushtype;
    const char *priority;
    const char *expiration;
    size_t nleft;
    size_t nsize;
};



enum { IO_NONE, WANT_READ, WANT_WRITE };



int get_cert_password_cb2(char *buf,int size, int rwflag, void *userdata)
{

    std::string password="123456";
    //g_pConfigData->GetStr(CONF_KX_CERT_PASS, &password);
   // Capns_client::log->debug("desc=get_cert_password password=%s\n",password.c_str());

    strcpy(buf,password.c_str());

    return password.length();
}


static void die(const char *msg) {
  fprintf(stderr, "FATAL: %s\n", msg);
  exit(EXIT_FAILURE);
}

/*
 * Prints error containing the function name |func| and error code
 * |error_code| and exit.
 */
static void diec(const char *func, int error_code) {
  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
          nghttp2_strerror(error_code));
  exit(EXIT_FAILURE);
}


static void dief(const char *func, const char *msg) {
  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
  exit(EXIT_FAILURE);
}

/*
 * The implementation of nghttp2_send_callback type. Here we write
 * |data| with size |length| to the network and return the number of
 * bytes actually written. See the documentation of
 * nghttp2_send_callback for the details.
 */
static ssize_t send_callback(nghttp2_session *session, const uint8_t *data,
                             size_t length, int flags, void *user_data) {
  struct Connection *connection;
  int rv;
  (void)session;
  (void)flags;

  connection = (struct Connection *)user_data;
  //connection->want_io = IO_NONE;
  ERR_clear_error();
  rv = SSL_write(connection->ssl, data, (int)length);
  if (rv <= 0) {
    int err = SSL_get_error(connection->ssl, rv);
    if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
      connection->want_io =
          (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
      rv = NGHTTP2_ERR_WOULDBLOCK;
    } else {
      rv = NGHTTP2_ERR_CALLBACK_FAILURE;
    }
  }
  return rv;
}

/*
 * The implementation of nghttp2_recv_callback type. Here we read data
 * from the network and write them in |buf|. The capacity of |buf| is
 * |length| bytes. Returns the number of bytes stored in |buf|. See
 * the documentation of nghttp2_recv_callback for the details.
 */
static ssize_t recv_callback(nghttp2_session *session, uint8_t *buf,
                             size_t length, int flags, void *user_data) {
  struct Connection *connection;
  int rv;
  (void)session;
  (void)flags;

  connection = (struct Connection *)user_data;
  connection->want_io = IO_NONE;
  ERR_clear_error();
  rv = SSL_read(connection->ssl, buf, (int)length);
  if (rv < 0) {
    int err = SSL_get_error(connection->ssl, rv);
    if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
      connection->want_io =
          (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
      rv = NGHTTP2_ERR_WOULDBLOCK;
    } else {
      rv = NGHTTP2_ERR_CALLBACK_FAILURE;
    }
  } else if (rv == 0) {
    rv = NGHTTP2_ERR_EOF;
  }
  return rv;
}

static int on_frame_send_callback(nghttp2_session *session,
                                  const nghttp2_frame *frame, void *user_data) {
  size_t i;
  (void)user_data;

  switch (frame->hd.type) {
  case NGHTTP2_HEADERS:
    if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
      const nghttp2_nv *nva = frame->headers.nva;
      printf("[INFO] C ----------------------------> S (HEADERS)\n");
      for (i = 0; i < frame->headers.nvlen; ++i) {
        fwrite(nva[i].name, 1, nva[i].namelen, stdout);
        printf(": ");
        fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
        printf("\n");
      }
    }
    break;
  case NGHTTP2_RST_STREAM:
    printf("[INFO] C ----------------------------> S (RST_STREAM)\n");
    break;
  case NGHTTP2_GOAWAY:
    printf("[INFO] C ----------------------------> S (GOAWAY)\n");
    break;
  }
  return 0;
}

static int on_frame_recv_callback(nghttp2_session *session,
                                  const nghttp2_frame *frame, void *user_data) {
  size_t i;
  (void)user_data;

  switch (frame->hd.type) {
  case NGHTTP2_HEADERS:
    if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE) {
      const nghttp2_nv *nva = frame->headers.nva;
      struct XRequest *req;
      req = (struct XRequest *)nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
      if (req) {
        printf("[INFO] C <---------------------------- S (HEADERS)\n");
        for (i = 0; i < frame->headers.nvlen; ++i) {
          fwrite(nva[i].name, 1, nva[i].namelen, stdout);
          printf(": ");
          fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
          printf("\n");
        }
      }
    }
    break;
  case NGHTTP2_RST_STREAM:
    printf("[INFO] C <---------------------------- S (RST_STREAM)\n");
    break;
  case NGHTTP2_GOAWAY:
    printf("[INFO] C <---------------------------- S (GOAWAY)\n");
    break;
  }
  return 0;
}

/*
 * The implementation of nghttp2_on_stream_close_callback type. We use
 * this function to know the response is fully received. Since we just
 * fetch 1 resource in this program, after reception of the response,
 * we submit GOAWAY and close the session.
 */
static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
                                    uint32_t error_code, void *user_data) {
  struct XRequest *req;
  (void)error_code;
  (void)user_data;

  req =  (struct XRequest *)nghttp2_session_get_stream_user_data(session, stream_id);
  if (req) {
    int rv;
    rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);

    if (rv != 0) {
      diec("nghttp2_session_terminate_session", rv);
    }
  }
  return 0;
}

/*
 * The implementation of nghttp2_on_data_chunk_recv_callback type. We
 * use this function to print the received response body.
 */
static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
                                       int32_t stream_id, const uint8_t *data,
                                       size_t len, void *user_data) {
  struct XRequest *req;
  (void)flags;
  (void)user_data;

  req =  (struct XRequest *)nghttp2_session_get_stream_user_data(session, stream_id);
  if (req) {
    printf("[INFO] C <---------------------------- S (DATA chunk)\n"
           "%lu bytes\n",
           (unsigned long int)len);
    fwrite(data, 1, len, stdout);
    printf("\n");
  }
  return 0;
}

#define MAKE_NV(NAME, VALUE)                                                   \
  {                                                                            \
    (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, sizeof(VALUE) - 1,    \
        NGHTTP2_NV_FLAG_NONE                                                   \
  }

#define MAKE_NV_CS(NAME, VALUE)                                                \
  {                                                                            \
    (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, strlen(VALUE),        \
        NGHTTP2_NV_FLAG_NONE                                                   \
  }


ssize_t nghttp2_prd_callback(
nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length,
uint32_t *data_flags, nghttp2_data_source *source, void *user_data)
{
    struct XRequest *req = (struct XRequest *)source->ptr;
    
      size_t n = std::min(req->nleft, length);
      memcpy(buf,req->pdata+ req->nsize - req->nleft, n);
      req->nleft -= n;
      if (req->nleft == 0) {
        *data_flags |= NGHTTP2_DATA_FLAG_EOF;
      }
      return n;
}


/*
 * Update |pollfd| based on the state of |connection|.
 */
static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
  pollfd->events = 0;
  if (nghttp2_session_want_read(connection->session) ||
      connection->want_io == WANT_READ) {
    pollfd->events |= POLLIN;
  }
  if (nghttp2_session_want_write(connection->session) ||
      connection->want_io == WANT_WRITE) {
    pollfd->events |= POLLOUT;
  }
}



/*
 * Submits the request |req| to the connection |connection|.  This
 * function does not send packets; just append the request to the
 * internal queue in |connection->session|.
 */
static void submit_request(struct Connection *connection, struct XRequest *req) {
  int32_t stream_id;
  /* Make sure that the last item is NULL */
  const nghttp2_nv nva[] = {MAKE_NV(":method", "POST"),
                            MAKE_NV_CS(":path", req->path),
                            MAKE_NV(":scheme", "https"),
                            MAKE_NV_CS(":authority", req->hostport),
                            MAKE_NV("accept", "*/*"),
                            MAKE_NV("user-agent", "nghttp2/" NGHTTP2_VERSION),
              MAKE_NV_CS("apns-topic",req->topic),
              MAKE_NV_CS("apns-priority",req->priority),
              MAKE_NV_CS("apns-expiration",req->expiration),
              MAKE_NV_CS("apns-push-type",req->pushtype),
              MAKE_NV_CS("host",req->host)
      
  };
    
    nghttp2_data_provider *prd = new nghttp2_data_provider();
    prd->source.ptr = req;
    
    prd->read_callback =nghttp2_prd_callback;
    stream_id = nghttp2_submit_request(connection->session, NULL, nva,
                                     sizeof(nva) / sizeof(nva[0]), prd, req);

  if (stream_id < 0) {
    diec("nghttp2_submit_request", stream_id);
  }

  req->stream_id = stream_id;
  printf("[INFO] Stream ID = %d\n", stream_id);
}


static void make_non_block(int fd) {
  int flags, rv;
  while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
    ;
  if (flags == -1) {
    dief("fcntl", strerror(errno));
  }
  while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
    ;
  if (rv == -1) {
    dief("fcntl", strerror(errno));
  }
}

static void set_tcp_nodelay(int fd) {
  int val = 1;
  int rv;
  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
  if (rv == -1) {
    dief("setsockopt", strerror(errno));
  }
}



/*
 * Performs the network I/O.
 */
static void exec_io(struct Connection *connection) {
  int rv;
  rv = nghttp2_session_recv(connection->session);
  if (rv != 0) {
    diec("nghttp2_session_recv", rv);
  }
  rv = nghttp2_session_send(connection->session);
  if (rv != 0) {
    diec("nghttp2_session_send", rv);
  }
}


int testapns( const std::string &m_capath,
              const std::string &m_cerfile,
              const std::string &m_keyfile,
              const std::string &m_host,
              const std::string &urlpath,
              const std::string &pushtype,
             const std::string &topic,
             const std::string &priority,
             const std::string &expiration,
            const std::string &data
                                     
             )
{
    nfds_t npollfds = 1;
    struct pollfd pollfds[1];

    struct sockaddr_in   m_server_addr;
    struct hostent       m_host_info;

    int m_port;

    int err;
    int ret=0;
    struct timeval tv;
    time_t now=time(NULL);
    #define ERR_STRING_LEN  256
    char errString[ERR_STRING_LEN]={0};
    #define GET_SSL_ERR_STRING  \
    ERR_error_string_n(ERR_get_error(),errString,ERR_STRING_LEN-1)

    int hostbuf_len=1024;
    char *hostbuf=NULL;
    bool retry=false;

    /* Create an SSL_METHOD structure (choose an SSL/TLS protocol version) */
    const SSL_METHOD * m_method = SSLv23_method();
    if(!m_method)
    {
        return -1;
    }


    /* Create an SSL_CTX structure */
    SSL_CTX *  m_ctx = SSL_CTX_new(m_method);
    if(!m_ctx)
    {
        return -1;
    }

    SSL_CTX_set_default_passwd_cb(m_ctx,get_cert_password_cb2);


    /* Load the CA from the Path */
    if(SSL_CTX_load_verify_locations(m_ctx, NULL, m_capath.c_str()) <= 0)
    {
     GET_SSL_ERR_STRING  ;
     std::cout << "err=failed_to_set_ca ssl_err= " << errString << "\n";
     return -1;
    }

    /* Load the client certificate into the SSL_CTX structure */
    if (SSL_CTX_use_certificate_file(m_ctx, m_cerfile.c_str(), SSL_FILETYPE_PEM) <= 0) {
        GET_SSL_ERR_STRING  ;
        std::cout << "SSL_CTX_use_certificate_filessl_err= " << errString << "\n";
        return -1;
    }

    /* Load the private-key corresponding to the client certificate */
    if (SSL_CTX_use_PrivateKey_file(m_ctx, m_keyfile.c_str(), SSL_FILETYPE_PEM) <= 0) {
     GET_SSL_ERR_STRING  ;
     std::cout << "SSL_CTX_use_PrivateKey_file = " << errString << "\n";
     return -1;
    }

    /* Check if the client certificate and private-key matches */
    if (!SSL_CTX_check_private_key(m_ctx)) {
      GET_SSL_ERR_STRING  ;
       std::cout << "SSL_CTX_check_private_key = " << errString << "\n";
       return -1;
    }

    /* Set up a TCP socket */
    int m_sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(m_sock == -1)
    {
        err=-1;
        return -1;
    }

    memset (&m_server_addr, '\0', sizeof(m_server_addr));
    m_server_addr.sin_family      = AF_INET;
    m_server_addr.sin_port        = htons(m_port);       /* Server Port number */

    if((hostbuf=(char *)malloc(hostbuf_len))==NULL)
    {
        return -1;
    }

    struct hostent  *phost=NULL;
    int ret1=0;
    phost = gethostbyname(m_host.c_str());

    m_server_addr.sin_addr = *(struct in_addr*)phost->h_addr_list[0];
    char m_connect_ip[30];
     inet_ntop(AF_INET, &m_server_addr.sin_addr, m_connect_ip,sizeof(m_connect_ip));
           m_connect_ip[15]='\0';
    m_server_addr.sin_port = htons(443);
    printf("host ip %s \n", m_connect_ip);


    /* Establish a TCP/IP connection to the SSL client */
    err = ::connect(m_sock, (struct sockaddr*) &m_server_addr, sizeof(m_server_addr));
    if(err == -1)
    {
        return -1;
    }


    /* An SSL structure is created */
    SSL *m_ssl = SSL_new(m_ctx);
    if(!m_ssl)
    {
        err=-1;
        return -1;
    }

    /* Assign the socket into the SSL structure (SSL and socket without BIO) */
    SSL_set_fd(m_ssl, m_sock);

    /* Perform SSL Handshake on the SSL client */
    err = SSL_connect(m_ssl);
    if(err <= 0)
    {
        GET_SSL_ERR_STRING  ;
        err=-1;
        return -1;
    }

    struct Connection connection;
    connection.ssl = m_ssl;
    nghttp2_session_callbacks *callbacks;
    int rv = nghttp2_session_callbacks_new(&callbacks);

    nghttp2_session_callbacks_set_send_callback(callbacks, send_callback);

     nghttp2_session_callbacks_set_recv_callback(callbacks, recv_callback);

     nghttp2_session_callbacks_set_on_frame_send_callback(callbacks,
                                                          on_frame_send_callback);

     nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
                                                          on_frame_recv_callback);

     nghttp2_session_callbacks_set_on_stream_close_callback(
         callbacks, on_stream_close_callback);

     nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
         callbacks, on_data_chunk_recv_callback);



    rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);

    nghttp2_session_callbacks_del(callbacks);

    if (rv != 0) {
      diec("nghttp2_session_client_new", rv);
    }

    rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);


    connection.want_io = IO_NONE;

     /* Here make file descriptor non-block */
    make_non_block(m_sock);
    set_tcp_nodelay(m_sock);

    if (rv != 0) {
      diec("nghttp2_submit_settings", rv);
    }
    struct XRequest req;
    req.host = m_host.c_str();
    req.path = urlpath.c_str();
    req.hostport = m_host.c_str();
    req.pdata = data.c_str();
    req.nsize = req.nleft = strlen(req.pdata);
    req.expiration = expiration.c_str();
    req.priority = priority.c_str();
    req.pushtype = pushtype.c_str();
    req.topic = topic.c_str();
    /* Submit the HTTP request to the outbound queue. */
    submit_request(&connection, &req);


    pollfds[0].fd = m_sock;
    ctl_poll(pollfds, &connection);

    /* Event loop */
    while (nghttp2_session_want_read(connection.session) ||
         nghttp2_session_want_write(connection.session)) {
    int nfds = poll(pollfds, npollfds, -1);
    if (nfds == -1) {
      dief("poll", strerror(errno));
    }
    if (pollfds[0].revents & (POLLIN | POLLOUT)) {
      exec_io(&connection);
    }
    if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
      die("Connection error");
    }
    ctl_poll(pollfds, &connection);
    }

    nghttp2_session_del(connection.session);
    SSL_shutdown(m_ssl);
    SSL_free(m_ssl);
    SSL_CTX_free(m_ctx);
    shutdown(m_sock, SHUT_WR);
    close(m_sock);
    
    return 0;

}

 

 类似资料: