blob: 38e99e37ca0eec03dac9263c4109580239842e99 [file] [log] [blame]
Nathan Bullockbdabded2015-02-10 20:15:53 -05001// 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
17namespace buffet {
18
19XmppConnection::~XmppConnection() {
20 if (fd_ > 0) {
21 close(fd_);
22 }
23}
24
25bool 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
51bool 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 Bullockd9e0bcd2015-02-11 11:36:39 -050059 LOG(INFO) << "Read: (" << msg->size() << ")" << *msg;
Nathan Bullockbdabded2015-02-10 20:15:53 -050060 return true;
61}
62
63bool XmppConnection::Write(const std::string& msg) const {
Nathan Bullockd9e0bcd2015-02-11 11:36:39 -050064 LOG(INFO) << "Write: (" << msg.size() << ")" << msg;
Nathan Bullockbdabded2015-02-10 20:15:53 -050065 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