summaryrefslogtreecommitdiffstats
path: root/Doc/lib/libthreading.tex
blob: 19c496e499d3de85cb258fb044831abf2a706cd2 (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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
\section{\module{threading} ---
         Higher-level threading interface}

\declaremodule{standard}{threading}
\modulesynopsis{Higher-level threading interface.}


This module constructs higher-level threading interfaces on top of the 
lower level \refmodule{thread} module.

The \refmodule[dummythreading]{dummy_threading} module is provided for
situations where \module{threading} cannot be used because
\refmodule{thread} is missing.

This module defines the following functions and objects:

\begin{funcdesc}{activeCount}{}
Return the number of \class{Thread} objects currently alive.  The
returned count is equal to the length of the list returned by
\function{enumerate()}.
\end{funcdesc}

\begin{funcdescni}{Condition}{}
A factory function that returns a new condition variable object.
A condition variable allows one or more threads to wait until they
are notified by another thread.
\end{funcdescni}

\begin{funcdesc}{currentThread}{}
Return the current \class{Thread} object, corresponding to the
caller's thread of control.  If the caller's thread of control was not
created through the
\module{threading} module, a dummy thread object with limited functionality
is returned.
\end{funcdesc}

\begin{funcdesc}{enumerate}{}
Return a list of all \class{Thread} objects currently alive.  The list
includes daemonic threads, dummy thread objects created by
\function{currentThread()}, and the main thread.  It excludes
terminated threads and threads that have not yet been started.
\end{funcdesc}

\begin{funcdescni}{Event}{}
A factory function that returns a new event object.  An event manages
a flag that can be set to true with the \method{set()} method and
reset to false with the \method{clear()} method.  The \method{wait()}
method blocks until the flag is true.
\end{funcdescni}

\begin{classdesc*}{local}{}
A class that represents thread-local data.  Thread-local data are data
whose values are thread specific.  To manage thread-local data, just
create an instance of \class{local} (or a subclass) and store
attributes on it:

\begin{verbatim}
mydata = threading.local()
mydata.x = 1
\end{verbatim}

The instance's values will be different for separate threads.

For more details and extensive examples, see the documentation string
of the \module{_threading_local} module.

\versionadded{2.4}
\end{classdesc*}

\begin{funcdesc}{Lock}{}
A factory function that returns a new primitive lock object.  Once
a thread has acquired it, subsequent attempts to acquire it block,
until it is released; any thread may release it.
\end{funcdesc}

\begin{funcdesc}{RLock}{}
A factory function that returns a new reentrant lock object.
A reentrant lock must be released by the thread that acquired it.
Once a thread has acquired a reentrant lock, the same thread may
acquire it again without blocking; the thread must release it once
for each time it has acquired it.
\end{funcdesc}

\begin{funcdescni}{Semaphore}{\optional{value}}
A factory function that returns a new semaphore object.  A
semaphore manages a counter representing the number of \method{release()}
calls minus the number of \method{acquire()} calls, plus an initial value.
The \method{acquire()} method blocks if necessary until it can return
without making the counter negative.  If not given, \var{value} defaults to
1. 
\end{funcdescni}

\begin{funcdesc}{BoundedSemaphore}{\optional{value}}
A factory function that returns a new bounded semaphore object.  A bounded
semaphore checks to make sure its current value doesn't exceed its initial
value.  If it does, \exception{ValueError} is raised. In most situations
semaphores are used to guard resources with limited capacity.  If the
semaphore is released too many times it's a sign of a bug.  If not given,
\var{value} defaults to 1. 
\end{funcdesc}

\begin{classdesc*}{Thread}
A class that represents a thread of control.  This class can be safely
subclassed in a limited fashion.
\end{classdesc*}

\begin{classdesc*}{Timer}
A thread that executes a function after a specified interval has passed.
\end{classdesc*}

\begin{funcdesc}{settrace}{func}
Set a trace function\index{trace function} for all threads started
from the \module{threading} module.  The \var{func} will be passed to 
\function{sys.settrace()} for each thread, before its \method{run()}
method is called.
\versionadded{2.3}
\end{funcdesc}

\begin{funcdesc}{setprofile}{func}
Set a profile function\index{profile function} for all threads started
from the \module{threading} module.  The \var{func} will be passed to 
\function{sys.setprofile()} for each thread, before its \method{run()}
method is called.
\versionadded{2.3}
\end{funcdesc}

\begin{funcdesc}{stack_size}{\optional{size}}
Return the thread stack size used when creating new threads.  The
optional \var{size} argument specifies the stack size to be used for
subsequently created threads, and must be 0 (use platform or
configured default) or a positive integer value of at least 32,768 (32kB).
If changing the thread stack size is unsupported, a \exception{ThreadError}
is raised.  If the specified stack size is invalid, a \exception{ValueError}
is raised and the stack size is unmodified.  32kB is currently the minimum
supported stack size value to guarantee sufficient stack space for the
interpreter itself.  Note that some platforms may have particular
restrictions on values for the stack size, such as requiring a minimum
stack size > 32kB or requiring allocation in multiples of the system
memory page size - platform documentation should be referred to for
more information (4kB pages are common; using multiples of 4096 for
the stack size is the suggested approach in the absence of more
specific information).
Availability: Windows, systems with \POSIX{} threads.
\versionadded{2.5}
\end{funcdesc}

Detailed interfaces for the objects are documented below.  

The design of this module is loosely based on Java's threading model.
However, where Java makes locks and condition variables basic behavior
of every object, they are separate objects in Python.  Python's \class{Thread}
class supports a subset of the behavior of Java's Thread class;
currently, there are no priorities, no thread groups, and threads
cannot be destroyed, stopped, suspended, resumed, or interrupted.  The
static methods of Java's Thread class, when implemented, are mapped to
module-level functions.

All of the methods described below are executed atomically.


\subsection{Lock Objects \label{lock-objects}}

A primitive lock is a synchronization primitive that is not owned
by a particular thread when locked.  In Python, it is currently
the lowest level synchronization primitive available, implemented
directly by the \refmodule{thread} extension module.

A primitive lock is in one of two states, ``locked'' or ``unlocked''.
It is created in the unlocked state.  It has two basic methods,
\method{acquire()} and \method{release()}.  When the state is
unlocked, \method{acquire()} changes the state to locked and returns
immediately.  When the state is locked, \method{acquire()} blocks
until a call to \method{release()} in another thread changes it to
unlocked, then the \method{acquire()} call resets it to locked and
returns.  The \method{release()} method should only be called in the
locked state; it changes the state to unlocked and returns
immediately. If an attempt is made to release an unlocked lock, a
\exception{RuntimeError} will be raised.

When more than one thread is blocked in \method{acquire()} waiting for
the state to turn to unlocked, only one thread proceeds when a
\method{release()} call resets the state to unlocked; which one of the
waiting threads proceeds is not defined, and may vary across
implementations.

All methods are executed atomically.

\begin{methoddesc}[Lock]{acquire}{\optional{blocking\code{ = 1}}}
Acquire a lock, blocking or non-blocking.

When invoked without arguments, block until the lock is
unlocked, then set it to locked, and return true.  

When invoked with the \var{blocking} argument set to true, do the
same thing as when called without arguments, and return true.

When invoked with the \var{blocking} argument set to false, do not
block.  If a call without an argument would block, return false
immediately; otherwise, do the same thing as when called
without arguments, and return true.
\end{methoddesc}

\begin{methoddesc}[Lock]{release}{}
Release a lock.

When the lock is locked, reset it to unlocked, and return.  If
any other threads are blocked waiting for the lock to become
unlocked, allow exactly one of them to proceed.

Do not call this method when the lock is unlocked.

There is no return value.
\end{methoddesc}


\subsection{RLock Objects \label{rlock-objects}}

A reentrant lock is a synchronization primitive that may be
acquired multiple times by the same thread.  Internally, it uses
the concepts of ``owning thread'' and ``recursion level'' in
addition to the locked/unlocked state used by primitive locks.  In
the locked state, some thread owns the lock; in the unlocked
state, no thread owns it.

To lock the lock, a thread calls its \method{acquire()} method; this
returns once the thread owns the lock.  To unlock the lock, a
thread calls its \method{release()} method.
\method{acquire()}/\method{release()} call pairs may be nested; only
the final \method{release()} (the \method{release()} of the outermost
pair) resets the lock to unlocked and allows another thread blocked in
\method{acquire()} to proceed.

\begin{methoddesc}[RLock]{acquire}{\optional{blocking\code{ = 1}}}
Acquire a lock, blocking or non-blocking.

When invoked without arguments: if this thread already owns
the lock, increment the recursion level by one, and return
immediately.  Otherwise, if another thread owns the lock,
block until the lock is unlocked.  Once the lock is unlocked
(not owned by any thread), then grab ownership, set the
recursion level to one, and return.  If more than one thread
is blocked waiting until the lock is unlocked, only one at a
time will be able to grab ownership of the lock.  There is no
return value in this case.

When invoked with the \var{blocking} argument set to true, do the
same thing as when called without arguments, and return true.

When invoked with the \var{blocking} argument set to false, do not
block.  If a call without an argument would block, return false
immediately; otherwise, do the same thing as when called
without arguments, and return true.
\end{methoddesc}

\begin{methoddesc}[RLock]{release}{}
Release a lock, decrementing the recursion level.  If after the
decrement it is zero, reset the lock to unlocked (not owned by any
thread), and if any other threads are blocked waiting for the lock to
become unlocked, allow exactly one of them to proceed.  If after the
decrement the recursion level is still nonzero, the lock remains
locked and owned by the calling thread.

Only call this method when the calling thread owns the lock. A
\exception{RuntimeError} is raised if this method is called when the
lock is unlocked.

There is no return value.
\end{methoddesc}


\subsection{Condition Objects \label{condition-objects}}

A condition variable is always associated with some kind of lock;
this can be passed in or one will be created by default.  (Passing
one in is useful when several condition variables must share the
same lock.)

A condition variable has \method{acquire()} and \method{release()}
methods that call the corresponding methods of the associated lock.
It also has a \method{wait()} method, and \method{notify()} and
\method{notifyAll()} methods.  These three must only be called when
the calling thread has acquired the lock, otherwise a
\exception{RuntimeError} is raised.

The \method{wait()} method releases the lock, and then blocks until it
is awakened by a \method{notify()} or \method{notifyAll()} call for
the same condition variable in another thread.  Once awakened, it
re-acquires the lock and returns.  It is also possible to specify a
timeout.

The \method{notify()} method wakes up one of the threads waiting for
the condition variable, if any are waiting.  The \method{notifyAll()}
method wakes up all threads waiting for the condition variable.

Note: the \method{notify()} and \method{notifyAll()} methods don't
release the lock; this means that the thread or threads awakened will
not return from their \method{wait()} call immediately, but only when
the thread that called \method{notify()} or \method{notifyAll()}
finally relinquishes ownership of the lock.

Tip: the typical programming style using condition variables uses the
lock to synchronize access to some shared state; threads that are
interested in a particular change of state call \method{wait()}
repeatedly until they see the desired state, while threads that modify
the state call \method{notify()} or \method{notifyAll()} when they
change the state in such a way that it could possibly be a desired
state for one of the waiters.  For example, the following code is a
generic producer-consumer situation with unlimited buffer capacity:

\begin{verbatim}
# Consume one item
cv.acquire()
while not an_item_is_available():
    cv.wait()
get_an_available_item()
cv.release()

# Produce one item
cv.acquire()
make_an_item_available()
cv.notify()
cv.release()
\end{verbatim}

To choose between \method{notify()} and \method{notifyAll()}, consider
whether one state change can be interesting for only one or several
waiting threads.  E.g. in a typical producer-consumer situation,
adding one item to the buffer only needs to wake up one consumer
thread.

\begin{classdesc}{Condition}{\optional{lock}}
If the \var{lock} argument is given and not \code{None}, it must be a
\class{Lock} or \class{RLock} object, and it is used as the underlying
lock.  Otherwise, a new \class{RLock} object is created and used as
the underlying lock.
\end{classdesc}

\begin{methoddesc}{acquire}{*args}
Acquire the underlying lock.
This method calls the corresponding method on the underlying
lock; the return value is whatever that method returns.
\end{methoddesc}

\begin{methoddesc}{release}{}
Release the underlying lock.
This method calls the corresponding method on the underlying
lock; there is no return value.
\end{methoddesc}

\begin{methoddesc}{wait}{\optional{timeout}}
Wait until notified or until a timeout occurs. If the calling thread
has not acquired the lock when this method is called, a
\exception{RuntimeError} is raised.

This method releases the underlying lock, and then blocks until it is
awakened by a \method{notify()} or \method{notifyAll()} call for the
same condition variable in another thread, or until the optional
timeout occurs.  Once awakened or timed out, it re-acquires the lock
and returns.

When the \var{timeout} argument is present and not \code{None}, it
should be a floating point number specifying a timeout for the
operation in seconds (or fractions thereof).

When the underlying lock is an \class{RLock}, it is not released using
its \method{release()} method, since this may not actually unlock the
lock when it was acquired multiple times recursively.  Instead, an
internal interface of the \class{RLock} class is used, which really
unlocks it even when it has been recursively acquired several times.
Another internal interface is then used to restore the recursion level
when the lock is reacquired.
\end{methoddesc}

\begin{methoddesc}{notify}{}
Wake up a thread waiting on this condition, if any. Wait until
notified or until a timeout occurs. If the calling thread has not
acquired the lock when this method is called, a
\exception{RuntimeError} is raised.

This method wakes up one of the threads waiting for the condition
variable, if any are waiting; it is a no-op if no threads are waiting.

The current implementation wakes up exactly one thread, if any are
waiting.  However, it's not safe to rely on this behavior.  A future,
optimized implementation may occasionally wake up more than one
thread.

Note: the awakened thread does not actually return from its
\method{wait()} call until it can reacquire the lock.  Since
\method{notify()} does not release the lock, its caller should.
\end{methoddesc}

\begin{methoddesc}{notifyAll}{}
Wake up all threads waiting on this condition.  This method acts like
\method{notify()}, but wakes up all waiting threads instead of one. If
the calling thread has not acquired the lock when this method is
called, a \exception{RuntimeError} is raised.
\end{methoddesc}


\subsection{Semaphore Objects \label{semaphore-objects}}

This is one of the oldest synchronization primitives in the history of
computer science, invented by the early Dutch computer scientist
Edsger W. Dijkstra (he used \method{P()} and \method{V()} instead of
\method{acquire()} and \method{release()}).

A semaphore manages an internal counter which is decremented by each
\method{acquire()} call and incremented by each \method{release()}
call.  The counter can never go below zero; when \method{acquire()}
finds that it is zero, it blocks, waiting until some other thread
calls \method{release()}.

\begin{classdesc}{Semaphore}{\optional{value}}
The optional argument gives the initial \var{value} for the internal
counter; it defaults to \code{1}. If the \var{value} given is less
than 0, \exception{ValueError} is raised.
\end{classdesc}

\begin{methoddesc}{acquire}{\optional{blocking}}
Acquire a semaphore.

When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately.  If it is
zero on entry, block, waiting until some other thread has called
\method{release()} to make it larger than zero.  This is done with
proper interlocking so that if multiple \method{acquire()} calls are
blocked, \method{release()} will wake exactly one of them up.  The
implementation may pick one at random, so the order in which blocked
threads are awakened should not be relied on.  There is no return
value in this case.

When invoked with \var{blocking} set to true, do the same thing as
when called without arguments, and return true.

When invoked with \var{blocking} set to false, do not block.  If a
call without an argument would block, return false immediately;
otherwise, do the same thing as when called without arguments, and
return true.
\end{methoddesc}

\begin{methoddesc}{release}{}
Release a semaphore,
incrementing the internal counter by one.  When it was zero on
entry and another thread is waiting for it to become larger
than zero again, wake up that thread.
\end{methoddesc}


\subsubsection{\class{Semaphore} Example \label{semaphore-examples}}

Semaphores are often used to guard resources with limited capacity, for
example, a database server.  In any situation where the size of the resource
size is fixed, you should use a bounded semaphore.  Before spawning any
worker threads, your main thread would initialize the semaphore:

\begin{verbatim}
maxconnections = 5
...
pool_sema = BoundedSemaphore(value=maxconnections)
\end{verbatim}

Once spawned, worker threads call the semaphore's acquire and release
methods when they need to connect to the server:

\begin{verbatim}
pool_sema.acquire()
conn = connectdb()
... use connection ...
conn.close()
pool_sema.release()
\end{verbatim}

The use of a bounded semaphore reduces the chance that a programming error
which causes the semaphore to be released more than it's acquired will go
undetected.


\subsection{Event Objects \label{event-objects}}

This is one of the simplest mechanisms for communication between
threads: one thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with
the \method{set()} method and reset to false with the \method{clear()}
method.  The \method{wait()} method blocks until the flag is true.


\begin{classdesc}{Event}{}
The internal flag is initially false.
\end{classdesc}

\begin{methoddesc}{isSet}{}
Return true if and only if the internal flag is true.
\end{methoddesc}

\begin{methoddesc}{set}{}
Set the internal flag to true.
All threads waiting for it to become true are awakened.
Threads that call \method{wait()} once the flag is true will not block
at all.
\end{methoddesc}

\begin{methoddesc}{clear}{}
Reset the internal flag to false.
Subsequently, threads calling \method{wait()} will block until
\method{set()} is called to set the internal flag to true again.
\end{methoddesc}

\begin{methoddesc}{wait}{\optional{timeout}}
Block until the internal flag is true.
If the internal flag is true on entry, return immediately.  Otherwise,
block until another thread calls \method{set()} to set the flag to
true, or until the optional timeout occurs.

When the timeout argument is present and not \code{None}, it should be a
floating point number specifying a timeout for the operation in
seconds (or fractions thereof).
\end{methoddesc}


\subsection{Thread Objects \label{thread-objects}}

This class represents an activity that is run in a separate thread
of control.  There are two ways to specify the activity: by
passing a callable object to the constructor, or by overriding the
\method{run()} method in a subclass.  No other methods (except for the
constructor) should be overridden in a subclass.  In other words, 
\emph{only}  override the \method{__init__()} and \method{run()}
methods of this class.

Once a thread object is created, its activity must be started by
calling the thread's \method{start()} method.  This invokes the
\method{run()} method in a separate thread of control.

Once the thread's activity is started, the thread is considered
'alive'. It stops being alive when its \method{run()} method terminates
-- either normally, or by raising an unhandled exception.  The
\method{isAlive()} method tests whether the thread is alive.

Other threads can call a thread's \method{join()} method.  This blocks
the calling thread until the thread whose \method{join()} method is
called is terminated.

A thread has a name.  The name can be passed to the constructor,
set with the \method{setName()} method, and retrieved with the
\method{getName()} method.

A thread can be flagged as a ``daemon thread''.  The significance
of this flag is that the entire Python program exits when only
daemon threads are left.  The initial value is inherited from the
creating thread.  The flag can be set with the \method{setDaemon()}
method and retrieved with the \method{isDaemon()} method.

There is a ``main thread'' object; this corresponds to the
initial thread of control in the Python program.  It is not a
daemon thread.

There is the possibility that ``dummy thread objects'' are created.
These are thread objects corresponding to ``alien threads'', which
are threads of control started outside the threading module, such as
directly from C code.  Dummy thread objects have limited
functionality; they are always considered alive and daemonic, and
cannot be \method{join()}ed.  They are never deleted, since it is
impossible to detect the termination of alien threads.


\begin{classdesc}{Thread}{group=None, target=None, name=None,
                          args=(), kwargs=\{\}}
This constructor should always be called with keyword
arguments.  Arguments are:

\var{group} should be \code{None}; reserved for future extension when
a \class{ThreadGroup} class is implemented.

\var{target} is the callable object to be invoked by the
\method{run()} method.  Defaults to \code{None}, meaning nothing is
called.

\var{name} is the thread name.  By default, a unique name is
constructed of the form ``Thread-\var{N}'' where \var{N} is a small
decimal number.

\var{args} is the argument tuple for the target invocation.  Defaults
to \code{()}.

\var{kwargs} is a dictionary of keyword arguments for the target
invocation.  Defaults to \code{\{\}}.

If the subclass overrides the constructor, it must make sure
to invoke the base class constructor (\code{Thread.__init__()})
before doing anything else to the thread.
\end{classdesc}

\begin{methoddesc}{start}{}
Start the thread's activity.

It must be called at most once per thread object.  It arranges for the
object's \method{run()} method to be invoked in a separate thread of
control.

This method will raise a \exception{RuntimeException} if called more
than once on the same thread object.
\end{methoddesc}

\begin{methoddesc}{run}{}
Method representing the thread's activity.

You may override this method in a subclass.  The standard
\method{run()} method invokes the callable object passed to the
object's constructor as the \var{target} argument, if any, with
sequential and keyword arguments taken from the \var{args} and
\var{kwargs} arguments, respectively.
\end{methoddesc}

\begin{methoddesc}{join}{\optional{timeout}}
Wait until the thread terminates.
This blocks the calling thread until the thread whose \method{join()}
method is called terminates -- either normally or through an
unhandled exception -- or until the optional timeout occurs.

When the \var{timeout} argument is present and not \code{None}, it
should be a floating point number specifying a timeout for the
operation in seconds (or fractions thereof). As \method{join()} always 
returns \code{None}, you must call \method{isAlive()} to decide whether 
a timeout happened.

When the \var{timeout} argument is not present or \code{None}, the
operation will block until the thread terminates.

A thread can be \method{join()}ed many times.

\method{join()} may throw a \exception{RuntimeError}, if an attempt is
made to join the current thread as that would cause a deadlock. It is
also an error to \method{join()} a thread before it has been started
and attempts to do so raises same exception.
\end{methoddesc}

\begin{methoddesc}{getName}{}
Return the thread's name.
\end{methoddesc}

\begin{methoddesc}{setName}{name}
Set the thread's name.

The name is a string used for identification purposes only.
It has no semantics.  Multiple threads may be given the same
name.  The initial name is set by the constructor.
\end{methoddesc}

\begin{methoddesc}{isAlive}{}
Return whether the thread is alive.

Roughly, a thread is alive from the moment the \method{start()} method
returns until its \method{run()} method terminates. The module
function \function{enumerate()} returns a list of all alive threads.
\end{methoddesc}

\begin{methoddesc}{isDaemon}{}
Return the thread's daemon flag.
\end{methoddesc}

\begin{methoddesc}{setDaemon}{daemonic}
Set the thread's daemon flag to the Boolean value \var{daemonic}.
This must be called before \method{start()} is called, otherwise
\exception{RuntimeError} is raised.

The initial value is inherited from the creating thread.

The entire Python program exits when no alive non-daemon threads are
left.
\end{methoddesc}


\subsection{Timer Objects \label{timer-objects}}

This class represents an action that should be run only after a
certain amount of time has passed --- a timer.  \class{Timer} is a
subclass of \class{Thread} and as such also functions as an example of
creating custom threads.

Timers are started, as with threads, by calling their \method{start()}
method.  The timer can be stopped (before its action has begun) by
calling the \method{cancel()} method.  The interval the timer will
wait before executing its action may not be exactly the same as the
interval specified by the user.

For example:
\begin{verbatim}
def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
\end{verbatim}

\begin{classdesc}{Timer}{interval, function, args=[], kwargs=\{\}}
Create a timer that will run \var{function} with arguments \var{args} and 
keyword arguments \var{kwargs}, after \var{interval} seconds have passed.
\end{classdesc}

\begin{methoddesc}{cancel}{}
Stop the timer, and cancel the execution of the timer's action.  This
will only work if the timer is still in its waiting stage.
\end{methoddesc}

\subsection{Using locks, conditions, and semaphores in the \keyword{with}
statement \label{with-locks}}

All of the objects provided by this module that have \method{acquire()} and
\method{release()} methods can be used as context managers for a \keyword{with}
statement.  The \method{acquire()} method will be called when the block is
entered, and \method{release()} will be called when the block is exited.

Currently, \class{Lock}, \class{RLock}, \class{Condition}, \class{Semaphore},
and \class{BoundedSemaphore} objects may be used as \keyword{with}
statement context managers.  For example:

\begin{verbatim}
from __future__ import with_statement
import threading

some_rlock = threading.RLock()

with some_rlock:
    print "some_rlock is locked while this executes"
\end{verbatim}

href='#n2352'>2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341
/* Socket module */

/*

This module provides an interface to Berkeley socket IPC.

Limitations:

- Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
  portable manner, though AF_PACKET, AF_NETLINK and AF_TIPC are supported
  under Linux.
- No read/write operations (use sendall/recv or makefile instead).
- Additional restrictions apply on some non-Unix platforms (compensated
  for by socket.py).

Module interface:

- socket.error: exception raised for socket specific errors
- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
	a subclass of socket.error
- socket.herror: exception raised for gethostby* errors,
	a subclass of socket.error
- socket.fromfd(fd, family, type[, proto]) --> new socket object (created
        from an existing file descriptor)
- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
- socket.getprotobyname(protocolname) --> protocol number
- socket.getservbyname(servicename[, protocolname]) --> port number
- socket.getservbyport(portnumber[, protocolname]) --> service name
- socket.socket([family[, type [, proto]]]) --> new socket object
- socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
- socket.ntohs(16 bit value) --> new int object
- socket.ntohl(32 bit value) --> new int object
- socket.htons(16 bit value) --> new int object
- socket.htonl(32 bit value) --> new int object
- socket.getaddrinfo(host, port [, family, socktype, proto, flags])
	--> List of (family, socktype, proto, canonname, sockaddr)
- socket.getnameinfo(sockaddr, flags) --> (host, port)
- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
- socket.has_ipv6: boolean value indicating if IPv6 is supported
- socket.inet_aton(IP address) -> 32-bit packed IP representation
- socket.inet_ntoa(packed IP) -> IP address string
- socket.getdefaulttimeout() -> None | float
- socket.setdefaulttimeout(None | float)
- an Internet socket address is a pair (hostname, port)
  where hostname can be anything recognized by gethostbyname()
  (including the dd.dd.dd.dd notation) and port is in host byte order
- where a hostname is returned, the dd.dd.dd.dd notation is used
- a UNIX domain socket address is a string specifying the pathname
- an AF_PACKET socket address is a tuple containing a string
  specifying the ethernet interface and an integer specifying
  the Ethernet protocol number to be received. For example:
  ("eth0",0x1234).  Optional 3rd,4th,5th elements in the tuple
  specify packet-type and ha-type/addr.
- an AF_TIPC socket address is expressed as
 (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
	TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
  and scope can be one of:
	TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
  The meaning of v1, v2 and v3 depends on the value of addr_type:
	if addr_type is TIPC_ADDR_NAME:
		v1 is the server type
		v2 is the port identifier
		v3 is ignored
	if addr_type is TIPC_ADDR_NAMESEQ:
		v1 is the server type
		v2 is the lower port number
		v3 is the upper port number
	if addr_type is TIPC_ADDR_ID:
		v1 is the node
		v2 is the ref
		v3 is ignored


Local naming conventions:

- names starting with sock_ are socket object methods
- names starting with socket_ are module-level functions
- names starting with PySocket are exported through socketmodule.h

*/

#ifdef __APPLE__
  /*
   * inet_aton is not available on OSX 10.3, yet we want to use a binary
   * that was build on 10.4 or later to work on that release, weak linking
   * comes to the rescue.
   */
# pragma weak inet_aton
#endif

#include "Python.h"
#include "structmember.h"

#undef MAX
#define MAX(x, y) ((x) < (y) ? (y) : (x))

/* Socket object documentation */
PyDoc_STRVAR(sock_doc,
"socket([family[, type[, proto]]]) -> socket object\n\
\n\
Open a socket of the given type.  The family argument specifies the\n\
address family; it defaults to AF_INET.  The type argument specifies\n\
whether this is a stream (SOCK_STREAM, this is the default)\n\
or datagram (SOCK_DGRAM) socket.  The protocol argument defaults to 0,\n\
specifying the default protocol.  Keyword arguments are accepted.\n\
\n\
A socket object represents one endpoint of a network connection.\n\
\n\
Methods of socket objects (keyword arguments not allowed):\n\
\n\
accept() -- accept a connection, returning new socket and client address\n\
bind(addr) -- bind the socket to a local address\n\
close() -- close the socket\n\
connect(addr) -- connect the socket to a remote address\n\
connect_ex(addr) -- connect, return an error code instead of an exception\n\
dup() -- return a new socket object identical to the current one [*]\n\
fileno() -- return underlying file descriptor\n\
getpeername() -- return remote address [*]\n\
getsockname() -- return local address\n\
getsockopt(level, optname[, buflen]) -- get socket options\n\
gettimeout() -- return timeout or None\n\
listen(n) -- start listening for incoming connections\n\
makefile([mode, [bufsize]]) -- return a file object for the socket [*]\n\
recv(buflen[, flags]) -- receive data\n\
recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
recvfrom_into(buffer[, nbytes, [, flags])\n\
  -- receive data and sender\'s address (into a buffer)\n\
sendall(data[, flags]) -- send all data\n\
send(data[, flags]) -- send data, may not send all of it\n\
sendto(data[, flags], addr) -- send data to a given address\n\
setblocking(0 | 1) -- set or clear the blocking I/O flag\n\
setsockopt(level, optname, value) -- set socket options\n\
settimeout(None | float) -- set or clear the timeout\n\
shutdown(how) -- shut down traffic in one or both directions\n\
\n\
 [*] not available on all platforms!");

/* XXX This is a terrible mess of platform-dependent preprocessor hacks.
   I hope some day someone can clean this up please... */

/* Hacks for gethostbyname_r().  On some non-Linux platforms, the configure
   script doesn't get this right, so we hardcode some platform checks below.
   On the other hand, not all Linux versions agree, so there the settings
   computed by the configure script are needed! */

#ifndef linux
# undef HAVE_GETHOSTBYNAME_R_3_ARG
# undef HAVE_GETHOSTBYNAME_R_5_ARG
# undef HAVE_GETHOSTBYNAME_R_6_ARG
#endif

#ifndef WITH_THREAD
# undef HAVE_GETHOSTBYNAME_R
#endif

#ifdef HAVE_GETHOSTBYNAME_R
# if defined(_AIX) || defined(__osf__)
#  define HAVE_GETHOSTBYNAME_R_3_ARG
# elif defined(__sun) || defined(__sgi)
#  define HAVE_GETHOSTBYNAME_R_5_ARG
# elif defined(linux)
/* Rely on the configure script */
# else
#  undef HAVE_GETHOSTBYNAME_R
# endif
#endif

#if !defined(HAVE_GETHOSTBYNAME_R) && defined(WITH_THREAD) && \
    !defined(MS_WINDOWS)
# define USE_GETHOSTBYNAME_LOCK
#endif

/* To use __FreeBSD_version */
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
/* On systems on which getaddrinfo() is believed to not be thread-safe,
   (this includes the getaddrinfo emulation) protect access with a lock. */
#if defined(WITH_THREAD) && (defined(__APPLE__) || \
    (defined(__FreeBSD__) && __FreeBSD_version+0 < 503000) || \
    defined(__OpenBSD__) || defined(__NetBSD__) || \
    defined(__VMS) || !defined(HAVE_GETADDRINFO))
#define USE_GETADDRINFO_LOCK
#endif

#ifdef USE_GETADDRINFO_LOCK
#define ACQUIRE_GETADDRINFO_LOCK PyThread_acquire_lock(netdb_lock, 1);
#define RELEASE_GETADDRINFO_LOCK PyThread_release_lock(netdb_lock);
#else
#define ACQUIRE_GETADDRINFO_LOCK
#define RELEASE_GETADDRINFO_LOCK
#endif

#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
# include "pythread.h"
#endif

#if defined(PYCC_VACPP)
# include <types.h>
# include <io.h>
# include <sys/ioctl.h>
# include <utils.h>
# include <ctype.h>
#endif

#if defined(__VMS)
#  include <ioctl.h>
#endif

#if defined(PYOS_OS2)
# define  INCL_DOS
# define  INCL_DOSERRORS
# define  INCL_NOPMAPI
# include <os2.h>
#endif

#if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
/* make sure that the reentrant (gethostbyaddr_r etc)
   functions are declared correctly if compiling with
   MIPSPro 7.x in ANSI C mode (default) */

/* XXX Using _SGIAPI is the wrong thing,
   but I don't know what the right thing is. */
#undef _SGIAPI /* to avoid warning */
#define _SGIAPI 1

#undef _XOPEN_SOURCE
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#ifdef _SS_ALIGNSIZE
#define HAVE_GETADDRINFO 1
#define HAVE_GETNAMEINFO 1
#endif

#define HAVE_INET_PTON
#include <netdb.h>
#endif

/* Irix 6.5 fails to define this variable at all. This is needed
   for both GCC and SGI's compiler. I'd say that the SGI headers
   are just busted. Same thing for Solaris. */
#if (defined(__sgi) || defined(sun)) && !defined(INET_ADDRSTRLEN)
#define INET_ADDRSTRLEN 16
#endif

/* Generic includes */
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

/* Generic socket object definitions and includes */
#define PySocket_BUILDING_SOCKET
#include "socketmodule.h"

/* Addressing includes */

#ifndef MS_WINDOWS

/* Non-MS WINDOWS includes */
# include <netdb.h>

/* Headers needed for inet_ntoa() and inet_addr() */
# ifdef __BEOS__
#  include <net/netdb.h>
# elif defined(PYOS_OS2) && defined(PYCC_VACPP)
#  include <netdb.h>
typedef size_t socklen_t;
# else
#   include <arpa/inet.h>
# endif

# ifndef RISCOS
#  include <fcntl.h>
# else
#  include <sys/ioctl.h>
#  include <socklib.h>
#  define NO_DUP
int h_errno; /* not used */
#  define INET_ADDRSTRLEN 16
# endif

#else

/* MS_WINDOWS includes */
# ifdef HAVE_FCNTL_H
#  include <fcntl.h>
# endif

#endif

#include <stddef.h>

#ifndef offsetof
# define offsetof(type, member)	((size_t)(&((type *)0)->member))
#endif

#ifndef O_NONBLOCK
# define O_NONBLOCK O_NDELAY
#endif

/* include Python's addrinfo.h unless it causes trouble */
#if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
  /* Do not include addinfo.h on some newer IRIX versions.
   * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
   * for example, but not by 6.5.10.
   */
#elif defined(_MSC_VER) && _MSC_VER>1201
  /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
   * EAI_* constants are defined in (the already included) ws2tcpip.h.
   */
#else
#  include "addrinfo.h"
#endif

#ifndef HAVE_INET_PTON
#if !defined(NTDDI_VERSION) || (NTDDI_VERSION < NTDDI_LONGHORN)
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
#endif
#endif

#ifdef __APPLE__
/* On OS X, getaddrinfo returns no error indication of lookup
   failure, so we must use the emulation instead of the libinfo
   implementation. Unfortunately, performing an autoconf test
   for this bug would require DNS access for the machine performing
   the configuration, which is not acceptable. Therefore, we
   determine the bug just by checking for __APPLE__. If this bug
   gets ever fixed, perhaps checking for sys/version.h would be
   appropriate, which is 10/0 on the system with the bug. */
#ifndef HAVE_GETNAMEINFO
/* This bug seems to be fixed in Jaguar. Ths easiest way I could
   Find to check for Jaguar is that it has getnameinfo(), which
   older releases don't have */
#undef HAVE_GETADDRINFO
#endif

#ifdef HAVE_INET_ATON
#define USE_INET_ATON_WEAKLINK
#endif

#endif

/* I know this is a bad practice, but it is the easiest... */
#if !defined(HAVE_GETADDRINFO)
/* avoid clashes with the C library definition of the symbol. */
#define getaddrinfo fake_getaddrinfo
#define gai_strerror fake_gai_strerror
#define freeaddrinfo fake_freeaddrinfo
#include "getaddrinfo.c"
#endif
#if !defined(HAVE_GETNAMEINFO)
#define getnameinfo fake_getnameinfo
#include "getnameinfo.c"
#endif

#if defined(MS_WINDOWS) || defined(__BEOS__)
/* BeOS suffers from the same socket dichotomy as Win32... - [cjh] */
/* seem to be a few differences in the API */
#define SOCKETCLOSE closesocket
#define NO_DUP /* Actually it exists on NT 3.5, but what the heck... */
#endif

#ifdef MS_WIN32
#define EAFNOSUPPORT WSAEAFNOSUPPORT
#define snprintf _snprintf
#endif

#if defined(PYOS_OS2) && !defined(PYCC_GCC)
#define SOCKETCLOSE soclose
#define NO_DUP /* Sockets are Not Actual File Handles under OS/2 */
#endif

#ifndef SOCKETCLOSE
#define SOCKETCLOSE close
#endif

#if defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H) &&  !defined(__NetBSD__)
#define USE_BLUETOOTH 1
#if defined(__FreeBSD__)
#define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
#define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
#define BTPROTO_HCI BLUETOOTH_PROTO_HCI
#define SOL_HCI SOL_HCI_RAW
#define HCI_FILTER SO_HCI_RAW_FILTER
#define sockaddr_l2 sockaddr_l2cap
#define sockaddr_rc sockaddr_rfcomm
#define hci_dev hci_node
#define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#elif defined(__NetBSD__)
#define sockaddr_l2 sockaddr_bt
#define sockaddr_rc sockaddr_bt
#define sockaddr_hci sockaddr_bt
#define sockaddr_sco sockaddr_bt
#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
#else
#define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
#endif
#endif

#ifdef __VMS
/* TCP/IP Services for VMS uses a maximum send/recv buffer length */
#define SEGMENT_SIZE (32 * 1024 -1)
#endif

#define	SAS2SA(x)	((struct sockaddr *)(x))

/*
 * Constants for getnameinfo()
 */
#if !defined(NI_MAXHOST)
#define NI_MAXHOST 1025
#endif
#if !defined(NI_MAXSERV)
#define NI_MAXSERV 32
#endif

/* XXX There's a problem here: *static* functions are not supposed to have
   a Py prefix (or use CapitalizedWords).  Later... */

/* Global variable holding the exception type for errors detected
   by this module (but not argument type or memory errors, etc.). */
static PyObject *socket_error;
static PyObject *socket_herror;
static PyObject *socket_gaierror;
static PyObject *socket_timeout;

#ifdef RISCOS
/* Global variable which is !=0 if Python is running in a RISC OS taskwindow */
static int taskwindow;
#endif

/* A forward reference to the socket type object.
   The sock_type variable contains pointers to various functions,
   some of which call new_sockobject(), which uses sock_type, so
   there has to be a circular reference. */
static PyTypeObject sock_type;

#if defined(HAVE_POLL_H)
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
#endif

#ifdef Py_SOCKET_FD_CAN_BE_GE_FD_SETSIZE
/* Platform can select file descriptors beyond FD_SETSIZE */
#define IS_SELECTABLE(s) 1
#elif defined(HAVE_POLL)
/* Instead of select(), we'll use poll() since poll() works on any fd. */
#define IS_SELECTABLE(s) 1
/* Can we call select() with this socket without a buffer overrun? */
#else
/* POSIX says selecting file descriptors beyond FD_SETSIZE
   has undefined behaviour.  If there's no timeout left, we don't have to
   call select, so it's a safe, little white lie. */
#define IS_SELECTABLE(s) ((s)->sock_fd < FD_SETSIZE || s->sock_timeout <= 0.0)
#endif

static PyObject*
select_error(void)
{
	PyErr_SetString(socket_error, "unable to select on socket");
	return NULL;
}

/* Convenience function to raise an error according to errno
   and return a NULL pointer from a function. */

static PyObject *
set_error(void)
{
#ifdef MS_WINDOWS
	int err_no = WSAGetLastError();
	/* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
	   recognizes the error codes used by both GetLastError() and
	   WSAGetLastError */
	if (err_no)
		return PyErr_SetExcFromWindowsErr(socket_error, err_no);
#endif

#if defined(PYOS_OS2) && !defined(PYCC_GCC)
	if (sock_errno() != NO_ERROR) {
		APIRET rc;
		ULONG  msglen;
		char outbuf[100];
		int myerrorcode = sock_errno();

		/* Retrieve socket-related error message from MPTN.MSG file */
		rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
				   myerrorcode - SOCBASEERR + 26,
				   "mptn.msg",
				   &msglen);
		if (rc == NO_ERROR) {
			PyObject *v;

			/* OS/2 doesn't guarantee a terminator */
			outbuf[msglen] = '\0';
			if (strlen(outbuf) > 0) {
				/* If non-empty msg, trim CRLF */
				char *lastc = &outbuf[ strlen(outbuf)-1 ];
				while (lastc > outbuf &&
				       isspace(Py_CHARMASK(*lastc))) {
					/* Trim trailing whitespace (CRLF) */
					*lastc-- = '\0';
				}
			}
			v = Py_BuildValue("(is)", myerrorcode, outbuf);
			if (v != NULL) {
				PyErr_SetObject(socket_error, v);
				Py_DECREF(v);
			}
			return NULL;
		}
	}
#endif

#if defined(RISCOS)
	if (_inet_error.errnum != NULL) {
		PyObject *v;
		v = Py_BuildValue("(is)", errno, _inet_err());
		if (v != NULL) {
			PyErr_SetObject(socket_error, v);
			Py_DECREF(v);
		}
		return NULL;
	}
#endif

	return PyErr_SetFromErrno(socket_error);
}


static PyObject *
set_herror(int h_error)
{
	PyObject *v;

#ifdef HAVE_HSTRERROR
	v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
#else
	v = Py_BuildValue("(is)", h_error, "host not found");
#endif
	if (v != NULL) {
		PyErr_SetObject(socket_herror, v);
		Py_DECREF(v);
	}

	return NULL;
}


static PyObject *
set_gaierror(int error)
{
	PyObject *v;

#ifdef EAI_SYSTEM
	/* EAI_SYSTEM is not available on Windows XP. */
	if (error == EAI_SYSTEM)
		return set_error();
#endif

#ifdef HAVE_GAI_STRERROR
	v = Py_BuildValue("(is)", error, gai_strerror(error));
#else
	v = Py_BuildValue("(is)", error, "getaddrinfo failed");
#endif
	if (v != NULL) {
		PyErr_SetObject(socket_gaierror, v);
		Py_DECREF(v);
	}

	return NULL;
}

#ifdef __VMS
/* Function to send in segments */
static int
sendsegmented(int sock_fd, char *buf, int len, int flags)
{
	int n = 0;
	int remaining = len;

	while (remaining > 0) {
		unsigned int segment;

		segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
		n = send(sock_fd, buf, segment, flags);
		if (n < 0) {
			return n;
		}
		remaining -= segment;
		buf += segment;
	} /* end while */

	return len;
}
#endif

/* Function to perform the setting of socket blocking mode
   internally. block = (1 | 0). */
static int
internal_setblocking(PySocketSockObject *s, int block)
{
#ifndef RISCOS
#ifndef MS_WINDOWS
	int delay_flag;
#endif
#endif

	Py_BEGIN_ALLOW_THREADS
#ifdef __BEOS__
	block = !block;
	setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
		   (void *)(&block), sizeof(int));
#else
#ifndef RISCOS
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
	block = !block;
	ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
#elif defined(__VMS)
	block = !block;
	ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
#else  /* !PYOS_OS2 && !__VMS */
	delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
	if (block)
		delay_flag &= (~O_NONBLOCK);
	else
		delay_flag |= O_NONBLOCK;
	fcntl(s->sock_fd, F_SETFL, delay_flag);
#endif /* !PYOS_OS2 */
#else /* MS_WINDOWS */
	block = !block;
	ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* MS_WINDOWS */
#else /* RISCOS */
	block = !block;
	socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* RISCOS */
#endif /* __BEOS__ */
	Py_END_ALLOW_THREADS

	/* Since these don't return anything */
	return 1;
}

/* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
   The argument writing indicates the direction.
   This does not raise an exception; we'll let our caller do that
   after they've reacquired the interpreter lock.
   Returns 1 on timeout, -1 on error, 0 otherwise. */
static int
internal_select(PySocketSockObject *s, int writing)
{
	int n;

	/* Nothing to do unless we're in timeout mode (not non-blocking) */
	if (s->sock_timeout <= 0.0)
		return 0;

	/* Guard against closed socket */
	if (s->sock_fd < 0)
		return 0;

	/* Prefer poll, if available, since you can poll() any fd
	 * which can't be done with select(). */
#ifdef HAVE_POLL
	{
		struct pollfd pollfd;
		int timeout;

		pollfd.fd = s->sock_fd;
		pollfd.events = writing ? POLLOUT : POLLIN;

		/* s->sock_timeout is in seconds, timeout in ms */
		timeout = (int)(s->sock_timeout * 1000 + 0.5); 
		n = poll(&pollfd, 1, timeout);
	}
#else
	{
		/* Construct the arguments to select */
		fd_set fds;
		struct timeval tv;
		tv.tv_sec = (int)s->sock_timeout;
		tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
		FD_ZERO(&fds);
		FD_SET(s->sock_fd, &fds);

		/* See if the socket is ready */
		if (writing)
			n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
		else
			n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
	}
#endif
	
	if (n < 0)
		return -1;
	if (n == 0)
		return 1;
	return 0;
}

