monotone

monotone Mtn Source Tree

Root/unix/ssh_agent_platform.cc

1// Copyright (C) 2007 Justin Patrin <papercrane@reversefold.com>
2//
3// This program is made available under the GNU GPL version 2.0 or
4// greater. See the accompanying file COPYING for details.
5//
6// This program is distributed WITHOUT ANY WARRANTY; without even the
7// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
8// PURPOSE.
9
10#include "base.hh"
11#include <sys/types.h>
12#include <sys/un.h>
13#include <sys/socket.h>
14#include <fcntl.h>
15#include <stdlib.h>
16#include <string.h>
17#include <unistd.h>
18
19#include "../sanity.hh"
20
21#include "ssh_agent_platform.hh"
22
23using boost::shared_ptr;
24using Netxx::Stream;
25using std::min;
26using std::string;
27
28bool
29ssh_agent_platform::connect()
30{
31 const char *authsocket;
32 int sock;
33 struct sockaddr_un sunaddr;
34
35 authsocket = getenv("SSH_AUTH_SOCK");
36
37 if (!authsocket || !strlen(authsocket))
38 {
39 L(FL("ssh_agent: connect: ssh-agent socket not found"));
40 return false;
41 }
42
43 sunaddr.sun_family = AF_UNIX;
44 strncpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
45
46 sock = socket(AF_UNIX, SOCK_STREAM, 0);
47 if (sock < 0)
48 {
49 W(F("ssh_agent: connect: could not open socket to ssh-agent"));
50 return false;
51 }
52
53 int ret = fcntl(sock, F_SETFD, FD_CLOEXEC);
54 if (ret == -1)
55 {
56 close(sock);
57 W(F("ssh_agent: connect: could not set up socket for ssh-agent"));
58 return false;
59 }
60 ret = ::connect(sock, (struct sockaddr *)&sunaddr, sizeof sunaddr);
61 if (ret < 0)
62 {
63 close(sock);
64 W(F("ssh_agent: connect: could not connect to socket for ssh-agent"));
65 return false;
66 }
67 stream = shared_ptr<Stream>(new Stream(sock));
68 return true;
69}
70
71bool
72ssh_agent_platform::disconnect()
73{
74 if (connected())
75 stream->close();
76 return true;
77}
78
79bool
80ssh_agent_platform::connected()
81{
82 return stream != NULL;
83}
84
85void
86ssh_agent_platform::write_data(string const & data)
87{
88 L(FL("ssh_agent_platform::write_data: asked to write %u bytes") % data.length());
89 stream->write(data.c_str(), data.length());
90}
91
92void
93ssh_agent_platform::read_data(u32 const len, string & out)
94{
95 int ret;
96 const u32 bufsize = 4096;
97 char read_buf[bufsize];
98 u32 get = len;
99 L(FL("ssh_agent: read_data: asked to read %u bytes") % len);
100 while (get > 0)
101 {
102 ret = stream->read(read_buf, min(get, bufsize));
103 E(ret >= 0, F("stream read failed (%i)") % ret);
104 /*
105 if (ret > 0)
106L(FL("ssh_agent: read_data: read %i bytes") % ret);
107 */
108 out.append(read_buf, ret);
109 get -= ret;
110 }
111 E(get == 0, F("%u extra bytes from ssh-agent") % -get);
112}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status