summaryrefslogtreecommitdiff
path: root/boost/process/detail/windows/async_pipe.hpp
blob: 1bc2c8fec5e31d32742ae7f3222e48056ac59124 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PROCESS_DETAIL_WINDOWS_ASYNC_PIPE_HPP_
#define BOOST_PROCESS_DETAIL_WINDOWS_ASYNC_PIPE_HPP_

#include <boost/winapi/basic_types.hpp>
#include <boost/winapi/pipes.hpp>
#include <boost/winapi/handles.hpp>
#include <boost/winapi/file_management.hpp>
#include <boost/winapi/get_last_error.hpp>
#include <boost/winapi/access_rights.hpp>
#include <boost/winapi/process.hpp>
#include <boost/process/detail/windows/basic_pipe.hpp>
#include <boost/asio/windows/stream_handle.hpp>
#include <atomic>
#include <system_error>
#include <string>

namespace boost { namespace process { namespace detail { namespace windows {

inline std::string make_pipe_name()
{
    std::string name = "\\\\.\\pipe\\boost_process_auto_pipe_";

    auto pid = ::boost::winapi::GetCurrentProcessId();

    static std::atomic_size_t cnt{0};
    name += std::to_string(pid);
    name += "_";
    name += std::to_string(cnt++);

    return name;
}

class async_pipe
{
    ::boost::asio::windows::stream_handle _source;
    ::boost::asio::windows::stream_handle _sink  ;
public:
    typedef ::boost::winapi::HANDLE_ native_handle_type;
    typedef ::boost::asio::windows::stream_handle   handle_type;

    inline async_pipe(boost::asio::io_context & ios,
                      const std::string & name = make_pipe_name())
                    : async_pipe(ios, ios, name) {}

    inline async_pipe(boost::asio::io_context & ios_source,
                      boost::asio::io_context & ios_sink,
                      const std::string & name = make_pipe_name());

