HttpJob.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. bool success = m_socket->connect(m_request.url().host(), m_request.url().port());
  22. if (!success) {
  23. deferred_invoke([this](auto&) {
  24. return did_fail(Core::NetworkJob::Error::ConnectionFailed);
  25. });
  26. }
  27. }
  28. void HttpJob::shutdown()
  29. {
  30. if (!m_socket)
  31. return;
  32. m_socket->on_ready_to_read = nullptr;
  33. m_socket->on_connected = nullptr;
  34. remove_child(*m_socket);
  35. m_socket = nullptr;
  36. }
  37. void HttpJob::register_on_ready_to_read(Function<void()> callback)
  38. {
  39. m_socket->on_ready_to_read = move(callback);
  40. }
  41. void HttpJob::register_on_ready_to_write(Function<void()> callback)
  42. {
  43. // There is no need to wait, the connection is already established
  44. callback();
  45. }
  46. bool HttpJob::can_read_line() const
  47. {
  48. return m_socket->can_read_line();
  49. }
  50. String HttpJob::read_line(size_t size)
  51. {
  52. return m_socket->read_line(size);
  53. }
  54. ByteBuffer HttpJob::receive(size_t size)
  55. {
  56. return m_socket->receive(size);
  57. }
  58. bool HttpJob::can_read() const
  59. {
  60. return m_socket->can_read();
  61. }
  62. bool HttpJob::eof() const
  63. {
  64. return m_socket->eof();
  65. }
  66. bool HttpJob::write(ReadonlyBytes bytes)
  67. {
  68. return m_socket->write(bytes);
  69. }
  70. }