2
0

scgi_oop.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. #include <scgi.h>
  2. #include <scgi_oop.h>
  3. #define connection_construct_common() memset(&handle, 0, sizeof(handle))
  4. SCGIhandle::SCGIhandle(void)
  5. {
  6. connection_construct_common();
  7. }
  8. SCGIhandle::~SCGIhandle()
  9. {
  10. scgi_disconnect(&handle);
  11. scgi_safe_free(data_buf);
  12. buflen = 0;
  13. bufsize = 0;
  14. }
  15. int SCGIhandle::socketDescriptor()
  16. {
  17. if (handle.connected) {
  18. return (int) handle.sock;
  19. }
  20. return -1;
  21. }
  22. int SCGIhandle::disconnect()
  23. {
  24. return scgi_disconnect(&handle);
  25. }
  26. int SCGIhandle::connected()
  27. {
  28. return handle.connected;
  29. }
  30. int SCGIhandle::addParam(const char *name, const char *value)
  31. {
  32. return (int) scgi_add_param(&handle, name, value);
  33. }
  34. int SCGIhandle::addBody(const char *value)
  35. {
  36. return (int) scgi_add_body(&handle, value);
  37. }
  38. char *SCGIhandle::getBody()
  39. {
  40. return handle.body;
  41. }
  42. char *SCGIhandle::getParam(const char *name)
  43. {
  44. return (char *) scgi_get_param(&handle, name);
  45. }
  46. char *SCGIhandle::sendRequest(const char *host, int port, int timeout)
  47. {
  48. ssize_t len;
  49. if (!host) {
  50. return 0;
  51. }
  52. if (timeout < 1000) {
  53. timeout = 1000;
  54. }
  55. if (scgi_connect(&handle, host, port, timeout) == SCGI_SUCCESS) {
  56. if (scgi_send_request(&handle) == SCGI_SUCCESS) {
  57. while((len = scgi_recv(&handle, buf, sizeof(buf))) > 0) {
  58. if (buflen + len > bufsize) {
  59. bufsize = buflen + len + 1024;
  60. void *tmp = realloc(data_buf, bufsize);
  61. assert(tmp);
  62. data_buf = (char *)tmp;
  63. *(data_buf+buflen) = '\0';
  64. }
  65. snprintf(data_buf+buflen, bufsize-buflen, "%s", buf);
  66. buflen += len;
  67. }
  68. return data_buf;
  69. }
  70. }
  71. return (char *) "";
  72. }
  73. int SCGIhandle::bind(const char *host, int port)
  74. {
  75. return (scgi_bind(host, port, &server_sock) == SCGI_SUCCESS) ? 1 : 0;
  76. }
  77. int SCGIhandle::accept(void)
  78. {
  79. scgi_socket_t client_sock;
  80. if (scgi_accept(server_sock, &client_sock, NULL) == SCGI_SUCCESS) {
  81. if (scgi_parse(client_sock, &handle) == SCGI_SUCCESS) {
  82. return 1;
  83. }
  84. closesocket(client_sock);
  85. }
  86. return 0;
  87. }
  88. int SCGIhandle::respond(char *msg)
  89. {
  90. int b = write(handle.sock, msg, strlen(msg));
  91. scgi_disconnect(&handle);
  92. scgi_safe_free(data_buf);
  93. buflen = 0;
  94. bufsize = 0;
  95. return b;
  96. }