Nathan Bullock | bdabded | 2015-02-10 20:15:53 -0500 | [diff] [blame] | 1 | // Copyright 2015 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "buffet/xmpp/xmpp_connection.h" |
| 6 | |
| 7 | #include <arpa/inet.h> |
| 8 | #include <netdb.h> |
| 9 | #include <netinet/in.h> |
| 10 | #include <unistd.h> |
| 11 | |
| 12 | #include <string> |
| 13 | |
| 14 | #include <base/files/file_util.h> |
| 15 | #include <chromeos/syslog_logging.h> |
| 16 | |
| 17 | namespace buffet { |
| 18 | |
| 19 | XmppConnection::~XmppConnection() { |
| 20 | if (fd_ > 0) { |
| 21 | close(fd_); |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | bool XmppConnection::Initialize() { |
| 26 | LOG(INFO) << "Opening XMPP connection"; |
| 27 | |
| 28 | fd_ = socket(AF_INET, SOCK_STREAM, 0); |
| 29 | |
| 30 | // TODO(nathanbullock): Use gethostbyname_r. |
| 31 | struct hostent* server = gethostbyname("talk.google.com"); |
| 32 | if (server == NULL) { |
| 33 | LOG(WARNING) << "Failed to find host talk.google.com"; |
| 34 | return false; |
| 35 | } |
| 36 | |
| 37 | sockaddr_in serv_addr; |
| 38 | memset(&serv_addr, 0, sizeof(serv_addr)); |
| 39 | serv_addr.sin_family = AF_INET; |
| 40 | bcopy(server->h_addr, &(serv_addr.sin_addr), server->h_length); |
| 41 | serv_addr.sin_port = htons(5222); |
| 42 | |
| 43 | if (connect(fd_, (struct sockaddr*)&serv_addr, sizeof(sockaddr)) < 0) { |
| 44 | LOG(WARNING) << "Failed to connect to talk.google.com:5222"; |
| 45 | return false; |
| 46 | } |
| 47 | |
| 48 | return true; |
| 49 | } |
| 50 | |
| 51 | bool XmppConnection::Read(std::string* msg) const { |
| 52 | char buffer[4096]; // This should be large enough for our purposes. |
| 53 | ssize_t bytes = HANDLE_EINTR(read(fd_, buffer, sizeof(buffer))); |
| 54 | if (bytes < 0) { |
| 55 | LOG(WARNING) << "Failure reading"; |
| 56 | return false; |
| 57 | } |
| 58 | *msg = std::string{buffer, static_cast<size_t>(bytes)}; |
Nathan Bullock | d9e0bcd | 2015-02-11 11:36:39 -0500 | [diff] [blame] | 59 | LOG(INFO) << "Read: (" << msg->size() << ")" << *msg; |
Nathan Bullock | bdabded | 2015-02-10 20:15:53 -0500 | [diff] [blame] | 60 | return true; |
| 61 | } |
| 62 | |
| 63 | bool XmppConnection::Write(const std::string& msg) const { |
Nathan Bullock | d9e0bcd | 2015-02-11 11:36:39 -0500 | [diff] [blame] | 64 | LOG(INFO) << "Write: (" << msg.size() << ")" << msg; |
Nathan Bullock | bdabded | 2015-02-10 20:15:53 -0500 | [diff] [blame] | 65 | if (!base::WriteFileDescriptor(fd_, msg.c_str(), msg.size())) { |
| 66 | LOG(WARNING) << "Failure writing"; |
| 67 | return false; |
| 68 | } |
| 69 | return true; |
| 70 | } |
| 71 | |
| 72 | } // namespace buffet |