    inline async_pipe(const async_pipe& rhs);
    async_pipe(async_pipe&& rhs)  : _source(std::move(rhs._source)), _sink(std::move(rhs._sink))
    {
        rhs._source.assign (::boost::winapi::INVALID_HANDLE_VALUE_);
        rhs._sink  .assign (::boost::winapi::INVALID_HANDLE_VALUE_);
    }
    template<class CharT, class Traits = std::char_traits<CharT>>
    explicit async_pipe(::boost::asio::io_context & ios_source,
                        ::boost::asio::io_context & ios_sink,
                         const basic_pipe<CharT, Traits> & p)
            : _source(ios_source, p.native_source()), _sink(ios_sink, p.native_sink())
    {
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    explicit async_pipe(boost::asio::io_context & ios, const basic_pipe<CharT, Traits> & p)
            : async_pipe(ios, ios, p)
    {
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    inline async_pipe& operator=(const basic_pipe<CharT, Traits>& p);
    inline async_pipe& operator=(const async_pipe& rhs);

    inline async_pipe& operator=(async_pipe&& rhs);

    ~async_pipe()
    {
        boost::system::error_code ec;
        close(ec);
    }

    template<class CharT, class Traits = std::char_traits<CharT>>
    inline explicit operator basic_pipe<CharT, Traits>() const;

    void cancel()
    {
        if (_sink.is_open())
            _sink.cancel();
        if (_source.is_open())
            _source.cancel();
    }

    void close()
    {
        if (_sink.is_open())
        {
            _sink.close();
            _sink = handle_type(_sink.get_io_context());
        }
        if (_source.is_open())
        {
            _source.close();
            _source = handle_type(_source.get_io_context());
        }
    }
    void close(boost::system::error_code & ec)
    {
        if (_sink.is_open())
        {
            _sink.close(ec);
            _sink = handle_type(_sink.get_io_context());
        }
        if (_source.is_open())
        {
            _source.close(ec);
            _source = handle_type(_source.get_io_context());
        }
    }

    bool is_open() const
    {
        return  _sink.is_open() || _source.is_open();
    }
    void async_close()
    {
        if (_sink.is_open())
            _sink.get_io_context().  post([this]{_sink.close();});
        if (_source.is_open())
            _source.get_io_context().post([this]{_source.close();});
    }

    template<typename MutableBufferSequence>
    std::size_t read_some(const MutableBufferSequence & buffers)
    {
        return _source.read_some(buffers);
    }
    template<typename MutableBufferSequence>
    std::size_t write_some(const MutableBufferSequence & buffers)
    {
        return _sink.write_some(buffers);
    }


    template<typename MutableBufferSequence>
    std::size_t read_some(const MutableBufferSequence & buffers, boost::system::error_code & ec) noexcept
    {
        return _source.read_some(buffers, ec);
    }
    template<typename MutableBufferSequence>
    std::size_t write_some(const MutableBufferSequence & buffers, boost::system::error_code & ec) noexcept
    {
        return _sink.write_some(buffers, ec);
    }

    native_handle_type native_source() const {return const_cast<boost::asio::windows::stream_handle&>(_source).native_handle();}
    native_handle_type native_sink  () const {return const_cast<boost::asio::windows::stream_handle&>(_sink  ).native_handle();}

    template<typename MutableBufferSequence,
             typename ReadHandler>
    BOOST_ASIO_INITFN_RESULT_TYPE(
          ReadHandler, void(boost::system::error_code, std::size_t))
      async_read_some(
        const MutableBufferSequence & buffers,
              ReadHandler &&handler)
    {
        _source.async_read_some(buffers, std::forward<ReadHandler>(handler));
    }

    template<typename ConstBufferSequence,
             typename WriteHandler>
    BOOST_ASIO_INITFN_RESULT_TYPE(
              WriteHandler, void(boost::system::error_code, std::size_t))
      async_write_some(
        const ConstBufferSequence & buffers,
        WriteHandler && handler)
    {
        _sink.async_write_some(buffers,  std::forward<WriteHandler>(handler));
    }

    const handle_type & sink  () const & {return _sink;}
    const handle_type & source() const & {return _source;}

    handle_type && source() && { return std::move(_source); }
    handle_type && sink()   && { return std::move(_sink); }

    handle_type source(::boost::asio::io_context& ios) &&
    {
        ::boost::asio::windows::stream_handle stolen(ios, _source.native_handle());
        _source.assign(::boost::winapi::INVALID_HANDLE_VALUE_);
        return stolen;
    }
    handle_type sink  (::boost::asio::io_context& ios) &&
    {
        ::boost::asio::windows::stream_handle stolen(ios, _sink.native_handle());
        _sink.assign(::boost::winapi::INVALID_HANDLE_VALUE_);
        return stolen;
    }

    handle_type source(::boost::asio::io_context& ios) const &
    {
        auto proc = ::boost::winapi::GetCurrentProcess();

        ::boost::winapi::HANDLE_ source;
        auto source_in = const_cast<handle_type&>(_source).native_handle();
        if (source_in == ::boost::winapi::INVALID_HANDLE_VALUE_)
            source = ::boost::winapi::INVALID_HANDLE_VALUE_;
        else if (!::boost::winapi::DuplicateHandle(
                proc, source_in, proc, &source, 0,
                static_cast<::boost::winapi::BOOL_>(true),
                 ::boost::winapi::DUPLICATE_SAME_ACCESS_))
            throw_last_error("Duplicate Pipe Failed");

        return ::boost::asio::windows::stream_handle(ios, source);
    }
    handle_type sink  (::boost::asio::io_context& ios) const &
    {
        auto proc = ::boost::winapi::GetCurrentProcess();

        ::boost::winapi::HANDLE_ sink;
        auto sink_in = const_cast<handle_type&>(_sink).native_handle();
        if (sink_in == ::boost::winapi::INVALID_HANDLE_VALUE_)
            sink = ::boost::winapi::INVALID_HANDLE_VALUE_;
        else if (!::boost::winapi::DuplicateHandle(
                proc, sink_in, proc, &sink, 0,
                static_cast<::boost::winapi::BOOL_>(true),
                 ::boost::winapi::DUPLICATE_SAME_ACCESS_))
            throw_last_error("Duplicate Pipe Failed");

        return ::boost::asio::windows::stream_handle(ios, sink);
    }
};



async_pipe::async_pipe(const async_pipe& p)  :
    _source(const_cast<handle_type&>(p._source).get_io_context()),
    _sink  (const_cast<handle_type&>(p._sink).get_io_context())
{
    auto proc = ::boost::winapi::GetCurrentProcess();

    ::boost::winapi::HANDLE_ source;
    ::boost::winapi::HANDLE_ sink;

    //cannot get the handle from a const object.
    auto source_in = const_cast<handle_type&>(p._source).native_handle();
    auto sink_in   = const_cast<handle_type&>(p._sink).native_handle();

    if (source_in == ::boost::winapi::INVALID_HANDLE_VALUE_)
        source = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, source_in, proc, &source, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    if (sink_in   == ::boost::winapi::INVALID_HANDLE_VALUE_)
        sink = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, sink_in, proc, &sink, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    _source.assign(source);
    _sink.  assign(sink);
}


async_pipe::async_pipe(boost::asio::io_context & ios_source,
                       boost::asio::io_context & ios_sink,
                       const std::string & name) : _source(ios_source), _sink(ios_sink)
{
    static constexpr int FILE_FLAG_OVERLAPPED_  = 0x40000000; //temporary

    ::boost::winapi::HANDLE_ source = ::boost::winapi::create_named_pipe(
#if defined(BOOST_NO_ANSI_APIS)
            ::boost::process::detail::convert(name).c_str(),
#else
            name.c_str(),
#endif
            ::boost::winapi::PIPE_ACCESS_INBOUND_
            | FILE_FLAG_OVERLAPPED_, //write flag
            0, 1, 8192, 8192, 0, nullptr);


    if (source == boost::winapi::INVALID_HANDLE_VALUE_)
        ::boost::process::detail::throw_last_error("create_named_pipe(" + name + ") failed");

    _source.assign(source);

    ::boost::winapi::HANDLE_ sink = boost::winapi::create_file(
#if defined(BOOST_NO_ANSI_APIS)
            ::boost::process::detail::convert(name).c_str(),
#else
            name.c_str(),
#endif
            ::boost::winapi::GENERIC_WRITE_, 0, nullptr,
            ::boost::winapi::OPEN_EXISTING_,
            FILE_FLAG_OVERLAPPED_, //to allow read
            nullptr);

    if (sink == ::boost::winapi::INVALID_HANDLE_VALUE_)
        ::boost::process::detail::throw_last_error("create_file() failed");

    _sink.assign(sink);
}

async_pipe& async_pipe::operator=(const async_pipe & p)
{
    auto proc = ::boost::winapi::GetCurrentProcess();

    ::boost::winapi::HANDLE_ source;
    ::boost::winapi::HANDLE_ sink;

    //cannot get the handle from a const object.
    auto &source_in = const_cast<::boost::asio::windows::stream_handle &>(p._source);
    auto &sink_in   = const_cast<::boost::asio::windows::stream_handle &>(p._sink);

    if (source_in.native_handle() == ::boost::winapi::INVALID_HANDLE_VALUE_)
        source = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, source_in.native_handle(), proc, &source, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    if (sink_in.native_handle()   == ::boost::winapi::INVALID_HANDLE_VALUE_)
        sink = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, sink_in.native_handle(), proc, &sink, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    //so we also assign the io_context
    _source = ::boost::asio::windows::stream_handle(source_in.get_io_context(), source);
    _sink = ::boost::asio::windows::stream_handle(source_in.get_io_context(), sink);

    return *this;
}

async_pipe& async_pipe::operator=(async_pipe && rhs)
{
    if (_source.native_handle() != ::boost::winapi::INVALID_HANDLE_VALUE_)
        ::boost::winapi::CloseHandle(_source.native_handle());

    if (_sink.native_handle()   != ::boost::winapi::INVALID_HANDLE_VALUE_)
        ::boost::winapi::CloseHandle(_sink.native_handle());

    _source.assign(rhs._source.native_handle());
    _sink  .assign(rhs._sink  .native_handle());
    rhs._source.assign(::boost::winapi::INVALID_HANDLE_VALUE_);
    rhs._sink  .assign(::boost::winapi::INVALID_HANDLE_VALUE_);
    return *this;
}

template<class CharT, class Traits>
async_pipe::operator basic_pipe<CharT, Traits>() const
{
    auto proc = ::boost::winapi::GetCurrentProcess();

    ::boost::winapi::HANDLE_ source;
    ::boost::winapi::HANDLE_ sink;

    //cannot get the handle from a const object.
    auto source_in = const_cast<::boost::asio::windows::stream_handle &>(_source).native_handle();
    auto sink_in   = const_cast<::boost::asio::windows::stream_handle &>(_sink).native_handle();

    if (source_in == ::boost::winapi::INVALID_HANDLE_VALUE_)
        source = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, source_in, proc, &source, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    if (sink_in == ::boost::winapi::INVALID_HANDLE_VALUE_)
        sink = ::boost::winapi::INVALID_HANDLE_VALUE_;
    else if (!::boost::winapi::DuplicateHandle(
            proc, sink_in, proc, &sink, 0,
            static_cast<::boost::winapi::BOOL_>(true),
             ::boost::winapi::DUPLICATE_SAME_ACCESS_))
        throw_last_error("Duplicate Pipe Failed");

    return basic_pipe<CharT, Traits>{source, sink};
}

inline bool operator==(const async_pipe & lhs, const async_pipe & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

inline bool operator!=(const async_pipe & lhs, const async_pipe & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator==(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator!=(const async_pipe & lhs, const basic_pipe<Char, Traits> & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator==(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
    return compare_handles(lhs.native_source(), rhs.native_source()) &&
           compare_handles(lhs.native_sink(),   rhs.native_sink());
}

template<class Char, class Traits>
inline bool operator!=(const basic_pipe<Char, Traits> & lhs, const async_pipe & rhs)
{
    return !compare_handles(lhs.native_source(), rhs.native_source()) ||
           !compare_handles(lhs.native_sink(),   rhs.native_sink());
}

}}}}

#endif /* INCLUDE_BOOST_PIPE_DETAIL_WINDOWS_ASYNC_PIPE_HPP_ */