/* Initialize a new socket object. */

static double defaulttimeout = -1.0; /* Default timeout for new sockets */

PyMODINIT_FUNC
init_sockobject(PySocketSockObject *s,
		SOCKET_T fd, int family, int type, int proto)
{
#ifdef RISCOS
	int block = 1;
#endif
	s->sock_fd = fd;
	s->sock_family = family;
	s->sock_type = type;
	s->sock_proto = proto;
	s->sock_timeout = defaulttimeout;

	s->errorhandler = &set_error;

	if (defaulttimeout >= 0.0)
		internal_setblocking(s, 0);

#ifdef RISCOS
	if (taskwindow)
		socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
#endif
}


/* Create a new socket object.
   This just creates the object and initializes it.
   If the creation fails, return NULL and set an exception (implicit
   in NEWOBJ()). */

static PySocketSockObject *
new_sockobject(SOCKET_T fd, int family, int type, int proto)
{
	PySocketSockObject *s;
	s = (PySocketSockObject *)
		PyType_GenericNew(&sock_type, NULL, NULL);
	if (s != NULL)
		init_sockobject(s, fd, family, type, proto);
	return s;
}


/* Lock to allow python interpreter to continue, but only allow one
   thread to be in gethostbyname or getaddrinfo */
#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
PyThread_type_lock netdb_lock;
#endif


