OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2009 The Chromium 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 "base/file_descriptor_shuffle.h" |
| 6 |
| 7 #include <errno.h> |
| 8 #include <unistd.h> |
| 9 |
| 10 #include "base/logging.h" |
| 11 |
| 12 namespace base { |
| 13 |
| 14 bool PerformInjectiveMultimap(const InjectiveMultimap& m_in, |
| 15 InjectionDelegate* delegate) { |
| 16 InjectiveMultimap m(m_in); |
| 17 std::vector<int> extra_fds; |
| 18 |
| 19 for (InjectiveMultimap::iterator i = m.begin(); i != m.end(); ++i) { |
| 20 int temp_fd = -1; |
| 21 |
| 22 // We DCHECK the injectiveness of the mapping. |
| 23 for (InjectiveMultimap::iterator j = i + 1; j != m.end(); ++j) |
| 24 DCHECK(i->dest != j->dest); |
| 25 |
| 26 const bool is_identity = i->source == i->dest; |
| 27 |
| 28 for (InjectiveMultimap::iterator j = i + 1; j != m.end(); ++j) { |
| 29 if (!is_identity && i->dest == j->source) { |
| 30 if (temp_fd == -1) { |
| 31 if (!delegate->Duplicate(&temp_fd, i->dest)) |
| 32 return false; |
| 33 extra_fds.push_back(temp_fd); |
| 34 } |
| 35 |
| 36 j->source = temp_fd; |
| 37 j->close = false; |
| 38 } |
| 39 |
| 40 if (i->close && i->source == j->dest) |
| 41 i->close = false; |
| 42 |
| 43 if (i->close && i->source == j->source) { |
| 44 i->close = false; |
| 45 j->close = true; |
| 46 } |
| 47 } |
| 48 |
| 49 if (!is_identity) { |
| 50 if (!delegate->Move(i->source, i->dest)) |
| 51 return false; |
| 52 } |
| 53 |
| 54 if (!is_identity && i->close) |
| 55 delegate->Close(i->source); |
| 56 } |
| 57 |
| 58 for (std::vector<int>::const_iterator |
| 59 i = extra_fds.begin(); i != extra_fds.end(); ++i) { |
| 60 delegate->Close(*i); |
| 61 } |
| 62 |
| 63 return true; |
| 64 } |
| 65 |
| 66 bool FileDescriptorTableInjection::Duplicate(int* result, int fd) { |
| 67 do { |
| 68 *result = dup(fd); |
| 69 } while(*result == -1 && errno == EINTR); |
| 70 |
| 71 return *result >= 0; |
| 72 } |
| 73 |
| 74 bool FileDescriptorTableInjection::Move(int src, int dest) { |
| 75 int result; |
| 76 |
| 77 do { |
| 78 result = dup2(src, dest); |
| 79 } while (result == -1 && errno == EINTR); |
| 80 |
| 81 return result != -1; |
| 82 } |
| 83 |
| 84 void FileDescriptorTableInjection::Close(int fd) { |
| 85 int result; |
| 86 |
| 87 do { |
| 88 result = close(fd); |
| 89 } while (result == -1 && errno == EINTR); |
| 90 } |
| 91 |
| 92 } // namespace base |
OLD | NEW |