HttpJob.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibCore/TCPSocket.h>
  8. #include <LibHTTP/HttpJob.h>
  9. #include <LibHTTP/HttpResponse.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. namespace HTTP {
  13. void HttpJob::start()
  14. {
  15. VERIFY(!m_socket);
  16. m_socket = Core::TCPSocket::construct(this);
  17. m_socket->on_connected = [this] {
  18. dbgln_if(CHTTPJOB_DEBUG, "HttpJob: on_connected callback");
  19. on_socket_connected();
  20. };
  21. m_socket->on_error = [this] {
  22. dbgln_if(CHTTPJOB_DEBUG, "HttpJob: on_error callback");
  23. deferred_invoke([this] {
  24. did_fail(Core::NetworkJob::Error::ConnectionFailed);
  25. });
  26. };
  27. bool success = m_socket->connect(m_request.url().host(), m_request.url().port());
  28. if (!success) {
  29. deferred_invoke([this] {
  30. return did_fail(Core::NetworkJob::Error::ConnectionFailed);
  31. });
  32. }
  33. }
  34. void HttpJob::shutdown()
  35. {
  36. if (!m_socket)
  37. return;
  38. m_socket->on_ready_to_read = nullptr;
  39. m_socket->on_connected = nullptr;
  40. remove_child(*m_socket);
  41. m_socket = nullptr;
  42. }
  43. void HttpJob::register_on_ready_to_read(Function<void()> callback)
  44. {
  45. m_socket->on_ready_to_read = move(callback);
  46. }
  47. void HttpJob::register_on_ready_to_write(Function<void()> callback)
  48. {
  49. // There is no need to wait, the connection is already established
  50. callback();
  51. }
  52. bool HttpJob::can_read_line() const
  53. {
  54. return m_socket->can_read_line();
  55. }
  56. String HttpJob::read_line(size_t size)
  57. {
  58. return m_socket->read_line(size);
  59. }
  60. ByteBuffer HttpJob::receive(size_t size)
  61. {
  62. return m_socket->receive(size);
  63. }
  64. bool HttpJob::can_read() const
  65. {
  66. return m_socket->can_read();
  67. }
  68. bool HttpJob::eof() const
  69. {
  70. return m_socket->eof();
  71. }
  72. bool HttpJob::write(ReadonlyBytes bytes)
  73. {
  74. return m_socket->write(bytes);
  75. }
  76. }