/* Convert a string specifying a host name or one of a few symbolic
   names to a numeric IP address.  This usually calls gethostbyname()
   to do the work; the names "" and "<broadcast>" are special.
   Return the length (IPv4 should be 4 bytes), or negative if
   an error occurred; then an exception is raised. */

static int
setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
{
	struct addrinfo hints, *res;
	int error;
	int d1, d2, d3, d4;
	char ch;

	memset((void *) addr_ret, '\0', sizeof(*addr_ret));
	if (name[0] == '\0') {
		int siz;
		memset(&hints, 0, sizeof(hints));
		hints.ai_family = af;
		hints.ai_socktype = SOCK_DGRAM;	/*dummy*/
		hints.ai_flags = AI_PASSIVE;
		Py_BEGIN_ALLOW_THREADS
		ACQUIRE_GETADDRINFO_LOCK
		error = getaddrinfo(NULL, "0", &hints, &res);
		Py_END_ALLOW_THREADS
		/* We assume that those thread-unsafe getaddrinfo() versions
		   *are* safe regarding their return value, ie. that a
		   subsequent call to getaddrinfo() does not destroy the
		   outcome of the first call. */
		RELEASE_GETADDRINFO_LOCK
		if (error) {
			set_gaierror(error);
			return -1;
		}
		switch (res->ai_family) {
		case AF_INET:
			siz = 4;
			break;
#ifdef ENABLE_IPV6
		case AF_INET6:
			siz = 16;
			break;
#endif
		default:
			freeaddrinfo(res);
			PyErr_SetString(socket_error,
				"unsupported address family");
			return -1;
		}
		if (res->ai_next) {
			freeaddrinfo(res);
			PyErr_SetString(socket_error,
				"wildcard resolved to multiple address");
			return -1;
		}
		if (res->ai_addrlen < addr_ret_size)
			addr_ret_size = res->ai_addrlen;
		memcpy(addr_ret, res->ai_addr, addr_ret_size);
		freeaddrinfo(res);
		return siz;
	}
	if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
		struct sockaddr_in *sin;
		if (af != AF_INET && af != AF_UNSPEC) {
			PyErr_SetString(socket_error,
				"address family mismatched");
			return -1;
		}
		sin = (struct sockaddr_in *)addr_ret;
		memset((void *) sin, '\0', sizeof(*sin));
		sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
		sin->sin_len = sizeof(*sin);
#endif
		sin->sin_addr.s_addr = INADDR_BROADCAST;
		return sizeof(sin->sin_addr);
	}
	if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
	    0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
	    0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
		struct sockaddr_in *sin;
		sin = (struct sockaddr_in *)addr_ret;
		sin->sin_addr.s_addr = htonl(
			((long) d1 << 24) | ((long) d2 << 16) |
			((long) d3 << 8) | ((long) d4 << 0));
		sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
		sin->sin_len = sizeof(*sin);
