summaryrefslogtreecommitdiffstats
path: root/netwerk/base/nsTemporaryFileInputStream.cpp
blob: 86dc9e06d9c5b80ab0053d6a032e74a4903ecd8a (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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsTemporaryFileInputStream.h"

#include "mozilla/ipc/InputStreamUtils.h"
#include "mozilla/Mutex.h"
#include "nsStreamUtils.h"
#include "private/pprio.h"
#include <algorithm>

using namespace mozilla;
using namespace mozilla::ipc;

typedef mozilla::ipc::FileDescriptor::PlatformHandleType FileHandleType;

NS_IMPL_ISUPPORTS(nsTemporaryFileInputStream,
                  nsIInputStream,
                  nsISeekableStream,
                  nsIIPCSerializableInputStream)

nsTemporaryFileInputStream::nsTemporaryFileInputStream(FileDescOwner* aFileDescOwner, uint64_t aStartPos, uint64_t aEndPos)
  : mFileDescOwner(aFileDescOwner),
    mStartPos(aStartPos),
    mCurPos(aStartPos),
    mEndPos(aEndPos),
    mClosed(false)
{ 
  NS_ASSERTION(aStartPos <= aEndPos, "StartPos should less equal than EndPos!");
}

nsTemporaryFileInputStream::nsTemporaryFileInputStream()
  : mStartPos(0),
    mCurPos(0),
    mEndPos(0),
    mClosed(false)
{
}

NS_IMETHODIMP
nsTemporaryFileInputStream::Close()
{
  mClosed = true;
  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::Available(uint64_t * bytesAvailable)
{
  if (mClosed)
    return NS_BASE_STREAM_CLOSED;

  NS_ASSERTION(mCurPos <= mEndPos, "CurPos should less equal than EndPos!");

  *bytesAvailable = mEndPos - mCurPos;
  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::Read(char* buffer, uint32_t count, uint32_t* bytesRead)
{
  return ReadSegments(NS_CopySegmentToBuffer, buffer, count, bytesRead);
}

NS_IMETHODIMP
nsTemporaryFileInputStream::ReadSegments(nsWriteSegmentFun writer,
                                         void *            closure,
                                         uint32_t          count,
                                         uint32_t *        result)
{
  NS_ASSERTION(result, "null ptr");
  NS_ASSERTION(mCurPos <= mEndPos, "bad stream state");
  *result = 0;

  if (mClosed) {
    return NS_BASE_STREAM_CLOSED;
  }

  mozilla::MutexAutoLock lock(mFileDescOwner->FileMutex());
  int64_t offset = PR_Seek64(mFileDescOwner->mFD, mCurPos, PR_SEEK_SET);
  if (offset == -1) {
    return NS_ErrorAccordingToNSPR();
  }

  // Limit requested count to the amount remaining in our section of the file.
  count = std::min(count, uint32_t(mEndPos - mCurPos));

  char buf[4096];
  while (*result < count) {
    uint32_t bufCount = std::min(count - *result, (uint32_t) sizeof(buf));
    int32_t bytesRead = PR_Read(mFileDescOwner->mFD, buf, bufCount);
    if (bytesRead == 0) {
      mClosed = true;
      return NS_OK;
    }

    if (bytesRead < 0) {
      return NS_ErrorAccordingToNSPR();
    }

    int32_t bytesWritten = 0;
    while (bytesWritten < bytesRead) {
      uint32_t writerCount = 0;
      nsresult rv = writer(this, closure, buf + bytesWritten, *result,
                           bytesRead - bytesWritten, &writerCount);
      if (NS_FAILED(rv) || writerCount == 0) {
        // nsIInputStream::ReadSegments' contract specifies that errors
        // from writer are not propagated to ReadSegments' caller.
        //
        // If writer fails, leaving bytes still in buf, that's okay: we
        // only update mCurPos to reflect successful writes, so the call
        // to PR_Seek64 at the top will restart us at the right spot.
        return NS_OK;
      }
      NS_ASSERTION(writerCount <= (uint32_t) (bytesRead - bytesWritten),
                   "writer should not write more than we asked it to write");
      bytesWritten += writerCount;
      *result += writerCount;
      mCurPos += writerCount;
    }
  }

  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::IsNonBlocking(bool * nonBlocking)
{
  *nonBlocking = false;
  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::Seek(int32_t aWhence, int64_t aOffset)
{
  if (mClosed) {
    return NS_BASE_STREAM_CLOSED;
  }

  switch (aWhence) {
    case nsISeekableStream::NS_SEEK_SET:
      aOffset += mStartPos;
      break;

    case nsISeekableStream::NS_SEEK_CUR:
      aOffset += mCurPos;
      break;

    case nsISeekableStream::NS_SEEK_END:
      aOffset += mEndPos;
      break;

    default:
      return NS_ERROR_FAILURE;
  }

  if (aOffset < (int64_t)mStartPos || aOffset > (int64_t)mEndPos) {
    return NS_ERROR_INVALID_ARG;
  }

  mCurPos = aOffset;
  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::Tell(int64_t* aPos)
{
  if (!aPos) {
    return NS_ERROR_FAILURE;
  }

  if (mClosed) {
    return NS_BASE_STREAM_CLOSED;
  }

  MOZ_ASSERT(mStartPos <= mCurPos, "StartPos should less equal than CurPos!");
  *aPos = mCurPos - mStartPos;
  return NS_OK;
}

NS_IMETHODIMP
nsTemporaryFileInputStream::SetEOF()
{
  if (mClosed) {
    return NS_BASE_STREAM_CLOSED;
  }

  return Close();
}

void
nsTemporaryFileInputStream::Serialize(InputStreamParams& aParams,
                                      FileDescriptorArray& aFileDescriptors)
{
  TemporaryFileInputStreamParams params;

  MutexAutoLock lock(mFileDescOwner->FileMutex());
  MOZ_ASSERT(mFileDescOwner->mFD);
  if (!mClosed) {
    FileHandleType fd = FileHandleType(PR_FileDesc2NativeHandle(mFileDescOwner->mFD));
    NS_ASSERTION(fd, "This should never be null!");

    DebugOnly<FileDescriptor*> dbgFD = aFileDescriptors.AppendElement(fd);
    NS_ASSERTION(dbgFD->IsValid(), "Sending an invalid file descriptor!");

    params.fileDescriptorIndex() = aFileDescriptors.Length() - 1;

    Close();
  } else {
    NS_WARNING("The stream is already closed. "
               "Sending an invalid file descriptor to the other process!");

    params.fileDescriptorIndex() = UINT32_MAX;
  }
  params.startPos() = mCurPos;
  params.endPos() = mEndPos;
  aParams = params;
}

bool
nsTemporaryFileInputStream::Deserialize(const InputStreamParams& aParams,
                                        const FileDescriptorArray& aFileDescriptors)
{
  const TemporaryFileInputStreamParams& params = aParams.get_TemporaryFileInputStreamParams();

  uint32_t fileDescriptorIndex = params.fileDescriptorIndex();
  FileDescriptor fd;
  if (fileDescriptorIndex < aFileDescriptors.Length()) {
    fd = aFileDescriptors[fileDescriptorIndex];
    NS_WARNING_ASSERTION(fd.IsValid(),
                         "Received an invalid file descriptor!");
  } else {
    NS_WARNING("Received a bad file descriptor index!");
  }

  if (fd.IsValid()) {
    auto rawFD = fd.ClonePlatformHandle();
    PRFileDesc* fileDesc = PR_ImportFile(PROsfd(rawFD.release()));
    if (!fileDesc) {
      NS_WARNING("Failed to import file handle!");
      return false;
    }
    mFileDescOwner = new FileDescOwner(fileDesc);
  } else {
    mClosed = true;
  }

  mStartPos = mCurPos = params.startPos();
  mEndPos = params.endPos();
  return true;
}

Maybe<uint64_t>
nsTemporaryFileInputStream::ExpectedSerializedLength()
{
  return Nothing();
}