]> git.saurik.com Git - apple/security.git/blob - Network/xfercore.cpp
Security-28.tar.gz
[apple/security.git] / Network / xfercore.cpp
1 /*
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
8 * using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
16 */
17
18
19 //
20 // xfercore - core data transfer engine
21 //
22 #include "xfercore.h"
23 #include <Security/debugging.h>
24
25
26 namespace Security {
27 namespace Network {
28
29
30 //
31 // Create an engine-level client object.
32 // @@@ Defer buffer allocation to mating?
33 // @@@ Defer state initialization to mating?
34 //
35 TransferEngine::Client::Client()
36 : mMode(invalidInput), mAutoCopyOut(false),
37 mSink(NULL), mSource(NULL),
38 mAutoFlush(true),
39 mReadBuffer(16384), mWriteBuffer(16384)
40 {
41 }
42
43 TransferEngine::Client::~Client()
44 {
45 }
46
47
48 //
49 // Add and remove clients to/from the engine
50 //
51 void TransferEngine::add(Client *client)
52 {
53 client->io = client->fileDesc(); // punch master I/O down to Selector client level
54 Selector::add(client->io, *client, input | critical); // initial registration
55 }
56
57 void TransferEngine::remove(Client *client)
58 {
59 #ifndef NDEBUG
60 if (!client->mReadBuffer.isEmpty())
61 debug("xferengine", "xfer %p(%d) HAD %ld BYTES READ LEFT",
62 client, client->fileDesc(), client->mReadBuffer.length());
63 if (!client->mWriteBuffer.isEmpty())
64 debug("xferengine", "xfer %p(%d) HAD %ld BYTES WRITE LEFT",
65 client, client->fileDesc(), client->mWriteBuffer.length());
66 #endif //NDEBUG
67 Selector::remove(client->io);
68 client->io = FileDesc(); // invalidate
69 }
70
71
72 //
73 // Mode switching.
74 // In addition to the generic switcher (mode), there are variants that set associated
75 // information, such as sources/sinks.
76 //
77 void TransferEngine::Client::mode(InputMode newMode)
78 {
79 debug("xferengine", "xfer %p(%d) switching to mode %d", this, fileDesc(), newMode);
80 switch (newMode) {
81 case rawInput:
82 case lineInput:
83 mMode = newMode;
84 break;
85 case connecting:
86 enable(output);
87 mMode = connecting;
88 break;
89 default:
90 assert(false); // can't switch to these modes like that
91 }
92 }
93
94 void TransferEngine::Client::mode(Sink &sink, size_t byteCount)
95 {
96 mMode = autoReadInput;
97 mSink = &sink;
98 mResidualReadCount = byteCount;
99 debug("xferengine", "xfer %p(%d) switching to autoReadInput (%ld bytes)",
100 this, fileDesc(), byteCount);
101 }
102
103 void TransferEngine::Client::mode(Source &source, size_t byteCount)
104 {
105 assert (!mAutoCopyOut); // no replacements, please
106 mAutoCopyOut = true;
107 mSource = &source;
108 mResidualWriteCount = byteCount;
109 debug("xferengine", "xfer %p(%d) enabling autoCopyOut mode (%ld bytes)",
110 this, fileDesc(), byteCount);
111 enable(output);
112 }
113
114
115 //
116 // Output methods. This queues output to be sent to the client's connection
117 // as soon as practical.
118 //
119 void TransferEngine::Client::printf(const char *format, ...)
120 {
121 va_list args;
122 va_start(args, format);
123 vprintf(format, args);
124 va_end(args);
125 }
126
127 void TransferEngine::Client::vprintf(const char *format, va_list args)
128 {
129 mWriteBuffer.vprintf(format, args);
130 #if !defined(NDEBUG)
131 char buffer[1024];
132 vsnprintf(buffer, sizeof(buffer), format, args);
133 debug("engineio", "%p(%d) <-- %s", this, fileDesc(), buffer);
134 #endif //NDEBUG
135 startOutput();
136 }
137
138 void TransferEngine::Client::printfe(const char *format, ...)
139 {
140 va_list args;
141 va_start(args, format);
142 vprintfe(format, args);
143 va_end(args);
144 }
145
146 void TransferEngine::Client::vprintfe(const char *format, va_list args)
147 {
148 mWriteBuffer.vprintf(format, args);
149 mWriteBuffer.printf("\r\n");
150 #if !defined(NDEBUG)
151 char buffer[1024];
152 vsnprintf(buffer, sizeof(buffer), format, args);
153 debug("engineio", "%p(%d) <-- %s[CRNL]", this, fileDesc(), buffer);
154 #endif //NDEBUG
155 startOutput();
156 }
157
158
159 //
160 // Set output auto-flush mode. Think of this as a weak output-hold mode.
161 // If autoflush is off, we don't try hard to send data out immediately. If it's
162 // on, we send data as soon as it's generated.
163 // Calling flushOutput(true) always generates I/O as needed to send output
164 // data NOW (even if the mode was already on).
165 //
166 void TransferEngine::Client::flushOutput(bool autoFlush)
167 {
168 mAutoFlush = autoFlush;
169 debug("engineio", "%p(%d) output flush %s", this, fileDesc(), autoFlush? "on" : "off");
170 if (mAutoFlush)
171 startOutput();
172 }
173
174
175 //
176 // StartOutput is called by output generators to get output flowing.
177 // It may generate output I/O, or hold things in buffers according to
178 // current settings.
179 //
180 void TransferEngine::Client::startOutput()
181 {
182 if (mAutoFlush) {
183 if (mAutoCopyOut && !mWriteBuffer.isFull())
184 autoCopy(); // try to tack on some autoCopy output
185 if (!mWriteBuffer.isEmpty()) {
186 mWriteBuffer.write(*this);
187 if (mAutoFlush || !mWriteBuffer.isEmpty()) { // possibly more output
188 enable(output); // ask for output-drain notification
189 } else {
190 disable(output); // no need for output-possible events
191 }
192 }
193 }
194 }
195
196
197 //
198 // Given that autoCopyOut mode is active, try to transfer some bytes
199 // into the write buffer. This is a lazy, fast push, suitable for tacking on
200 // when you are about to send data for some other reason.
201 // Returns the number of bytes retrieved from the auto-Source (possibly zero).
202 //
203 size_t TransferEngine::Client::autoCopy()
204 {
205 size_t len = mWriteBuffer.available(); //@@@ (true) ?
206 if (mResidualWriteCount && mResidualWriteCount < len)
207 len = mResidualWriteCount;
208 void *addr; mWriteBuffer.locatePut(addr, len);
209 mSource->produce(addr, len);
210 debug("xferengine", "xfer %p(%d) autoCopyOut source delivered %ld bytes",
211 this, fileDesc(), len);
212 mWriteBuffer.usePut(len);
213 return len;
214 }
215
216
217 //
218 // This is the notify function called by the IP Selector layer when I/O is possible.
219 // It runs the state machines for all current clients, calling their transit methods
220 // in turn.
221 //
222 void TransferEngine::Client::notify(int fd, Type type)
223 {
224 try {
225 //@@@ Note: We do not currently do anything special about critical events.
226
227 if (type & Selector::output) {
228 // if we're in connecting mode
229 if (mMode == connecting) {
230 Socket s; s = fd; // Socket(fd) means something different...
231 int error = s.error();
232 debug("xferengine", "xfer %p(%d) connect (errno %d)",
233 this, fd, error);
234 transit(connectionDone, NULL, error);
235 return;
236 }
237
238 //@@@ use high/low water marks here
239 if (mAutoCopyOut && !mWriteBuffer.isFull()) {
240 if (autoCopy() == 0) {
241 switch (mSource->state()) {
242 case Source::stalled:
243 // ah well, maybe later
244 debug("xferengine", "xfer %p(%d) autoCopyOut source is stalled", this, fd);
245 break;
246 case Source::endOfData:
247 mAutoCopyOut = false; // done
248 debug("xferengine", "xfer %p(%d) autoCopyOut end of data", this, fd);
249 if (mResidualWriteCount > 0)
250 debug("xferengine", "xfer %p(%d) has %ld autoCopy bytes left",
251 this, fd, mResidualWriteCount);
252 transit(autoWriteDone);
253 if (!isActive())
254 return; // transit removed us; stop now
255 break;
256 default:
257 assert(false);
258 }
259 }
260 }
261 if (mWriteBuffer.isEmpty()) { // output possible, no output pending
262 debug("xferengine", "xfer %p(%d) disabling output (empty)", this, fd);
263 disable(output);
264 } else { // stuff some more
265 size_t length = mWriteBuffer.write(*this);
266 debug("xferengine", "xfer %p(%d) writing %ld bytes", this, fd, length);
267 }
268 }
269
270 if (type & Selector::input) {
271 IFDEBUG(debug("xferengine", "xfer %p(%d) input ready %d bytes",
272 this, fd, io.iocget<int>(FIONREAD)));
273
274 do {
275 //@@@ break out after partial buffer to give Equal Time to other transfers? good idea?!
276 if (mReadBuffer.read(*this) == 0) {
277 mReadBuffer.read(*this, true);
278 }
279
280 if (mReadBuffer.isEmpty() && atEnd()) {
281 transit(endOfInput);
282 break;
283 }
284 switch (mMode) {
285 case rawInput:
286 rawInputTransit();
287 break;
288 case lineInput:
289 lineInputTransit();
290 break;
291 case autoReadInput:
292 autoReadInputTransit();
293 if (mMode != autoIODone)
294 break;
295 // autoRead completed; fall through to autoIODone handling
296 case autoIODone:
297 mMode = invalidInput; // pre-mark error
298 transit(autoReadDone); // notify; this must reset mode or exit
299 if (!isActive()) // if we're terminated...
300 return; // ... then go
301 assert(mMode != invalidInput); // else enforce mode reset
302 break;
303 case connecting:
304 {
305 // we should never be here. Selector gave us "read but not write" while connecting. FUBAR
306 Socket s; s = fd;
307 debug("xferengine",
308 "fd %d input while connecting (errno=%d, type=%d)",
309 fd, s.error(), type);
310 UnixError::throwMe(ECONNREFUSED); // likely interpretation
311 }
312 default:
313 debug("xferengine", "mode error in input sequencer (mode=%d)", mMode);
314 assert(false);
315 }
316 if (!io) // client has unhooked; clear buffer and exit loop
317 mReadBuffer.clear();
318 } while (!mReadBuffer.isEmpty());
319 //@@@ feed back for more output here? But also see comments above...
320 //@@@ probably better to take the trip through the Selector
321 }
322 } catch (CssmCommonError &err) {
323 transitError(err);
324 } catch (...) {
325 transitError(UnixError::make(EIO)); // best guess (could be anything)
326 }
327 }
328
329 void TransferEngine::Client::rawInputTransit()
330 {
331 // just shove it at the user
332 char *addr; size_t length = mReadBuffer.length();
333 mReadBuffer.locateGet(addr, length);
334 IFDEBUG(debug("engineio", "%p(%d) --> %d bytes RAW",
335 this, fileDesc(), io.iocget<int>(FIONREAD)));
336 transit(inputAvailable, addr, length);
337 mReadBuffer.usePut(length);
338 }
339
340 void TransferEngine::Client::lineInputTransit()
341 {
342 char *line; size_t length = mReadBuffer.length();
343 mReadBuffer.locateGet(line, length);
344
345 char *nl;
346 for (nl = line; nl < line + length && *nl != '\n'; nl++) ;
347 if (nl == line + length) // no end-of-line, wait for more
348 return;
349
350 if (nl > line && nl[-1] == '\r') { // proper \r\n termination
351 nl[-1] = '\0'; // terminate for transit convenience
352 debug("engineio", "%p(%d) --> %s", this, fileDesc(), line);
353 transit(inputAvailable, line, nl - line - 1);
354 } else { // improper, tolerate
355 nl[0] = '\0'; // terminate for transit convenience
356 debug("engineio", "%p(%d) [IMPROPER] --> %s", this, fileDesc(), line);
357 transit(inputAvailable, line, nl - line);
358 }
359 mReadBuffer.useGet(nl - line + 1);
360 }
361
362 void TransferEngine::Client::autoReadInputTransit()
363 {
364 debug("xferengine", "xfer %p(%d) %ld pending %d available",
365 this, fileDesc(), mReadBuffer.length(), io.iocget<int>(FIONREAD));
366 void *data; size_t length = mReadBuffer.length();
367 if (mResidualReadCount && mResidualReadCount < length)
368 length = mResidualReadCount;
369 mReadBuffer.locateGet(data, length);
370 debug("engineio", "%p(%d) --> %ld bytes autoReadInput", this, fileDesc(), length);
371 mSink->consume(data, length);
372 mReadBuffer.useGet(length);
373 if (mResidualReadCount && (mResidualReadCount -= length) == 0)
374 mMode = autoIODone;
375 }
376
377
378 //
379 // The (protected) tickle() method causes a one-time scan
380 // of the requesting client. This will simulate an input-ready event
381 // and possibly call the transit method.
382 // This is designed to be used from validate() or in other unusual
383 // external situations. Don't call this from within transit().
384 //
385 void TransferEngine::Client::tickle()
386 {
387 notify(io, input | critical);
388 }
389
390
391 //
392 // The default read/write methods perform direct I/O on the underlying file descriptor.
393 //
394 size_t TransferEngine::Client::read(void *data, size_t size)
395 { return io.read(data, size); }
396
397 size_t TransferEngine::Client::write(const void *data, size_t size)
398 { return io.write(data, size); }
399
400 bool TransferEngine::Client::atEnd() const
401 { return io.atEnd(); }
402
403
404 } // end namespace Network
405 } // end namespace Security