#endif
		return 4;
	}
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = af;
	Py_BEGIN_ALLOW_THREADS
	ACQUIRE_GETADDRINFO_LOCK
	error = getaddrinfo(name, NULL, &hints, &res);
#if defined(__digital__) && defined(__unix__)
	if (error == EAI_NONAME && af == AF_UNSPEC) {
		/* On Tru64 V5.1, numeric-to-addr conversion fails
		   if no address family is given. Assume IPv4 for now.*/
		hints.ai_family = AF_INET;
		error = getaddrinfo(name, NULL, &hints, &res);
	}
#endif
	Py_END_ALLOW_THREADS
	RELEASE_GETADDRINFO_LOCK  /* see comment in setipaddr() */
	if (error) {
		set_gaierror(error);
		return -1;
	}
	if (res->ai_addrlen < addr_ret_size)
		addr_ret_size = res->ai_addrlen;
	memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
	freeaddrinfo(res);
	switch (addr_ret->sa_family) {
	case AF_INET:
		return 4;
#ifdef ENABLE_IPV6
	case AF_INET6:
		return 16;
#endif
	default:
		PyErr_SetString(socket_error, "unknown address family");
		return -1;
	}
}


/* Create a string object representing an IP address.
   This is always a string of the form 'dd.dd.dd.dd' (with variable
   size numbers). */

static PyObject *
makeipaddr(struct sockaddr *addr, int addrlen)
{
	char buf[NI_MAXHOST];
	int error;

	error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
		NI_NUMERICHOST);
	if (error) {
		set_gaierror(error);
		return NULL;
	}
	return PyString_FromString(buf);
}


#ifdef USE_BLUETOOTH
/* Convert a string representation of a Bluetooth address into a numeric
   address.  Returns the length (6), or raises an exception and returns -1 if
   an error occurred. */

static int
setbdaddr(char *name, bdaddr_t *bdaddr)
{
	unsigned int b0, b1, b2, b3, b4, b5;
	char ch;
	int n;

	n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
		   &b5, &b4, &b3, &b2, &b1, &b0, &ch);
	if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
		bdaddr->b[0] = b0;
		bdaddr->b[1] = b1;
		bdaddr->b[2] = b2;
		bdaddr->b[3] = b3;
		bdaddr->b[4] = b4;
		bdaddr->b[5] = b5;
		return 6;
	} else {
		PyErr_SetString(socket_error, "bad bluetooth address");
		return -1;
	}
}

/* Create a string representation of the Bluetooth address.  This is always a
   string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
   value (zero padded if necessary). */

static PyObject *
makebdaddr(bdaddr_t *bdaddr)
{
	char buf[(6 * 2) + 5 + 1];

	sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
		bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
		bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
	return PyString_FromString(buf);
}
#endif


/* Create an object representing the given socket address,
   suitable for passing it back to bind(), connect() etc.
   The family field of the sockaddr structure is inspected
   to determine what kind of address it really is. */

/*ARGSUSED*/
static PyObject *
makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
{
	if (addrlen == 0) {
		/* No address -- may be recvfrom() from known socket */
		Py_INCREF(Py_None);
		return Py_None;
	}

#ifdef __BEOS__
	/* XXX: BeOS version of accept() doesn't set family correctly */
	addr->sa_family = AF_INET;
#endif

	switch (addr->sa_family) {

	case AF_INET:
	{
		struct sockaddr_in *a;
		PyObject *addrobj = makeipaddr(addr, sizeof(*a));
		PyObject *ret = NULL;
		if (addrobj) {
			a = (struct sockaddr_in *)addr;
			ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
			Py_DECREF(addrobj);
		}
		return ret;
	}

#if defined(AF_UNIX)
	case AF_UNIX:
	{
		struct sockaddr_un *a = (struct sockaddr_un *) addr;
#ifdef linux
		if (a->sun_path[0] == 0) {  /* Linux abstract namespace */
			addrlen -= offsetof(struct sockaddr_un, sun_path);
			return PyString_FromStringAndSize(a->sun_path,
							  addrlen);
		}
		else
#endif /* linux */
		{
			/* regular NULL-terminated string */
			return PyString_FromString(a->sun_path);
		}
	}
#endif /* AF_UNIX */

#if defined(AF_NETLINK)
       case AF_NETLINK:
       {
               struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
               return Py_BuildValue("II", a->nl_pid, a->nl_groups);
       }
#endif /* AF_NETLINK */

#ifdef ENABLE_IPV6
	case AF_INET6:
	{
		struct sockaddr_in6 *a;
		PyObject *addrobj = makeipaddr(addr, sizeof(*a));
		PyObject *ret = NULL;
		if (addrobj) {
			a = (struct sockaddr_in6 *)addr;
			ret = Py_BuildValue("Oiii",
					    addrobj,
					    ntohs(a->sin6_port),
					    a->sin6_flowinfo,
					    a->sin6_scope_id);
			Py_DECREF(addrobj);
		}
		return ret;
	}
#endif

#ifdef USE_BLUETOOTH
	case AF_BLUETOOTH:
		switch (proto) {

		case BTPROTO_L2CAP:
		{
			struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
			PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
			PyObject *ret = NULL;
			if (addrobj) {
				ret = Py_BuildValue("Oi",
						    addrobj,
						    _BT_L2_MEMB(a, psm));
				Py_DECREF(addrobj);
			}
			return ret;
		}

		case BTPROTO_RFCOMM:
		{
			struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
			PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
			PyObject *ret = NULL;
			if (addrobj) {
				ret = Py_BuildValue("Oi",
						    addrobj,
						    _BT_RC_MEMB(a, channel));
				Py_DECREF(addrobj);
			}
			return ret;
		}

		case BTPROTO_HCI:
		{
			struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
			PyObject *ret = NULL;
			ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
			return ret;
		}

#if !defined(__FreeBSD__)
		case BTPROTO_SCO:
		{
			struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
			return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
		}
#endif

		}
#endif

#ifdef HAVE_NETPACKET_PACKET_H
	case AF_PACKET:
	{
		struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
		char *ifname = "";
		struct ifreq ifr;
		/* need to look up interface name give index */
		if (a->sll_ifindex) {
			ifr.ifr_ifindex = a->sll_ifindex;
			if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
				ifname = ifr.ifr_name;
		}
		return Py_BuildValue("shbhs#",
				     ifname,
				     ntohs(a->sll_protocol),
				     a->sll_pkttype,
				     a->sll_hatype,
				     a->sll_addr,
				     a->sll_halen);
	}
#endif

#ifdef HAVE_LINUX_TIPC_H
	case AF_TIPC:
	{
		struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
		if (a->addrtype == TIPC_ADDR_NAMESEQ) {
			return Py_BuildValue("IIIII",
					a->addrtype,
					a->addr.nameseq.type,
					a->addr.nameseq.lower,
					a->addr.nameseq.upper,
					a->scope);
		} else if (a->addrtype == TIPC_ADDR_NAME) {
			return Py_BuildValue("IIIII",
					a->addrtype,
					a->addr.name.name.type,
					a->addr.name.name.instance,
					a->addr.name.name.instance,
					a->scope);
		} else if (a->addrtype == TIPC_ADDR_ID) {
			return Py_BuildValue("IIIII",
					a->addrtype,
					a->addr.id.node,
					a->addr.id.ref,
					0,
					a->scope);
		} else {
			PyErr_SetString(PyExc_TypeError,
					"Invalid address type");
			return NULL;
		}
	}
#endif

	/* More cases here... */

	default:
		/* If we don't know the address family, don't raise an
		   exception -- return it as a tuple. */
		return Py_BuildValue("is#",
				     addr->sa_family,
				     addr->sa_data,
				     sizeof(addr->sa_data));

	}
}


/* Parse a socket address argument according to the socket object's
   address family.  Return 1 if the address was in the proper format,
   0 of not.  The address is returned through addr_ret, its length
   through len_ret. */

static int
getsockaddrarg(PySocketSockObject *s, PyObject *args,
	       struct sockaddr *addr_ret, int *len_ret)
{
	switch (s->sock_family) {

#if defined(AF_UNIX)
	case AF_UNIX:
	{
		struct sockaddr_un* addr;
		char *path;
		int len;
		if (!PyArg_Parse(args, "t#", &path, &len))
			return 0;

		addr = (struct sockaddr_un*)addr_ret;
#ifdef linux
		if (len > 0 && path[0] == 0) {
			/* Linux abstract namespace extension */
			if (len > sizeof addr->sun_path) {
				PyErr_SetString(socket_error,
						"AF_UNIX path too long");
				return 0;
			}
		}
		else
#endif /* linux */
                {
			/* regular NULL-terminated string */
			if (len >= sizeof addr->sun_path) {
				PyErr_SetString(socket_error,
						"AF_UNIX path too long");
				return 0;
			}
			addr->sun_path[len] = 0;
		}
		addr->sun_family = s->sock_family;
		memcpy(addr->sun_path, path, len);
#if defined(PYOS_OS2)
		*len_ret = sizeof(*addr);
#else
		*len_ret = len + offsetof(struct sockaddr_un, sun_path);
#endif
		return 1;
	}
#endif /* AF_UNIX */

#if defined(AF_NETLINK)
	case AF_NETLINK:
	{
		struct sockaddr_nl* addr;
		int pid, groups;
		addr = (struct sockaddr_nl *)addr_ret;
		if (!PyTuple_Check(args)) {
			PyErr_Format(
				PyExc_TypeError,
				"getsockaddrarg: "
				"AF_NETLINK address must be tuple, not %.500s",
				Py_TYPE(args)->tp_name);
			return 0;
		}
		if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
			return 0;
		addr->nl_family = AF_NETLINK;
		addr->nl_pid = pid;
		addr->nl_groups = groups;
		*len_ret = sizeof(*addr);
		return 1;
	}
#endif

	case AF_INET:
	{
		struct sockaddr_in* addr;
		char *host;
		int port, result;
		if (!PyTuple_Check(args)) {
			PyErr_Format(
				PyExc_TypeError,
				"getsockaddrarg: "
				"AF_INET address must be tuple, not %.500s",
				Py_TYPE(args)->tp_name);
			return 0;
		}
		if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
				      "idna", &host, &port))
			return 0;
		addr=(struct sockaddr_in*)addr_ret;
                result = setipaddr(host, (struct sockaddr *)addr,
                                   sizeof(*addr),  AF_INET);
                PyMem_Free(host);
                if (result < 0)
			return 0;
		if (port < 0 || port > 0xffff) {
			PyErr_SetString(
				PyExc_OverflowError,
				"getsockaddrarg: port must be 0-65535.");
			return 0;
		}
		addr->sin_family = AF_INET;
		addr->sin_port = htons((short)port);
		*len_ret = sizeof *addr;
		return 1;
	}

