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 <sys/un.h>
11#include <sys/socket.h>
12#include <fcntl.h>
13#include <stdlib.h>
14#include <string.h>
15
16#include "../sanity.hh"
17
18#include "ssh_agent_platform.hh"
19
20using boost::shared_ptr;
21using Netxx::Stream;
22using std::min;
23using std::string;
24
25bool
26ssh_agent_platform::connect()
27{
28 const char *authsocket;
29 int sock;
30 struct sockaddr_un sunaddr;
31
32 authsocket = getenv("SSH_AUTH_SOCK");
33
34 if (!authsocket || !strlen(authsocket))
35 {
36 L(FL("ssh_agent: connect: ssh-agent socket not found"));
37 return false;
38 }
39
40 sunaddr.sun_family = AF_UNIX;
41 strncpy(sunaddr.sun_path, authsocket, sizeof(sunaddr.sun_path));
42
43 sock = socket(AF_UNIX, SOCK_STREAM, 0);
44 if (sock < 0)
45 {
46 W(F("ssh_agent: connect: could not open socket to ssh-agent"));
47 return false;
48 }
49
50 int ret = fcntl(sock, F_SETFD, FD_CLOEXEC);
51 if (ret == -1)
52 {
53 close(sock);
54 W(F("ssh_agent: connect: could not set up socket for ssh-agent"));
55 return false;
56 }
57 ret = ::connect(sock, (struct sockaddr *)&sunaddr, sizeof sunaddr);
58 if (ret < 0)
59 {
60 close(sock);
61 W(F("ssh_agent: connect: could not connect to socket for ssh-agent"));
62 return false;
63 }
64 stream = shared_ptr<Stream>(new Stream(sock));
65 return true;
66}
67
68bool
69ssh_agent_platform::disconnect()
70{
71 if (connected())
72 stream->close();
73 return true;
74}
75
76bool
77ssh_agent_platform::connected()
78{
79 return stream != NULL;
80}
81
82void
83ssh_agent_platform::write_data(string const & data)
84{
85 L(FL("ssh_agent_platform::write_data: asked to write %u bytes") % data.length());
86 stream->write(data.c_str(), data.length());
87}
88
89void
90ssh_agent_platform::read_data(u32 const len, string & out)
91{
92 int ret;
93 const u32 bufsize = 4096;
94 char read_buf[bufsize];
95 u32 get = len;
96 L(FL("ssh_agent: read_data: asked to read %u bytes") % len);
97 while (get > 0)
98 {
99 ret = stream->read(read_buf, min(get, bufsize));
100 E(ret >= 0, F("stream read failed (%i)") % ret);
101 /*
102 if (ret > 0)
103L(FL("ssh_agent: read_data: read %i bytes") % ret);
104 */
105 out.append(read_buf, ret);
106 get -= ret;
107 }
108 E(get == 0, F("%u extra bytes from ssh-agent") % -get);
109}

Archive Download this file

Branches

Tags

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