Socket.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <Kernel/Socket.h>
  2. #include <Kernel/LocalSocket.h>
  3. #include <Kernel/IPv4Socket.h>
  4. #include <Kernel/UnixTypes.h>
  5. #include <Kernel/Process.h>
  6. #include <LibC/errno_numbers.h>
  7. KResultOr<Retained<Socket>> Socket::create(int domain, int type, int protocol)
  8. {
  9. (void)protocol;
  10. switch (domain) {
  11. case AF_LOCAL:
  12. return LocalSocket::create(type & SOCK_TYPE_MASK);
  13. case AF_INET:
  14. return IPv4Socket::create(type & SOCK_TYPE_MASK, protocol);
  15. default:
  16. return KResult(-EAFNOSUPPORT);
  17. }
  18. }
  19. Socket::Socket(int domain, int type, int protocol)
  20. : m_domain(domain)
  21. , m_type(type)
  22. , m_protocol(protocol)
  23. {
  24. m_origin_pid = current->pid();
  25. }
  26. Socket::~Socket()
  27. {
  28. }
  29. KResult Socket::listen(int backlog)
  30. {
  31. LOCKER(m_lock);
  32. if (m_type != SOCK_STREAM)
  33. return KResult(-EOPNOTSUPP);
  34. m_backlog = backlog;
  35. kprintf("Socket{%p} listening with backlog=%d\n", this, m_backlog);
  36. return KSuccess;
  37. }
  38. RetainPtr<Socket> Socket::accept()
  39. {
  40. LOCKER(m_lock);
  41. if (m_pending.is_empty())
  42. return nullptr;
  43. auto client = m_pending.take_first();
  44. ASSERT(!client->is_connected());
  45. client->m_connected = true;
  46. m_clients.append(client.copy_ref());
  47. return client;
  48. }
  49. KResult Socket::queue_connection_from(Socket& peer)
  50. {
  51. LOCKER(m_lock);
  52. if (m_pending.size() >= m_backlog)
  53. return KResult(-ECONNREFUSED);
  54. m_pending.append(peer);
  55. return KSuccess;
  56. }