#ifdef ENABLE_IPV6
	case AF_INET6:
	{
		struct sockaddr_in6* addr;
		char *host;
		int port, flowinfo, scope_id, result;
		flowinfo = scope_id = 0;
		if (!PyTuple_Check(args)) {
			PyErr_Format(
				PyExc_TypeError,
				"getsockaddrarg: "
				"AF_INET6 address must be tuple, not %.500s",
				Py_TYPE(args)->tp_name);
			return 0;
		}
		if (!PyArg_ParseTuple(args, "eti|ii",
				      "idna", &host, &port, &flowinfo,
				      &scope_id)) {
			return 0;
		}
		addr = (struct sockaddr_in6*)addr_ret;
                result = setipaddr(host, (struct sockaddr *)addr,
                                   sizeof(*addr), AF_INET6);
                PyMem_Free(host);
                if (result < 0)
			return 0;
		if (port < 0 || port > 0xffff) {
			PyErr_SetString(
				PyExc_OverflowError,
				"getsockaddrarg: port must be 0-65535.");
			return 0;
		}
		addr->sin6_family = s->sock_family;
		addr->sin6_port = htons((short)port);
		addr->sin6_flowinfo = flowinfo;
		addr->sin6_scope_id = scope_id;
		*len_ret = sizeof *addr;
		return 1;
	}
#endif

#ifdef USE_BLUETOOTH
	case AF_BLUETOOTH:
	{
		switch (s->sock_proto) {
		case BTPROTO_L2CAP:
		{
			struct sockaddr_l2 *addr;
			char *straddr;

			addr = (struct sockaddr_l2 *)addr_ret;
			_BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
			if (!PyArg_ParseTuple(args, "si", &straddr,
					      &_BT_L2_MEMB(addr, psm))) {
				PyErr_SetString(socket_error, "getsockaddrarg: "
						"wrong format");
				return 0;
			}
			if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
				return 0;

			*len_ret = sizeof *addr;
			return 1;
		}
		case BTPROTO_RFCOMM:
		{
			struct sockaddr_rc *addr;
			char *straddr;

			addr = (struct sockaddr_rc *)addr_ret;
			_BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
			if (!PyArg_ParseTuple(args, "si", &straddr,
					      &_BT_RC_MEMB(addr, channel))) {
				PyErr_SetString(socket_error, "getsockaddrarg: "
						"wrong format");
				return 0;
			}
			if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
				return 0;

			*len_ret = sizeof *addr;
			return 1;
		}
		case BTPROTO_HCI:
		{
			struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
			_BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
			if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
				PyErr_SetString(socket_error, "getsockaddrarg: "
						"wrong format");
				return 0;
			}
			*len_ret = sizeof *addr;
			return 1;
		}
#if !defined(__FreeBSD__)
		case BTPROTO_SCO:
		{
			struct sockaddr_sco *addr;
			char *straddr;

			addr = (struct sockaddr_sco *)addr_ret;
			_BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
			straddr = PyString_AsString(args);
			if (straddr == NULL) {
				PyErr_SetString(socket_error, "getsockaddrarg: "
						"wrong format");
				return 0;
			}
			if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
				return 0;

			*len_ret = sizeof *addr;
			return 1;
		}
#endif
		default:
			PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
			return 0;
		}
	}
#endif

#ifdef HAVE_NETPACKET_PACKET_H
	case AF_PACKET:
	{
		struct sockaddr_ll* addr;
		struct ifreq ifr;
		char *interfaceName;
		int protoNumber;
		int hatype = 0;
		int pkttype = 0;
		char *haddr = NULL;
		unsigned int halen = 0;

		if (!PyTuple_Check(args)) {
			PyErr_Format(
				PyExc_TypeError,
				"getsockaddrarg: "
				"AF_PACKET address must be tuple, not %.500s",
				Py_TYPE(args)->tp_name);
			return 0;
		}
		if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
				      &protoNumber, &pkttype, &hatype,
				      &haddr, &halen))
			return 0;
		strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
		ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
		if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
		        s->errorhandler();
			return 0;
		}
		if (halen > 8) {
		  PyErr_SetString(PyExc_ValueError,
				  "Hardware address must be 8 bytes or less");
		  return 0;
		}
		if (protoNumber < 0 || protoNumber > 0xffff) {
			PyErr_SetString(
				PyExc_OverflowError,
				"getsockaddrarg: protoNumber must be 0-65535.");
			return 0;
		}
		addr = (struct sockaddr_ll*)addr_ret;
		addr->sll_family = AF_PACKET;
		addr->sll_protocol = htons((short)protoNumber);
		addr->sll_ifindex = ifr.ifr_ifindex;
		addr->sll_pkttype = pkttype;
		addr->sll_hatype = hatype;
		if (halen != 0) {
		  memcpy(&addr->sll_addr, haddr, halen);
		}
		addr->sll_halen = halen;
		*len_ret = sizeof *addr;
		return 1;
	}
#endif

#ifdef HAVE_LINUX_TIPC_H
	case AF_TIPC:
	{
		unsigned int atype, v1, v2, v3;
		unsigned int scope = TIPC_CLUSTER_SCOPE;
		struct sockaddr_tipc *addr;

		if (!PyTuple_Check(args)) {
			PyErr_Format(
				PyExc_TypeError,
				"getsockaddrarg: "
				"AF_TIPC address must be tuple, not %.500s",
				Py_TYPE(args)->tp_name);
			return 0;
		}

		if (!PyArg_ParseTuple(args,
					"IIII|I;Invalid TIPC address format",
					&atype, &v1, &v2, &v3, &scope))
			return 0;

		addr = (struct sockaddr_tipc *) addr_ret;
		memset(addr, 0, sizeof(struct sockaddr_tipc));

		addr->family = AF_TIPC;
		addr->scope = scope;
		addr->addrtype = atype;

		if (atype == TIPC_ADDR_NAMESEQ) {
			addr->addr.nameseq.type = v1;
			addr->addr.nameseq.lower = v2;
			addr->addr.nameseq.upper = v3;
		} else if (atype == TIPC_ADDR_NAME) {
			addr->addr.name.name.type = v1;
			addr->addr.name.name.instance = v2;
		} else if (atype == TIPC_ADDR_ID) {
			addr->addr.id.node = v1;
			addr->addr.id.ref = v2;
		} else {
			/* Shouldn't happen */
			PyErr_SetString(PyExc_TypeError, "Invalid address type");
			return 0;
		}

		*len_ret = sizeof(*addr);

		return 1;
	}
#endif

	/* More cases here... */

	default:
		PyErr_SetString(socket_error, "getsockaddrarg: bad family");
		return 0;

	}
}


/* Get the address length according to the socket object's address family.
   Return 1 if the family is known, 0 otherwise.  The length is returned
   through len_ret. */

static int
getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
{
	switch (s->sock_family) {

#if defined(AF_UNIX)
	case AF_UNIX:
	{
		*len_ret = sizeof (struct sockaddr_un);
		return 1;
	}
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
       case AF_NETLINK:
       {
               *len_ret = sizeof (struct sockaddr_nl);
               return 1;
       }
#endif

	case AF_INET:
	{
		*len_ret = sizeof (struct sockaddr_in);
		return 1;
	}

#ifdef ENABLE_IPV6
	case AF_INET6:
	{
		*len_ret = sizeof (struct sockaddr_in6);
		return 1;
	}
#endif

#ifdef USE_BLUETOOTH
	case AF_BLUETOOTH:
	{
		switch(s->sock_proto)
		{

		case BTPROTO_L2CAP:
			*len_ret = sizeof (struct sockaddr_l2);
			return 1;
		case BTPROTO_RFCOMM:
			*len_ret = sizeof (struct sockaddr_rc);
			return 1;
		case BTPROTO_HCI:
			*len_ret = sizeof (struct sockaddr_hci);
			return 1;
#if !defined(__FreeBSD__)
		case BTPROTO_SCO:
			*len_ret = sizeof (struct sockaddr_sco);
			return 1;
#endif
		default:
			PyErr_SetString(socket_error, "getsockaddrlen: "
					"unknown BT protocol");
			return 0;

		}
	}
#endif

#ifdef HAVE_NETPACKET_PACKET_H
	case AF_PACKET:
	{
		*len_ret = sizeof (struct sockaddr_ll);
		return 1;
	}
#endif

#ifdef HAVE_LINUX_TIPC_H
	case AF_TIPC:
	{
		*len_ret = sizeof (struct sockaddr_tipc);
		return 1;
	}
#endif

	/* More cases here... */

	default:
		PyErr_SetString(socket_error, "getsockaddrlen: bad family");
		return 0;

	}
}


/* s.accept() method */

static PyObject *
sock_accept(PySocketSockObject *s)
{
	sock_addr_t addrbuf;
	SOCKET_T newfd;
	socklen_t addrlen;
	PyObject *sock = NULL;
	PyObject *addr = NULL;
	PyObject *res = NULL;
	int timeout;

	if (!getsockaddrlen(s, &addrlen))
		return NULL;
	memset(&addrbuf, 0, addrlen);

#ifdef MS_WINDOWS
	newfd = INVALID_SOCKET;
#else
	newfd = -1;
#endif

	if (!IS_SELECTABLE(s))
		return select_error();

	Py_BEGIN_ALLOW_THREADS
	timeout = internal_select(s, 0);
	if (!timeout)
		newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
	Py_END_ALLOW_THREADS

	if (timeout == 1) {
		PyErr_SetString(socket_timeout, "timed out");
		return NULL;
	}

#ifdef MS_WINDOWS
	if (newfd == INVALID_SOCKET)
#else
	if (newfd < 0)
#endif
		return s->errorhandler();

	/* Create the new object with unspecified family,
	   to avoid calls to bind() etc. on it. */
	sock = (PyObject *) new_sockobject(newfd,
					   s->sock_family,
					   s->sock_type,
					   s->sock_proto);

	if (sock == NULL) {
		SOCKETCLOSE(newfd);
		goto finally;
	}
	addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
			    addrlen, s->sock_proto);
	if (addr == NULL)
		goto finally;

	res = PyTuple_Pack(2, sock, addr);

finally:
	Py_XDECREF(sock);
	Py_XDECREF(addr);
	return res;
}

PyDoc_STRVAR(accept_doc,
"accept() -> (socket object, address info)\n\
\n\
Wait for an incoming connection.  Return a new socket representing the\n\
connection, and the address of the client.  For IP sockets, the address\n\
info is a pair (hostaddr, port).");

/* s.setblocking(flag) method.  Argument:
   False -- non-blocking mode; same as settimeout(0)
   True -- blocking mode; same as settimeout(None)
*/

