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

Archive Download this file

Branches

Tags

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