static PyObject *
sock_setblocking(PySocketSockObject *s, PyObject *arg)
{
	int block;

	block = PyInt_AsLong(arg);
	if (block == -1 && PyErr_Occurred())
		return NULL;

	s->sock_timeout = block ? -1.0 : 0.0;
	internal_setblocking(s, block);

	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(setblocking_doc,
"setblocking(flag)\n\
\n\
Set the socket to blocking (flag is true) or non-blocking (false).\n\
setblocking(True) is equivalent to settimeout(None);\n\
setblocking(False) is equivalent to settimeout(0.0).");

/* s.settimeout(timeout) method.  Argument:
   None -- no timeout, blocking mode; same as setblocking(True)
   0.0  -- non-blocking mode; same as setblocking(False)
   > 0  -- timeout mode; operations time out after timeout seconds
   < 0  -- illegal; raises an exception
*/
static PyObject *
sock_settimeout(PySocketSockObject *s, PyObject *arg)
{
	double timeout;

	if (arg == Py_None)
		timeout = -1.0;
	else {
		timeout = PyFloat_AsDouble(arg);
		if (timeout < 0.0) {
			if (!PyErr_Occurred())
				PyErr_SetString(PyExc_ValueError,
						"Timeout value out of range");
			return NULL;
		}
	}

	s->sock_timeout = timeout;
	internal_setblocking(s, timeout < 0.0);

	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(settimeout_doc,
"settimeout(timeout)\n\
\n\
Set a timeout on socket operations.  'timeout' can be a float,\n\
giving in seconds, or None.  Setting a timeout of None disables\n\
the timeout feature and is equivalent to setblocking(1).\n\
Setting a timeout of zero is the same as setblocking(0).");

/* s.gettimeout() method.
   Returns the timeout associated with a socket. */
static PyObject *
sock_gettimeout(PySocketSockObject *s)
{
	if (s->sock_timeout < 0.0) {
		Py_INCREF(Py_None);
		return Py_None;
	}
	else
		return PyFloat_FromDouble(s->sock_timeout);
}

PyDoc_STRVAR(gettimeout_doc,
"gettimeout() -> timeout\n\
\n\
Returns the timeout in floating seconds associated with socket \n\
operations. A timeout of None indicates that timeouts on socket \n\
operations are disabled.");

#ifdef RISCOS
/* s.sleeptaskw(1 | 0) method */

static PyObject *
sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
{
	int block;
	block = PyInt_AsLong(arg);
	if (block == -1 && PyErr_Occurred())
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
	Py_END_ALLOW_THREADS

	Py_INCREF(Py_None);
	return Py_None;
}
PyDoc_STRVAR(sleeptaskw_doc,
"sleeptaskw(flag)\n\
\n\
Allow sleeps in taskwindows.");
#endif


/* s.setsockopt() method.
   With an integer third argument, sets an integer option.
   With a string third argument, sets an option from a buffer;
   use optional built-in module 'struct' to encode the string. */

static PyObject *
sock_setsockopt(PySocketSockObject *s, PyObject *args)
{
	int level;
	int optname;
	int res;
	char *buf;
	int buflen;
	int flag;

	if (PyArg_ParseTuple(args, "iii:setsockopt",
			     &level, &optname, &flag)) {
		buf = (char *) &flag;
		buflen = sizeof flag;
	}
	else {
		PyErr_Clear();
		if (!PyArg_ParseTuple(args, "iis#:setsockopt",
				      &level, &optname, &buf, &buflen))
			return NULL;
	}
	res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
	if (res < 0)
		return s->errorhandler();
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(setsockopt_doc,
"setsockopt(level, option, value)\n\
\n\
Set a socket option.  See the Unix manual for level and option.\n\
The value argument can either be an integer or a string.");


/* s.getsockopt() method.
   With two arguments, retrieves an integer option.
   With a third integer argument, retrieves a string buffer of that size;
   use optional built-in module 'struct' to decode the string. */

static PyObject *
sock_getsockopt(PySocketSockObject *s, PyObject *args)
{
	int level;
	int optname;
	int res;
	PyObject *buf;
	socklen_t buflen = 0;

#ifdef __BEOS__
	/* We have incomplete socket support. */
	PyErr_SetString(socket_error, "getsockopt not supported");
	return NULL;
#else

	if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
			      &level, &optname, &buflen))
		return NULL;

	if (buflen == 0) {
		int flag = 0;
		socklen_t flagsize = sizeof flag;
		res = getsockopt(s->sock_fd, level, optname,
				 (void *)&flag, &flagsize);
		if (res < 0)
			return s->errorhandler();
		return PyInt_FromLong(flag);
	}
#ifdef __VMS
	/* socklen_t is unsigned so no negative test is needed,
	   test buflen == 0 is previously done */
	if (buflen > 1024) {
#else
	if (buflen <= 0 || buflen > 1024) {
#endif
		PyErr_SetString(socket_error,
				"getsockopt buflen out of range");
		return NULL;
	}
	buf = PyString_FromStringAndSize((char *)NULL, buflen);
	if (buf == NULL)
		return NULL;
	res = getsockopt(s->sock_fd, level, optname,
			 (void *)PyString_AS_STRING(buf), &buflen);
	if (res < 0) {
		Py_DECREF(buf);
		return s->errorhandler();
	}
	_PyString_Resize(&buf, buflen);
	return buf;
#endif /* __BEOS__ */
}

PyDoc_STRVAR(getsockopt_doc,
"getsockopt(level, option[, buffersize]) -> value\n\
\n\
Get a socket option.  See the Unix manual for level and option.\n\
If a nonzero buffersize argument is given, the return value is a\n\
string of that length; otherwise it is an integer.");


/* s.bind(sockaddr) method */

static PyObject *
sock_bind(PySocketSockObject *s, PyObject *addro)
{
	sock_addr_t addrbuf;
	int addrlen;
	int res;

	if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return s->errorhandler();
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(bind_doc,
"bind(address)\n\
\n\
Bind the socket to a local address.  For IP sockets, the address is a\n\
pair (host, port); the host must refer to the local host. For raw packet\n\
sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");


/* s.close() method.
   Set the file descriptor to -1 so operations tried subsequently
   will surely fail. */

static PyObject *
sock_close(PySocketSockObject *s)
{
	SOCKET_T fd;

	if ((fd = s->sock_fd) != -1) {
		s->sock_fd = -1;
		Py_BEGIN_ALLOW_THREADS
		(void) SOCKETCLOSE(fd);
		Py_END_ALLOW_THREADS
	}
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(close_doc,
"close()\n\
\n\
Close the socket.  It cannot be used after this call.");

static int
internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
		 int *timeoutp)
{
	int res, timeout;

	timeout = 0;
	res = connect(s->sock_fd, addr, addrlen);

#ifdef MS_WINDOWS

	if (s->sock_timeout > 0.0) {
		if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
		    IS_SELECTABLE(s)) {
			/* This is a mess.  Best solution: trust select */
			fd_set fds;
			fd_set fds_exc;
			struct timeval tv;
			tv.tv_sec = (int)s->sock_timeout;
			tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
			FD_ZERO(&fds);
			FD_SET(s->sock_fd, &fds);
			FD_ZERO(&fds_exc);
			FD_SET(s->sock_fd, &fds_exc);
			res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
			if (res == 0) {
				res = WSAEWOULDBLOCK;
				timeout = 1;
			} else if (res > 0) {
				if (FD_ISSET(s->sock_fd, &fds))
					/* The socket is in the writeable set - this
					   means connected */
					res = 0;
				else {
					/* As per MS docs, we need to call getsockopt()
					   to get the underlying error */
					int res_size = sizeof res;
					/* It must be in the exception set */
					assert(FD_ISSET(s->sock_fd, &fds_exc));
					if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
					                    (char *)&res, &res_size))
						/* getsockopt also clears WSAGetLastError,
						   so reset it back. */
						WSASetLastError(res);
					else
						res = WSAGetLastError();
				}
			}
			/* else if (res < 0) an error occurred */
		}
	}

	if (res < 0)
		res = WSAGetLastError();

#else

	if (s->sock_timeout > 0.0) {
                if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
                        timeout = internal_select(s, 1);
                        if (timeout == 0) {
                                /* Bug #1019808: in case of an EINPROGRESS, 
                                   use getsockopt(SO_ERROR) to get the real 
                                   error. */
                                socklen_t res_size = sizeof res;
                                (void)getsockopt(s->sock_fd, SOL_SOCKET, 
                                                 SO_ERROR, &res, &res_size);
                                if (res == EISCONN)
                                        res = 0;
                                errno = res;
                        }
                        else if (timeout == -1) {
                                res = errno;            /* had error */
                        }
			else
				res = EWOULDBLOCK;	/* timed out */
		}
	}

	if (res < 0)
		res = errno;

#endif
	*timeoutp = timeout;

	return res;
}

/* s.connect(sockaddr) method */

static PyObject *
sock_connect(PySocketSockObject *s, PyObject *addro)
{
	sock_addr_t addrbuf;
	int addrlen;
	int res;
	int timeout;

	if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
		return NULL;

	Py_BEGIN_ALLOW_THREADS
	res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
	Py_END_ALLOW_THREADS

	if (timeout == 1) {
		PyErr_SetString(socket_timeout, "timed out");
		return NULL;
	}
	if (res != 0)
		return s->errorhandler();
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(connect_doc,
"connect(address)\n\
\n\
Connect the socket to a remote address.  For IP sockets, the address\n\
is a pair (host, port).");


/* s.connect_ex(sockaddr) method */

static PyObject *
sock_connect_ex(PySocketSockObject *s, PyObject *addro)
{
	sock_addr_t addrbuf;
	int addrlen;
	int res;
	int timeout;

	if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
		return NULL;

	Py_BEGIN_ALLOW_THREADS
	res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
	Py_END_ALLOW_THREADS

	/* Signals are not errors (though they may raise exceptions).  Adapted
	   from PyErr_SetFromErrnoWithFilenameObject(). */
#ifdef EINTR
	if (res == EINTR && PyErr_CheckSignals())
		return NULL;
#endif

	return PyInt_FromLong((long) res);
}

PyDoc_STRVAR(connect_ex_doc,
"connect_ex(address) -> errno\n\
\n\
This is like connect(address), but returns an error code (the errno value)\n\
instead of raising an exception when an error occurs.");


/* s.fileno() method */

static PyObject *
sock_fileno(PySocketSockObject *s)
{
#if SIZEOF_SOCKET_T <= SIZEOF_LONG
	return PyInt_FromLong((long) s->sock_fd);
#else
	return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
#endif
}

PyDoc_STRVAR(fileno_doc,
"fileno() -> integer\n\
\n\
Return the integer file descriptor of the socket.");


#ifndef NO_DUP
/* s.dup() method */

static PyObject *
sock_dup(PySocketSockObject *s)
{
	SOCKET_T newfd;
	PyObject *sock;

	newfd = dup(s->sock_fd);
	if (newfd < 0)
		return s->errorhandler();
	sock = (PyObject *) new_sockobject(newfd,
					   s->sock_family,
					   s->sock_type,
					   s->sock_proto);
	if (sock == NULL)
		SOCKETCLOSE(newfd);
	return sock;
}

PyDoc_STRVAR(dup_doc,
"dup() -> socket object\n\
\n\
Return a new socket object connected to the same system resource.");

#endif


/* s.getsockname() method */

static PyObject *
sock_getsockname(PySocketSockObject *s)
{
	sock_addr_t addrbuf;
	int res;
	socklen_t addrlen;

	if (!getsockaddrlen(s, &addrlen))
		return NULL;
	memset(&addrbuf, 0, addrlen);
	Py_BEGIN_ALLOW_THREADS
	res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return s->errorhandler();
	return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
			    s->sock_proto);
}

PyDoc_STRVAR(getsockname_doc,
"getsockname() -> address info\n\
\n\
Return the address of the local endpoint.  For IP sockets, the address\n\
info is a pair (hostaddr, port).");


#ifdef HAVE_GETPEERNAME		/* Cray APP doesn't have this :-( */
/* s.getpeername() method */

static PyObject *
sock_getpeername(PySocketSockObject *s)
{
	sock_addr_t addrbuf;
	int res;
	socklen_t addrlen;

	if (!getsockaddrlen(s, &addrlen))
		return NULL;
	memset(&addrbuf, 0, addrlen);
	Py_BEGIN_ALLOW_THREADS
	res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return s->errorhandler();
	return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
			    s->sock_proto);
}

PyDoc_STRVAR(getpeername_doc,
"getpeername() -> address info\n\
\n\
Return the address of the remote endpoint.  For IP sockets, the address\n\
info is a pair (hostaddr, port).");

#endif /* HAVE_GETPEERNAME */


/* s.listen(n) method */

static PyObject *
sock_listen(PySocketSockObject *s, PyObject *arg)
{
	int backlog;
	int res;

	backlog = PyInt_AsLong(arg);
	if (backlog == -1 && PyErr_Occurred())
		return NULL;
	Py_BEGIN_ALLOW_THREADS
	if (backlog < 1)
		backlog = 1;
	res = listen(s->sock_fd, backlog);
	Py_END_ALLOW_THREADS
	if (res < 0)
		return s->errorhandler();
	Py_INCREF(Py_None);
	return Py_None;
}

PyDoc_STRVAR(listen_doc,
"listen(backlog)\n\
\n\
Enable a server to accept connections.  The backlog argument must be at\n\
least 1; it specifies the number of unaccepted connection that the system\n\
will allow before refusing new connections.");


#ifndef NO_DUP
/* s.makefile(mode) method.
   Create a new open file object referring to a dupped version of
   the socket's file descriptor.  (The dup() call is necessary so
   that the open file and socket objects may be closed independent
   of each other.)
   The mode argument specifies 'r' or 'w' passed to fdopen(). */

static PyObject *
sock_makefile(PySocketSockObject *s, PyObject *args)
{
	extern int fclose(FILE *);
	char *mode = "r";
	int bufsize = -1;
#ifdef MS_WIN32
	Py_intptr_t fd;
#else
	int fd;
#endif
	FILE *fp;
	PyObject *f;
#ifdef __VMS
	char *mode_r = "r";
	char *mode_w = "w";
#endif

	if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
		return NULL;
#ifdef __VMS
	if (strcmp(mode,"rb") == 0) {
	    mode = mode_r;
	}
	else {
		if (strcmp(mode,"wb") == 0) {
			mode = mode_w;
		}
	}
#endif
#ifdef MS_WIN32
	if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
	    ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
#else
	if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
#endif
	{
		if (fd >= 0)
			SOCKETCLOSE(fd);
		return s->errorhandler();
	}
	f = PyFile_FromFile(fp, "<socket>", mode, fclose);
	if (f != NULL)
		PyFile_SetBufSize(f, bufsize);
	return f;
}

PyDoc_STRVAR(makefile_doc,
"makefile([mode[, buffersize]]) -> file object\n\
\n\
Return a regular file object corresponding to the socket.\n\
The mode and buffersize arguments are as for the built-in open() function.");

#endif /* NO_DUP */

/*
 * This is the guts of the recv() and recv_into() methods, which reads into a
 * char buffer.  If you have any inc/dec ref to do to the objects that contain
 * the buffer, do it in the caller.  This function returns the number of bytes
 * succesfully read.  If there was an error, it returns -1.  Note that it is
 * also possible that we return a number of bytes smaller than the request
 * bytes.
 */
static ssize_t
sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
{
        ssize_t outlen = -1;
        int timeout;
#ifdef __VMS
	int remaining;
	char *read_buf;
#endif

	if (!IS_SELECTABLE(s)) {
		select_error();
		return -1;
	}

#ifndef __VMS
	Py_BEGIN_ALLOW_THREADS
	timeout = internal_select(s, 0);
	if (!timeout)
		outlen = recv(s->sock_fd, cbuf, len, flags);
	Py_END_ALLOW_THREADS

	if (timeout == 1) {
		PyErr_SetString(socket_timeout, "timed out");
		return -1;
	}
	if (outlen < 0) {
		/* Note: the call to errorhandler() ALWAYS indirectly returned
		   NULL, so ignore its return value */
		s->errorhandler();
		return -1;
	}
#else
	read_buf = cbuf;
	remaining = len;
	while (remaining != 0) {
		unsigned int segment;
		int nread = -1;

		segment = remaining /SEGMENT_SIZE;
		if (segment != 0) {
			segment = SEGMENT_SIZE;
		}
		else {
			segment = remaining;
		}

		Py_BEGIN_ALLOW_THREADS
		timeout = internal_select(s, 0);
		if (!timeout)
			nread = recv(s->sock_fd, read_buf, segment, flags);
		Py_END_ALLOW_THREADS

		if (timeout == 1) {
			PyErr_SetString(socket_timeout, "timed out");
			return -1;
		}
		if (nread < 0) {
			s->errorhandler();
			return -1;
		}
		if (nread != remaining) {
			read_buf += nread;
			break;
		}

		remaining -= segment;
		read_buf += segment;
	}
	outlen = read_buf - cbuf;
#endif /* !__VMS */

	return outlen;
}


/* s.recv(nbytes [,flags]) method */

static PyObject *
sock_recv(PySocketSockObject *s, PyObject *args)
{
	int recvlen, flags = 0;
        ssize_t outlen;
	PyObject *buf;

	if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
		return NULL;

	if (recvlen < 0) {
		PyErr_SetString(PyExc_ValueError,
				"negative buffersize in recv");
		return NULL;
	}

	/* Allocate a new string. */
	buf = PyString_FromStringAndSize((char *) 0, recvlen);
	if (buf == NULL)
		return NULL;

	/* Call the guts */
	outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
	if (outlen < 0) {
		/* An error occurred, release the string and return an
		   error. */
		Py_DECREF(buf);
		return NULL;
	}
	if (outlen != recvlen) {
		/* We did not read as many bytes as we anticipated, resize the
		   string if possible and be succesful. */
		if (_PyString_Resize(&buf, outlen) < 0)
			/* Oopsy, not so succesful after all. */
			return NULL;
	}

	return buf;
}

PyDoc_STRVAR(recv_doc,
"recv(buffersize[, flags]) -> data\n\
\n\
Receive up to buffersize bytes from the socket.  For the optional flags\n\
argument, see the Unix manual.  When no data is available, block until\n\
at least one byte is available or until the remote end is closed.  When\n\
the remote end is closed and all data is read, return the empty string.");


/* s.recv_into(buffer, [nbytes [,flags]]) method */

static PyObject*
sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
{
	static char *kwlist[] = {"buffer", "nbytes", "flags", 0};

	int recvlen = 0, flags = 0;
        ssize_t readlen;
	char *buf;
	int buflen;

	/* Get the buffer's memory */
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recv_into", kwlist,
					 &buf, &buflen, &recvlen, &flags))
		return NULL;
	assert(buf != 0 && buflen > 0);

	if (recvlen < 0) {
		PyErr_SetString(PyExc_ValueError,
				"negative buffersize in recv_into");
		return NULL;
	}
	if (recvlen == 0) {
            /* If nbytes was not specified, use the buffer's length */
            recvlen = buflen;
	}

	/* Check if the buffer is large enough */
	if (buflen < recvlen) {
		PyErr_SetString(PyExc_ValueError,
				"buffer too small for requested bytes");
		return NULL;
	}

	/* Call the guts */
	readlen = sock_recv_guts(s, buf, recvlen, flags);
	if (readlen < 0) {
		/* Return an error. */
		return NULL;
	}

	/* Return the number of bytes read.  Note that we do not do anything
	   special here in the case that readlen < recvlen. */
	return PyInt_FromSsize_t(readlen);
}

PyDoc_STRVAR(recv_into_doc,
"recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
\n\
A version of recv() that stores its data into a buffer rather than creating \n\
a new string.  Receive up to buffersize bytes from the socket.  If buffersize \n\
is not specified (or 0), receive up to the size available in the given buffer.\n\
\n\
See recv() for documentation about the flags.");


/*
 * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
 * into a char buffer.  If you have any inc/def ref to do to the objects that
 * contain the buffer, do it in the caller.  This function returns the number
 * of bytes succesfully read.  If there was an error, it returns -1.  Note
 * that it is also possible that we return a number of bytes smaller than the
 * request bytes.
 *
 * 'addr' is a return value for the address object.  Note that you must decref
 * it yourself.
 */
static ssize_t
sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
		   PyObject** addr)
{
	sock_addr_t addrbuf;
	int timeout;
	ssize_t n = -1;
	socklen_t addrlen;

	*addr = NULL;

	if (!getsockaddrlen(s, &addrlen))
		return -1;

	if (!IS_SELECTABLE(s)) {
		select_error();
		return -1;
	}

	Py_BEGIN_ALLOW_THREADS
	memset(&addrbuf, 0, addrlen);
	timeout = internal_select(s, 0);
	if (!timeout) {
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
		n = recvfrom(s->sock_fd, cbuf, len, flags,
			     SAS2SA(&addrbuf), &addrlen);
#else
		n = recvfrom(s->sock_fd, cbuf, len, flags,
			     (void *) &addrbuf, &addrlen);
#endif
#else
		n = recvfrom(s->sock_fd, cbuf, len, flags,
			     SAS2SA(&addrbuf), &addrlen);
#endif
	}
	Py_END_ALLOW_THREADS

	if (timeout == 1) {
		PyErr_SetString(socket_timeout, "timed out");
		return -1;
	}
	if (n < 0) {
		s->errorhandler();
                return -1;
	}

	if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
				   addrlen, s->sock_proto)))
		return -1;

	return n;
}

/* s.recvfrom(nbytes [,flags]) method */

static PyObject *
sock_recvfrom(PySocketSockObject *s, PyObject *args)
{
	PyObject *buf = NULL;
	PyObject *addr = NULL;
	PyObject *ret = NULL;
	int recvlen, flags = 0;
        ssize_t outlen;

	if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
		return NULL;

	if (recvlen < 0) {
		PyErr_SetString(PyExc_ValueError,
				"negative buffersize in recvfrom");
		return NULL;
	}

	buf = PyString_FromStringAndSize((char *) 0, recvlen);
	if (buf == NULL)
		return NULL;

	outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
				    recvlen, flags, &addr);
	if (outlen < 0) {
		goto finally;
	}

	if (outlen != recvlen) {
		/* We did not read as many bytes as we anticipated, resize the
		   string if possible and be succesful. */
		if (_PyString_Resize(&buf, outlen) < 0)
			/* Oopsy, not so succesful after all. */
			goto finally;
	}

	ret = PyTuple_Pack(2, buf, addr);

finally:
	Py_XDECREF(buf);
	Py_XDECREF(addr);
	return ret;
}

PyDoc_STRVAR(recvfrom_doc,
"recvfrom(buffersize[, flags]) -> (data, address info)\n\
\n\
Like recv(buffersize, flags) but also return the sender's address info.");


/* s.recvfrom_into(buffer[, nbytes [,flags]]) method */

static PyObject *
sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
{
	static char *kwlist[] = {"buffer", "nbytes", "flags", 0};

	int recvlen = 0, flags = 0;
        ssize_t readlen;
	char *buf;
	int buflen;

	PyObject *addr = NULL;

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "w#|ii:recvfrom_into",
					 kwlist, &buf, &buflen,
					 &recvlen, &flags))
		return NULL;
	assert(buf != 0 && buflen > 0);

	if (recvlen < 0) {
		PyErr_SetString(PyExc_ValueError,
				"negative buffersize in recvfrom_into");
		return NULL;
	}
	if (recvlen == 0) {
            /* If nbytes was not specified, use the buffer's length */
            recvlen = buflen;
	}

	readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
	if (readlen < 0) {
		/* Return an error */
		Py_XDECREF(addr);
		return NULL;
	}

	/* Return the number of bytes read and the address.  Note that we do
	   not do anything special here in the case that readlen < recvlen. */
 	return Py_BuildValue("lN", readlen, addr);
}

PyDoc_STRVAR(recvfrom_into_doc,
"recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
\n\
Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");


/* s.send(data [,flags]) method */

static PyObject *
sock_send(PySocketSockObject *s, PyObject *args)
{
	char *buf;
	int len, n = -1, flags = 0, timeout;
	Py_buffer pbuf;

	if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
		return NULL;

	if (!IS_SELECTABLE(s)) {
		PyBuffer_Release(&pbuf);
		return select_error();
	}
	buf = pbuf.buf;
	len = pbuf.len;

	Py_BEGIN_ALLOW_THREADS
	timeout = internal_select(s, 1);
	if (!timeout)
#ifdef __VMS
		n = sendsegmented(s->sock_fd, buf, len, flags);
#else
		n = send(s->sock_fd, buf, len, flags);
#endif
	Py_END_ALLOW_THREADS

	PyBuffer_Release(&pbuf);

	if (timeout == 1) {