~ubuntu-branches/ubuntu/natty/python3.1/natty-security

« back to all changes in this revision

Viewing changes to Modules/timemodule.c

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2010-07-06 16:52:42 UTC
  • mfrom: (1.2.1 upstream) (2.1.11 sid)
  • Revision ID: james.westby@ubuntu.com-20100706165242-2xv4i019r3et6c0j
Tags: 3.1.2+20100706-1ubuntu1
* Merge with Debian; remaining changes:
  - Regenerate the control file.
  - Add debian/patches/overwrite-semaphore-check for Lucid buildds.

Show diffs side-by-side

added added

removed removed

Lines of Context:
48
48
static HANDLE hInterruptEvent = NULL;
49
49
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
50
50
{
51
 
        SetEvent(hInterruptEvent);
52
 
        /* allow other default handlers to be called.
53
 
           Default Python handler will setup the
54
 
           KeyboardInterrupt exception.
55
 
        */
56
 
        return FALSE;
 
51
    SetEvent(hInterruptEvent);
 
52
    /* allow other default handlers to be called.
 
53
       Default Python handler will setup the
 
54
       KeyboardInterrupt exception.
 
55
    */
 
56
    return FALSE;
57
57
}
58
58
static long main_thread;
59
59
 
94
94
time_t
95
95
_PyTime_DoubleToTimet(double x)
96
96
{
97
 
        time_t result;
98
 
        double diff;
 
97
    time_t result;
 
98
    double diff;
99
99
 
100
 
        result = (time_t)x;
101
 
        /* How much info did we lose?  time_t may be an integral or
102
 
         * floating type, and we don't know which.  If it's integral,
103
 
         * we don't know whether C truncates, rounds, returns the floor,
104
 
         * etc.  If we lost a second or more, the C rounding is
105
 
         * unreasonable, or the input just doesn't fit in a time_t;
106
 
         * call it an error regardless.  Note that the original cast to
107
 
         * time_t can cause a C error too, but nothing we can do to
108
 
         * worm around that.
109
 
         */
110
 
        diff = x - (double)result;
111
 
        if (diff <= -1.0 || diff >= 1.0) {
112
 
                PyErr_SetString(PyExc_ValueError,
113
 
                                "timestamp out of range for platform time_t");
114
 
                result = (time_t)-1;
115
 
        }
116
 
        return result;
 
100
    result = (time_t)x;
 
101
    /* How much info did we lose?  time_t may be an integral or
 
102
     * floating type, and we don't know which.  If it's integral,
 
103
     * we don't know whether C truncates, rounds, returns the floor,
 
104
     * etc.  If we lost a second or more, the C rounding is
 
105
     * unreasonable, or the input just doesn't fit in a time_t;
 
106
     * call it an error regardless.  Note that the original cast to
 
107
     * time_t can cause a C error too, but nothing we can do to
 
108
     * worm around that.
 
109
     */
 
110
    diff = x - (double)result;
 
111
    if (diff <= -1.0 || diff >= 1.0) {
 
112
        PyErr_SetString(PyExc_ValueError,
 
113
                        "timestamp out of range for platform time_t");
 
114
        result = (time_t)-1;
 
115
    }
 
116
    return result;
117
117
}
118
118
 
119
119
static PyObject *
120
120
time_time(PyObject *self, PyObject *unused)
121
121
{
122
 
        double secs;
123
 
        secs = floattime();
124
 
        if (secs == 0.0) {
125
 
                PyErr_SetFromErrno(PyExc_IOError);
126
 
                return NULL;
127
 
        }
128
 
        return PyFloat_FromDouble(secs);
 
122
    double secs;
 
123
    secs = floattime();
 
124
    if (secs == 0.0) {
 
125
        PyErr_SetFromErrno(PyExc_IOError);
 
126
        return NULL;
 
127
    }
 
128
    return PyFloat_FromDouble(secs);
129
129
}
130
130
 
131
131
PyDoc_STRVAR(time_doc,
147
147
static PyObject *
148
148
time_clock(PyObject *self, PyObject *unused)
149
149
{
150
 
        return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
 
150
    return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
151
151
}
152
152
#endif /* HAVE_CLOCK */
153
153
 
156
156
static PyObject *
157
157
time_clock(PyObject *self, PyObject *unused)
158
158
{
159
 
        static LARGE_INTEGER ctrStart;
160
 
        static double divisor = 0.0;
161
 
        LARGE_INTEGER now;
162
 
        double diff;
 
159
    static LARGE_INTEGER ctrStart;
 
160
    static double divisor = 0.0;
 
161
    LARGE_INTEGER now;
 
162
    double diff;
163
163
 
164
 
        if (divisor == 0.0) {
165
 
                LARGE_INTEGER freq;
166
 
                QueryPerformanceCounter(&ctrStart);
167
 
                if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
168
 
                        /* Unlikely to happen - this works on all intel
169
 
                           machines at least!  Revert to clock() */
170
 
                        return PyFloat_FromDouble(((double)clock()) /
171
 
                                                  CLOCKS_PER_SEC);
172
 
                }
173
 
                divisor = (double)freq.QuadPart;
174
 
        }
175
 
        QueryPerformanceCounter(&now);
176
 
        diff = (double)(now.QuadPart - ctrStart.QuadPart);
177
 
        return PyFloat_FromDouble(diff / divisor);
 
164
    if (divisor == 0.0) {
 
165
        LARGE_INTEGER freq;
 
166
        QueryPerformanceCounter(&ctrStart);
 
167
        if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
 
168
            /* Unlikely to happen - this works on all intel
 
169
               machines at least!  Revert to clock() */
 
170
            return PyFloat_FromDouble(((double)clock()) /
 
171
                                      CLOCKS_PER_SEC);
 
172
        }
 
173
        divisor = (double)freq.QuadPart;
 
174
    }
 
175
    QueryPerformanceCounter(&now);
 
176
    diff = (double)(now.QuadPart - ctrStart.QuadPart);
 
177
    return PyFloat_FromDouble(diff / divisor);
178
178
}
179
179
 
180
180
#define HAVE_CLOCK /* So it gets included in the methods */
192
192
static PyObject *
193
193
time_sleep(PyObject *self, PyObject *args)
194
194
{
195
 
        double secs;
196
 
        if (!PyArg_ParseTuple(args, "d:sleep", &secs))
197
 
                return NULL;
198
 
        if (floatsleep(secs) != 0)
199
 
                return NULL;
200
 
        Py_INCREF(Py_None);
201
 
        return Py_None;
 
195
    double secs;
 
196
    if (!PyArg_ParseTuple(args, "d:sleep", &secs))
 
197
        return NULL;
 
198
    if (floatsleep(secs) != 0)
 
199
        return NULL;
 
200
    Py_INCREF(Py_None);
 
201
    return Py_None;
202
202
}
203
203
 
204
204
PyDoc_STRVAR(sleep_doc,
208
208
a floating point number for subsecond precision.");
209
209
 
210
210
static PyStructSequence_Field struct_time_type_fields[] = {
211
 
        {"tm_year", NULL},
212
 
        {"tm_mon", NULL},
213
 
        {"tm_mday", NULL},
214
 
        {"tm_hour", NULL},
215
 
        {"tm_min", NULL},
216
 
        {"tm_sec", NULL},
217
 
        {"tm_wday", NULL},
218
 
        {"tm_yday", NULL},
219
 
        {"tm_isdst", NULL},
220
 
        {0}
 
211
    {"tm_year", NULL},
 
212
    {"tm_mon", NULL},
 
213
    {"tm_mday", NULL},
 
214
    {"tm_hour", NULL},
 
215
    {"tm_min", NULL},
 
216
    {"tm_sec", NULL},
 
217
    {"tm_wday", NULL},
 
218
    {"tm_yday", NULL},
 
219
    {"tm_isdst", NULL},
 
220
    {0}
221
221
};
222
222
 
223
223
static PyStructSequence_Desc struct_time_type_desc = {
224
 
        "time.struct_time",
225
 
        NULL,
226
 
        struct_time_type_fields,
227
 
        9,
 
224
    "time.struct_time",
 
225
    NULL,
 
226
    struct_time_type_fields,
 
227
    9,
228
228
};
229
229
 
230
230
static int initialized;
233
233
static PyObject *
234
234
tmtotuple(struct tm *p)
235
235
{
236
 
        PyObject *v = PyStructSequence_New(&StructTimeType);
237
 
        if (v == NULL)
238
 
                return NULL;
 
236
    PyObject *v = PyStructSequence_New(&StructTimeType);
 
237
    if (v == NULL)
 
238
        return NULL;
239
239
 
240
240
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
241
241
 
242
 
        SET(0, p->tm_year + 1900);
243
 
        SET(1, p->tm_mon + 1);     /* Want January == 1 */
244
 
        SET(2, p->tm_mday);
245
 
        SET(3, p->tm_hour);
246
 
        SET(4, p->tm_min);
247
 
        SET(5, p->tm_sec);
248
 
        SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
249
 
        SET(7, p->tm_yday + 1);    /* Want January, 1 == 1 */
250
 
        SET(8, p->tm_isdst);
 
242
    SET(0, p->tm_year + 1900);
 
243
    SET(1, p->tm_mon + 1);         /* Want January == 1 */
 
244
    SET(2, p->tm_mday);
 
245
    SET(3, p->tm_hour);
 
246
    SET(4, p->tm_min);
 
247
    SET(5, p->tm_sec);
 
248
    SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
 
249
    SET(7, p->tm_yday + 1);        /* Want January, 1 == 1 */
 
250
    SET(8, p->tm_isdst);
251
251
#undef SET
252
 
        if (PyErr_Occurred()) {
253
 
                Py_XDECREF(v);
254
 
                return NULL;
255
 
        }
 
252
    if (PyErr_Occurred()) {
 
253
        Py_XDECREF(v);
 
254
        return NULL;
 
255
    }
256
256
 
257
 
        return v;
 
257
    return v;
258
258
}
259
259
 
260
260
static PyObject *
261
261
structtime_totuple(PyObject *t)
262
262
{
263
 
        PyObject *x = NULL;
264
 
        unsigned int i;
265
 
        PyObject *v = PyTuple_New(9);
266
 
        if (v == NULL)
267
 
                return NULL;
268
 
 
269
 
        for (i=0; i<9; i++) {
270
 
                x = PyStructSequence_GET_ITEM(t, i);
271
 
                Py_INCREF(x);
272
 
                PyTuple_SET_ITEM(v, i, x);
273
 
        }
274
 
 
275
 
        if (PyErr_Occurred()) {
276
 
                Py_XDECREF(v);
277
 
                return NULL;
278
 
        }
279
 
 
280
 
        return v;
 
263
    PyObject *x = NULL;
 
264
    unsigned int i;
 
265
    PyObject *v = PyTuple_New(9);
 
266
    if (v == NULL)
 
267
        return NULL;
 
268
 
 
269
    for (i=0; i<9; i++) {
 
270
        x = PyStructSequence_GET_ITEM(t, i);
 
271
        Py_INCREF(x);
 
272
        PyTuple_SET_ITEM(v, i, x);
 
273
    }
 
274
 
 
275
    if (PyErr_Occurred()) {
 
276
        Py_XDECREF(v);
 
277
        return NULL;
 
278
    }
 
279
 
 
280
    return v;
281
281
}
282
282
 
283
283
static PyObject *
284
284
time_convert(double when, struct tm * (*function)(const time_t *))
285
285
{
286
 
        struct tm *p;
287
 
        time_t whent = _PyTime_DoubleToTimet(when);
 
286
    struct tm *p;
 
287
    time_t whent = _PyTime_DoubleToTimet(when);
288
288
 
289
 
        if (whent == (time_t)-1 && PyErr_Occurred())
290
 
                return NULL;
291
 
        errno = 0;
292
 
        p = function(&whent);
293
 
        if (p == NULL) {
 
289
    if (whent == (time_t)-1 && PyErr_Occurred())
 
290
        return NULL;
 
291
    errno = 0;
 
292
    p = function(&whent);
 
293
    if (p == NULL) {
294
294
#ifdef EINVAL
295
 
                if (errno == 0)
296
 
                        errno = EINVAL;
 
295
        if (errno == 0)
 
296
            errno = EINVAL;
297
297
#endif
298
 
                return PyErr_SetFromErrno(PyExc_ValueError);
299
 
        }
300
 
        return tmtotuple(p);
 
298
        return PyErr_SetFromErrno(PyExc_ValueError);
 
299
    }
 
300
    return tmtotuple(p);
301
301
}
302
302
 
303
303
/* Parse arg tuple that can contain an optional float-or-None value;
307
307
static int
308
308
parse_time_double_args(PyObject *args, char *format, double *pwhen)
309
309
{
310
 
        PyObject *ot = NULL;
 
310
    PyObject *ot = NULL;
311
311
 
312
 
        if (!PyArg_ParseTuple(args, format, &ot))
313
 
                return 0;
314
 
        if (ot == NULL || ot == Py_None)
315
 
                *pwhen = floattime();
316
 
        else {
317
 
                double when = PyFloat_AsDouble(ot);
318
 
                if (PyErr_Occurred())
319
 
                        return 0;
320
 
                *pwhen = when;
321
 
        }
322
 
        return 1;
 
312
    if (!PyArg_ParseTuple(args, format, &ot))
 
313
        return 0;
 
314
    if (ot == NULL || ot == Py_None)
 
315
        *pwhen = floattime();
 
316
    else {
 
317
        double when = PyFloat_AsDouble(ot);
 
318
        if (PyErr_Occurred())
 
319
            return 0;
 
320
        *pwhen = when;
 
321
    }
 
322
    return 1;
323
323
}
324
324
 
325
325
static PyObject *
326
326
time_gmtime(PyObject *self, PyObject *args)
327
327
{
328
 
        double when;
329
 
        if (!parse_time_double_args(args, "|O:gmtime", &when))
330
 
                return NULL;
331
 
        return time_convert(when, gmtime);
 
328
    double when;
 
329
    if (!parse_time_double_args(args, "|O:gmtime", &when))
 
330
        return NULL;
 
331
    return time_convert(when, gmtime);
332
332
}
333
333
 
334
334
PyDoc_STRVAR(gmtime_doc,
341
341
static PyObject *
342
342
time_localtime(PyObject *self, PyObject *args)
343
343
{
344
 
        double when;
345
 
        if (!parse_time_double_args(args, "|O:localtime", &when))
346
 
                return NULL;
347
 
        return time_convert(when, localtime);
 
344
    double when;
 
345
    if (!parse_time_double_args(args, "|O:localtime", &when))
 
346
        return NULL;
 
347
    return time_convert(when, localtime);
348
348
}
349
349
 
350
350
PyDoc_STRVAR(localtime_doc,
351
351
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
352
 
                          tm_sec,tm_wday,tm_yday,tm_isdst)\n\
 
352
                          tm_sec,tm_wday,tm_yday,tm_isdst)\n\
353
353
\n\
354
354
Convert seconds since the Epoch to a time tuple expressing local time.\n\
355
355
When 'seconds' is not passed in, convert the current time instead.");
357
357
static int
358
358
gettmarg(PyObject *args, struct tm *p)
359
359
{
360
 
        int y;
361
 
        PyObject *t = NULL;
362
 
 
363
 
        memset((void *) p, '\0', sizeof(struct tm));
364
 
 
365
 
        if (PyTuple_Check(args)) {
366
 
                t = args;
367
 
                Py_INCREF(t);
368
 
        }
369
 
        else if (Py_TYPE(args) == &StructTimeType) {
370
 
                t = structtime_totuple(args);
371
 
        }
372
 
        else {
373
 
                PyErr_SetString(PyExc_TypeError,
374
 
                                "Tuple or struct_time argument required");
375
 
                return 0;
376
 
        }
377
 
 
378
 
        if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
379
 
                                           &y,
380
 
                                           &p->tm_mon,
381
 
                                           &p->tm_mday,
382
 
                                           &p->tm_hour,
383
 
                                           &p->tm_min,
384
 
                                           &p->tm_sec,
385
 
                                           &p->tm_wday,
386
 
                                           &p->tm_yday,
387
 
                                           &p->tm_isdst)) {
388
 
                Py_XDECREF(t);
389
 
                return 0;
390
 
        }
391
 
        Py_DECREF(t);
392
 
 
393
 
        if (y < 1900) {
394
 
                PyObject *accept = PyDict_GetItemString(moddict,
395
 
                                                        "accept2dyear");
396
 
                if (accept == NULL || !PyLong_CheckExact(accept) ||
397
 
                    !PyObject_IsTrue(accept)) {
398
 
                        PyErr_SetString(PyExc_ValueError,
399
 
                                        "year >= 1900 required");
400
 
                        return 0;
401
 
                }
402
 
                if (69 <= y && y <= 99)
403
 
                        y += 1900;
404
 
                else if (0 <= y && y <= 68)
405
 
                        y += 2000;
406
 
                else {
407
 
                        PyErr_SetString(PyExc_ValueError,
408
 
                                        "year out of range");
409
 
                        return 0;
410
 
                }
411
 
        }
412
 
        p->tm_year = y - 1900;
413
 
        p->tm_mon--;
414
 
        p->tm_wday = (p->tm_wday + 1) % 7;
415
 
        p->tm_yday--;
416
 
        return 1;
 
360
    int y;
 
361
    PyObject *t = NULL;
 
362
 
 
363
    memset((void *) p, '\0', sizeof(struct tm));
 
364
 
 
365
    if (PyTuple_Check(args)) {
 
366
        t = args;
 
367
        Py_INCREF(t);
 
368
    }
 
369
    else if (Py_TYPE(args) == &StructTimeType) {
 
370
        t = structtime_totuple(args);
 
371
    }
 
372
    else {
 
373
        PyErr_SetString(PyExc_TypeError,
 
374
                        "Tuple or struct_time argument required");
 
375
        return 0;
 
376
    }
 
377
 
 
378
    if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
 
379
                                       &y,
 
380
                                       &p->tm_mon,
 
381
                                       &p->tm_mday,
 
382
                                       &p->tm_hour,
 
383
                                       &p->tm_min,
 
384
                                       &p->tm_sec,
 
385
                                       &p->tm_wday,
 
386
                                       &p->tm_yday,
 
387
                                       &p->tm_isdst)) {
 
388
        Py_XDECREF(t);
 
389
        return 0;
 
390
    }
 
391
    Py_DECREF(t);
 
392
 
 
393
    if (y < 1900) {
 
394
        PyObject *accept = PyDict_GetItemString(moddict,
 
395
                                                "accept2dyear");
 
396
        if (accept == NULL || !PyLong_CheckExact(accept) ||
 
397
            !PyObject_IsTrue(accept)) {
 
398
            PyErr_SetString(PyExc_ValueError,
 
399
                            "year >= 1900 required");
 
400
            return 0;
 
401
        }
 
402
        if (69 <= y && y <= 99)
 
403
            y += 1900;
 
404
        else if (0 <= y && y <= 68)
 
405
            y += 2000;
 
406
        else {
 
407
            PyErr_SetString(PyExc_ValueError,
 
408
                            "year out of range");
 
409
            return 0;
 
410
        }
 
411
    }
 
412
    p->tm_year = y - 1900;
 
413
    p->tm_mon--;
 
414
    p->tm_wday = (p->tm_wday + 1) % 7;
 
415
    p->tm_yday--;
 
416
    return 1;
417
417
}
418
418
 
419
419
#ifdef HAVE_STRFTIME
430
430
static PyObject *
431
431
time_strftime(PyObject *self, PyObject *args)
432
432
{
433
 
        PyObject *tup = NULL;
434
 
        struct tm buf;
435
 
        const time_char *fmt;
436
 
        PyObject *format, *tmpfmt;
437
 
        size_t fmtlen, buflen;
438
 
        time_char *outbuf = 0;
439
 
        size_t i;
440
 
 
441
 
        memset((void *) &buf, '\0', sizeof(buf));
442
 
 
443
 
        /* Will always expect a unicode string to be passed as format.
444
 
           Given that there's no str type anymore in py3k this seems safe.
445
 
        */
446
 
        if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
447
 
                return NULL;
448
 
 
449
 
        if (tup == NULL) {
450
 
                time_t tt = time(NULL);
451
 
                buf = *localtime(&tt);
452
 
        } else if (!gettmarg(tup, &buf))
453
 
                return NULL;
454
 
 
455
 
        /* Checks added to make sure strftime() does not crash Python by
456
 
            indexing blindly into some array for a textual representation
457
 
            by some bad index (fixes bug #897625).
458
 
 
459
 
            Also support values of zero from Python code for arguments in which
460
 
            that is out of range by forcing that value to the lowest value that
461
 
            is valid (fixed bug #1520914).
462
 
 
463
 
            Valid ranges based on what is allowed in struct tm:
464
 
 
465
 
            - tm_year: [0, max(int)] (1)
466
 
            - tm_mon: [0, 11] (2)
467
 
            - tm_mday: [1, 31]
468
 
            - tm_hour: [0, 23]
469
 
            - tm_min: [0, 59]
470
 
            - tm_sec: [0, 60]
471
 
            - tm_wday: [0, 6] (1)
472
 
            - tm_yday: [0, 365] (2)
473
 
            - tm_isdst: [-max(int), max(int)]
474
 
 
475
 
            (1) gettmarg() handles bounds-checking.
476
 
            (2) Python's acceptable range is one greater than the range in C,
477
 
                thus need to check against automatic decrement by gettmarg().
478
 
        */
479
 
        if (buf.tm_mon == -1)
480
 
            buf.tm_mon = 0;
481
 
        else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
482
 
            PyErr_SetString(PyExc_ValueError, "month out of range");
483
 
                        return NULL;
484
 
        }
485
 
        if (buf.tm_mday == 0)
486
 
            buf.tm_mday = 1;
487
 
        else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
488
 
            PyErr_SetString(PyExc_ValueError, "day of month out of range");
489
 
                        return NULL;
490
 
        }
491
 
        if (buf.tm_hour < 0 || buf.tm_hour > 23) {
492
 
            PyErr_SetString(PyExc_ValueError, "hour out of range");
493
 
            return NULL;
494
 
        }
495
 
        if (buf.tm_min < 0 || buf.tm_min > 59) {
496
 
            PyErr_SetString(PyExc_ValueError, "minute out of range");
497
 
            return NULL;
498
 
        }
499
 
        if (buf.tm_sec < 0 || buf.tm_sec > 61) {
500
 
            PyErr_SetString(PyExc_ValueError, "seconds out of range");
501
 
            return NULL;
502
 
        }
503
 
        /* tm_wday does not need checking of its upper-bound since taking
504
 
        ``% 7`` in gettmarg() automatically restricts the range. */
505
 
        if (buf.tm_wday < 0) {
506
 
            PyErr_SetString(PyExc_ValueError, "day of week out of range");
507
 
            return NULL;
508
 
        }
509
 
        if (buf.tm_yday == -1)
510
 
            buf.tm_yday = 0;
511
 
        else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
512
 
            PyErr_SetString(PyExc_ValueError, "day of year out of range");
513
 
            return NULL;
514
 
        }
515
 
        if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
516
 
            PyErr_SetString(PyExc_ValueError,
517
 
                            "daylight savings flag out of range");
518
 
            return NULL;
519
 
        }
 
433
    PyObject *tup = NULL;
 
434
    struct tm buf;
 
435
    const time_char *fmt;
 
436
    PyObject *format, *tmpfmt;
 
437
    size_t fmtlen, buflen;
 
438
    time_char *outbuf = 0;
 
439
    size_t i;
 
440
 
 
441
    memset((void *) &buf, '\0', sizeof(buf));
 
442
 
 
443
    /* Will always expect a unicode string to be passed as format.
 
444
       Given that there's no str type anymore in py3k this seems safe.
 
445
    */
 
446
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format, &tup))
 
447
        return NULL;
 
448
 
 
449
    if (tup == NULL) {
 
450
        time_t tt = time(NULL);
 
451
        buf = *localtime(&tt);
 
452
    } else if (!gettmarg(tup, &buf))
 
453
        return NULL;
 
454
 
 
455
    /* Checks added to make sure strftime() does not crash Python by
 
456
        indexing blindly into some array for a textual representation
 
457
        by some bad index (fixes bug #897625).
 
458
 
 
459
        Also support values of zero from Python code for arguments in which
 
460
        that is out of range by forcing that value to the lowest value that
 
461
        is valid (fixed bug #1520914).
 
462
 
 
463
        Valid ranges based on what is allowed in struct tm:
 
464
 
 
465
        - tm_year: [0, max(int)] (1)
 
466
        - tm_mon: [0, 11] (2)
 
467
        - tm_mday: [1, 31]
 
468
        - tm_hour: [0, 23]
 
469
        - tm_min: [0, 59]
 
470
        - tm_sec: [0, 60]
 
471
        - tm_wday: [0, 6] (1)
 
472
        - tm_yday: [0, 365] (2)
 
473
        - tm_isdst: [-max(int), max(int)]
 
474
 
 
475
        (1) gettmarg() handles bounds-checking.
 
476
        (2) Python's acceptable range is one greater than the range in C,
 
477
        thus need to check against automatic decrement by gettmarg().
 
478
    */
 
479
    if (buf.tm_mon == -1)
 
480
        buf.tm_mon = 0;
 
481
    else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
 
482
        PyErr_SetString(PyExc_ValueError, "month out of range");
 
483
                    return NULL;
 
484
    }
 
485
    if (buf.tm_mday == 0)
 
486
        buf.tm_mday = 1;
 
487
    else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
 
488
        PyErr_SetString(PyExc_ValueError, "day of month out of range");
 
489
                    return NULL;
 
490
    }
 
491
    if (buf.tm_hour < 0 || buf.tm_hour > 23) {
 
492
        PyErr_SetString(PyExc_ValueError, "hour out of range");
 
493
        return NULL;
 
494
    }
 
495
    if (buf.tm_min < 0 || buf.tm_min > 59) {
 
496
        PyErr_SetString(PyExc_ValueError, "minute out of range");
 
497
        return NULL;
 
498
    }
 
499
    if (buf.tm_sec < 0 || buf.tm_sec > 61) {
 
500
        PyErr_SetString(PyExc_ValueError, "seconds out of range");
 
501
        return NULL;
 
502
    }
 
503
    /* tm_wday does not need checking of its upper-bound since taking
 
504
    ``% 7`` in gettmarg() automatically restricts the range. */
 
505
    if (buf.tm_wday < 0) {
 
506
        PyErr_SetString(PyExc_ValueError, "day of week out of range");
 
507
        return NULL;
 
508
    }
 
509
    if (buf.tm_yday == -1)
 
510
        buf.tm_yday = 0;
 
511
    else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
 
512
        PyErr_SetString(PyExc_ValueError, "day of year out of range");
 
513
        return NULL;
 
514
    }
 
515
    if (buf.tm_isdst < -1 || buf.tm_isdst > 1) {
 
516
        PyErr_SetString(PyExc_ValueError,
 
517
                        "daylight savings flag out of range");
 
518
        return NULL;
 
519
    }
520
520
 
521
521
#ifdef HAVE_WCSFTIME
522
 
        tmpfmt = PyBytes_FromStringAndSize(NULL,
523
 
                                           sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
524
 
        if (!tmpfmt)
525
 
                return NULL;
526
 
        /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
527
 
           expansion. */
528
 
        if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
529
 
                                 (wchar_t*)PyBytes_AS_STRING(tmpfmt),
530
 
                                 PyUnicode_GetSize(format)+1) == (size_t)-1)
531
 
                /* This shouldn't fail. */
532
 
                Py_FatalError("PyUnicode_AsWideChar failed");
533
 
        format = tmpfmt;
534
 
        fmt = (wchar_t*)PyBytes_AS_STRING(format);
 
522
    tmpfmt = PyBytes_FromStringAndSize(NULL,
 
523
                                       sizeof(wchar_t) * (PyUnicode_GetSize(format)+1));
 
524
    if (!tmpfmt)
 
525
        return NULL;
 
526
    /* This assumes that PyUnicode_AsWideChar doesn't do any UTF-16
 
527
       expansion. */
 
528
    if (PyUnicode_AsWideChar((PyUnicodeObject*)format,
 
529
                             (wchar_t*)PyBytes_AS_STRING(tmpfmt),
 
530
                             PyUnicode_GetSize(format)+1) == (size_t)-1)
 
531
        /* This shouldn't fail. */
 
532
        Py_FatalError("PyUnicode_AsWideChar failed");
 
533
    format = tmpfmt;
 
534
    fmt = (wchar_t*)PyBytes_AS_STRING(format);
535
535
#else
536
 
        /* Convert the unicode string to an ascii one */
537
 
        format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
538
 
        if (format == NULL)
539
 
                return NULL;
540
 
        fmt = PyBytes_AS_STRING(format);
 
536
    /* Convert the unicode string to an ascii one */
 
537
    format = PyUnicode_AsEncodedString(format, TZNAME_ENCODING, NULL);
 
538
    if (format == NULL)
 
539
        return NULL;
 
540
    fmt = PyBytes_AS_STRING(format);
541
541
#endif
542
542
 
543
543
#if defined(MS_WINDOWS) && defined(HAVE_WCSFTIME)
544
 
        /* check that the format string contains only valid directives */
545
 
        for(outbuf = wcschr(fmt, L'%');
546
 
                outbuf != NULL;
547
 
                outbuf = wcschr(outbuf+2, L'%'))
548
 
        {
549
 
                if (outbuf[1]=='#')
550
 
                        ++outbuf; /* not documented by python, */
551
 
                if (outbuf[1]=='\0' ||
552
 
                        !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
553
 
                {
554
 
                        PyErr_SetString(PyExc_ValueError, "Invalid format string");
555
 
                        return 0;
556
 
                }
557
 
        }
 
544
    /* check that the format string contains only valid directives */
 
545
    for(outbuf = wcschr(fmt, L'%');
 
546
        outbuf != NULL;
 
547
        outbuf = wcschr(outbuf+2, L'%'))
 
548
    {
 
549
        if (outbuf[1]=='#')
 
550
            ++outbuf; /* not documented by python, */
 
551
        if (outbuf[1]=='\0' ||
 
552
            !wcschr(L"aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
 
553
        {
 
554
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
 
555
            return 0;
 
556
        }
 
557
    }
558
558
#endif
559
559
 
560
 
        fmtlen = time_strlen(fmt);
 
560
    fmtlen = time_strlen(fmt);
561
561
 
562
 
        /* I hate these functions that presume you know how big the output
563
 
         * will be ahead of time...
564
 
         */
565
 
        for (i = 1024; ; i += i) {
566
 
                outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
567
 
                if (outbuf == NULL) {
568
 
                        Py_DECREF(format);
569
 
                        return PyErr_NoMemory();
570
 
                }
571
 
                buflen = format_time(outbuf, i, fmt, &buf);
572
 
                if (buflen > 0 || i >= 256 * fmtlen) {
573
 
                        /* If the buffer is 256 times as long as the format,
574
 
                           it's probably not failing for lack of room!
575
 
                           More likely, the format yields an empty result,
576
 
                           e.g. an empty format, or %Z when the timezone
577
 
                           is unknown. */
578
 
                        PyObject *ret;
 
562
    /* I hate these functions that presume you know how big the output
 
563
     * will be ahead of time...
 
564
     */
 
565
    for (i = 1024; ; i += i) {
 
566
        outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
 
567
        if (outbuf == NULL) {
 
568
            Py_DECREF(format);
 
569
            return PyErr_NoMemory();
 
570
        }
 
571
        buflen = format_time(outbuf, i, fmt, &buf);
 
572
        if (buflen > 0 || i >= 256 * fmtlen) {
 
573
            /* If the buffer is 256 times as long as the format,
 
574
               it's probably not failing for lack of room!
 
575
               More likely, the format yields an empty result,
 
576
               e.g. an empty format, or %Z when the timezone
 
577
               is unknown. */
 
578
            PyObject *ret;
579
579
#ifdef HAVE_WCSFTIME
580
 
                        ret = PyUnicode_FromWideChar(outbuf, buflen);
 
580
            ret = PyUnicode_FromWideChar(outbuf, buflen);
581
581
#else
582
 
                        ret = PyUnicode_Decode(outbuf, buflen,
583
 
                                               TZNAME_ENCODING, NULL);
 
582
            ret = PyUnicode_Decode(outbuf, buflen,
 
583
                                   TZNAME_ENCODING, NULL);
584
584
#endif
585
 
                        PyMem_Free(outbuf);
586
 
                        Py_DECREF(format);
587
 
                        return ret;
588
 
                }
589
 
                PyMem_Free(outbuf);
 
585
            PyMem_Free(outbuf);
 
586
            Py_DECREF(format);
 
587
            return ret;
 
588
        }
 
589
        PyMem_Free(outbuf);
590
590
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
591
 
                /* VisualStudio .NET 2005 does this properly */
592
 
                if (buflen == 0 && errno == EINVAL) {
593
 
                        PyErr_SetString(PyExc_ValueError, "Invalid format string");
594
 
                        Py_DECREF(format);
595
 
                        return 0;
596
 
                }
 
591
        /* VisualStudio .NET 2005 does this properly */
 
592
        if (buflen == 0 && errno == EINVAL) {
 
593
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
 
594
            Py_DECREF(format);
 
595
            return 0;
 
596
        }
597
597
#endif
598
 
        }
 
598
    }
599
599
}
600
600
 
601
601
#undef time_char
616
616
    PyObject *strptime_result;
617
617
 
618
618
    if (!strptime_module)
619
 
        return NULL;
 
619
    return NULL;
620
620
    strptime_result = PyObject_CallMethod(strptime_module, "_strptime_time", "O", args);
621
621
    Py_DECREF(strptime_module);
622
622
    return strptime_result;
632
632
static PyObject *
633
633
time_asctime(PyObject *self, PyObject *args)
634
634
{
635
 
        PyObject *tup = NULL;
636
 
        struct tm buf;
637
 
        char *p;
638
 
        if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
639
 
                return NULL;
640
 
        if (tup == NULL) {
641
 
                time_t tt = time(NULL);
642
 
                buf = *localtime(&tt);
643
 
        } else if (!gettmarg(tup, &buf))
644
 
                return NULL;
645
 
        p = asctime(&buf);
646
 
        if (p[24] == '\n')
647
 
                p[24] = '\0';
648
 
        return PyUnicode_FromString(p);
 
635
    PyObject *tup = NULL;
 
636
    struct tm buf;
 
637
    char *p;
 
638
    if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
 
639
        return NULL;
 
640
    if (tup == NULL) {
 
641
        time_t tt = time(NULL);
 
642
        buf = *localtime(&tt);
 
643
    } else if (!gettmarg(tup, &buf))
 
644
        return NULL;
 
645
    p = asctime(&buf);
 
646
    if (p[24] == '\n')
 
647
        p[24] = '\0';
 
648
    return PyUnicode_FromString(p);
649
649
}
650
650
 
651
651
PyDoc_STRVAR(asctime_doc,
658
658
static PyObject *
659
659
time_ctime(PyObject *self, PyObject *args)
660
660
{
661
 
        PyObject *ot = NULL;
662
 
        time_t tt;
663
 
        char *p;
 
661
    PyObject *ot = NULL;
 
662
    time_t tt;
 
663
    char *p;
664
664
 
665
 
        if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
666
 
                return NULL;
667
 
        if (ot == NULL || ot == Py_None)
668
 
                tt = time(NULL);
669
 
        else {
670
 
                double dt = PyFloat_AsDouble(ot);
671
 
                if (PyErr_Occurred())
672
 
                        return NULL;
673
 
                tt = _PyTime_DoubleToTimet(dt);
674
 
                if (tt == (time_t)-1 && PyErr_Occurred())
675
 
                        return NULL;
676
 
        }
677
 
        p = ctime(&tt);
678
 
        if (p == NULL) {
679
 
                PyErr_SetString(PyExc_ValueError, "unconvertible time");
680
 
                return NULL;
681
 
        }
682
 
        if (p[24] == '\n')
683
 
                p[24] = '\0';
684
 
        return PyUnicode_FromString(p);
 
665
    if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
 
666
        return NULL;
 
667
    if (ot == NULL || ot == Py_None)
 
668
        tt = time(NULL);
 
669
    else {
 
670
        double dt = PyFloat_AsDouble(ot);
 
671
        if (PyErr_Occurred())
 
672
            return NULL;
 
673
        tt = _PyTime_DoubleToTimet(dt);
 
674
        if (tt == (time_t)-1 && PyErr_Occurred())
 
675
            return NULL;
 
676
    }
 
677
    p = ctime(&tt);
 
678
    if (p == NULL) {
 
679
        PyErr_SetString(PyExc_ValueError, "unconvertible time");
 
680
        return NULL;
 
681
    }
 
682
    if (p[24] == '\n')
 
683
        p[24] = '\0';
 
684
    return PyUnicode_FromString(p);
685
685
}
686
686
 
687
687
PyDoc_STRVAR(ctime_doc,
695
695
static PyObject *
696
696
time_mktime(PyObject *self, PyObject *tup)
697
697
{
698
 
        struct tm buf;
699
 
        time_t tt;
700
 
        if (!gettmarg(tup, &buf))
701
 
                return NULL;
702
 
        tt = mktime(&buf);
703
 
        if (tt == (time_t)(-1)) {
704
 
                PyErr_SetString(PyExc_OverflowError,
705
 
                                "mktime argument out of range");
706
 
                return NULL;
707
 
        }
708
 
        return PyFloat_FromDouble((double)tt);
 
698
    struct tm buf;
 
699
    time_t tt;
 
700
    if (!gettmarg(tup, &buf))
 
701
        return NULL;
 
702
    tt = mktime(&buf);
 
703
    if (tt == (time_t)(-1)) {
 
704
        PyErr_SetString(PyExc_OverflowError,
 
705
                        "mktime argument out of range");
 
706
        return NULL;
 
707
    }
 
708
    return PyFloat_FromDouble((double)tt);
709
709
}
710
710
 
711
711
PyDoc_STRVAR(mktime_doc,
720
720
static PyObject *
721
721
time_tzset(PyObject *self, PyObject *unused)
722
722
{
723
 
        PyObject* m;
724
 
 
725
 
        m = PyImport_ImportModuleNoBlock("time");
726
 
        if (m == NULL) {
727
 
            return NULL;
728
 
        }
729
 
 
730
 
        tzset();
731
 
 
732
 
        /* Reset timezone, altzone, daylight and tzname */
733
 
        PyInit_timezone(m);
734
 
        Py_DECREF(m);
735
 
 
736
 
        Py_INCREF(Py_None);
737
 
        return Py_None;
 
723
    PyObject* m;
 
724
 
 
725
    m = PyImport_ImportModuleNoBlock("time");
 
726
    if (m == NULL) {
 
727
        return NULL;
 
728
    }
 
729
 
 
730
    tzset();
 
731
 
 
732
    /* Reset timezone, altzone, daylight and tzname */
 
733
    PyInit_timezone(m);
 
734
    Py_DECREF(m);
 
735
 
 
736
    Py_INCREF(Py_None);
 
737
    return Py_None;
738
738
}
739
739
 
740
740
PyDoc_STRVAR(tzset_doc,
754
754
static void
755
755
PyInit_timezone(PyObject *m) {
756
756
    /* This code moved from PyInit_time wholesale to allow calling it from
757
 
        time_tzset. In the future, some parts of it can be moved back
758
 
        (for platforms that don't HAVE_WORKING_TZSET, when we know what they
759
 
        are), and the extraneous calls to tzset(3) should be removed.
760
 
        I haven't done this yet, as I don't want to change this code as
761
 
        little as possible when introducing the time.tzset and time.tzsetwall
762
 
        methods. This should simply be a method of doing the following once,
763
 
        at the top of this function and removing the call to tzset() from
764
 
        time_tzset():
765
 
 
766
 
            #ifdef HAVE_TZSET
767
 
            tzset()
768
 
            #endif
769
 
 
770
 
        And I'm lazy and hate C so nyer.
 
757
    time_tzset. In the future, some parts of it can be moved back
 
758
    (for platforms that don't HAVE_WORKING_TZSET, when we know what they
 
759
    are), and the extraneous calls to tzset(3) should be removed.
 
760
    I haven't done this yet, as I don't want to change this code as
 
761
    little as possible when introducing the time.tzset and time.tzsetwall
 
762
    methods. This should simply be a method of doing the following once,
 
763
    at the top of this function and removing the call to tzset() from
 
764
    time_tzset():
 
765
 
 
766
        #ifdef HAVE_TZSET
 
767
        tzset()
 
768
        #endif
 
769
 
 
770
    And I'm lazy and hate C so nyer.
771
771
     */
772
772
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
773
 
        PyObject *otz0, *otz1;
774
 
        tzset();
 
773
    PyObject *otz0, *otz1;
 
774
    tzset();
775
775
#ifdef PYOS_OS2
776
 
        PyModule_AddIntConstant(m, "timezone", _timezone);
 
776
    PyModule_AddIntConstant(m, "timezone", _timezone);
777
777
#else /* !PYOS_OS2 */
778
 
        PyModule_AddIntConstant(m, "timezone", timezone);
 
778
    PyModule_AddIntConstant(m, "timezone", timezone);
779
779
#endif /* PYOS_OS2 */
780
780
#ifdef HAVE_ALTZONE
781
 
        PyModule_AddIntConstant(m, "altzone", altzone);
 
781
    PyModule_AddIntConstant(m, "altzone", altzone);
782
782
#else
783
783
#ifdef PYOS_OS2
784
 
        PyModule_AddIntConstant(m, "altzone", _timezone-3600);
 
784
    PyModule_AddIntConstant(m, "altzone", _timezone-3600);
785
785
#else /* !PYOS_OS2 */
786
 
        PyModule_AddIntConstant(m, "altzone", timezone-3600);
 
786
    PyModule_AddIntConstant(m, "altzone", timezone-3600);
787
787
#endif /* PYOS_OS2 */
788
788
#endif
789
 
        PyModule_AddIntConstant(m, "daylight", daylight);
790
 
        otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
791
 
        otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
792
 
        PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
 
789
    PyModule_AddIntConstant(m, "daylight", daylight);
 
790
    otz0 = PyUnicode_Decode(tzname[0], strlen(tzname[0]), TZNAME_ENCODING, NULL);
 
791
    otz1 = PyUnicode_Decode(tzname[1], strlen(tzname[1]), TZNAME_ENCODING, NULL);
 
792
    PyModule_AddObject(m, "tzname", Py_BuildValue("(NN)", otz0, otz1));
793
793
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
794
794
#ifdef HAVE_STRUCT_TM_TM_ZONE
795
 
        {
 
795
    {
796
796
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
797
 
                time_t t;
798
 
                struct tm *p;
799
 
                long janzone, julyzone;
800
 
                char janname[10], julyname[10];
801
 
                t = (time((time_t *)0) / YEAR) * YEAR;
802
 
                p = localtime(&t);
803
 
                janzone = -p->tm_gmtoff;
804
 
                strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
805
 
                janname[9] = '\0';
806
 
                t += YEAR/2;
807
 
                p = localtime(&t);
808
 
                julyzone = -p->tm_gmtoff;
809
 
                strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
810
 
                julyname[9] = '\0';
 
797
        time_t t;
 
798
        struct tm *p;
 
799
        long janzone, julyzone;
 
800
        char janname[10], julyname[10];
 
801
        t = (time((time_t *)0) / YEAR) * YEAR;
 
802
        p = localtime(&t);
 
803
        janzone = -p->tm_gmtoff;
 
804
        strncpy(janname, p->tm_zone ? p->tm_zone : "   ", 9);
 
805
        janname[9] = '\0';
 
806
        t += YEAR/2;
 
807
        p = localtime(&t);
 
808
        julyzone = -p->tm_gmtoff;
 
809
        strncpy(julyname, p->tm_zone ? p->tm_zone : "   ", 9);
 
810
        julyname[9] = '\0';
811
811
 
812
 
                if( janzone < julyzone ) {
813
 
                        /* DST is reversed in the southern hemisphere */
814
 
                        PyModule_AddIntConstant(m, "timezone", julyzone);
815
 
                        PyModule_AddIntConstant(m, "altzone", janzone);
816
 
                        PyModule_AddIntConstant(m, "daylight",
817
 
                                                janzone != julyzone);
818
 
                        PyModule_AddObject(m, "tzname",
819
 
                                           Py_BuildValue("(zz)",
820
 
                                                         julyname, janname));
821
 
                } else {
822
 
                        PyModule_AddIntConstant(m, "timezone", janzone);
823
 
                        PyModule_AddIntConstant(m, "altzone", julyzone);
824
 
                        PyModule_AddIntConstant(m, "daylight",
825
 
                                                janzone != julyzone);
826
 
                        PyModule_AddObject(m, "tzname",
827
 
                                           Py_BuildValue("(zz)",
828
 
                                                         janname, julyname));
829
 
                }
830
 
        }
 
812
        if( janzone < julyzone ) {
 
813
            /* DST is reversed in the southern hemisphere */
 
814
            PyModule_AddIntConstant(m, "timezone", julyzone);
 
815
            PyModule_AddIntConstant(m, "altzone", janzone);
 
816
            PyModule_AddIntConstant(m, "daylight",
 
817
                                    janzone != julyzone);
 
818
            PyModule_AddObject(m, "tzname",
 
819
                               Py_BuildValue("(zz)",
 
820
                                             julyname, janname));
 
821
        } else {
 
822
            PyModule_AddIntConstant(m, "timezone", janzone);
 
823
            PyModule_AddIntConstant(m, "altzone", julyzone);
 
824
            PyModule_AddIntConstant(m, "daylight",
 
825
                                    janzone != julyzone);
 
826
            PyModule_AddObject(m, "tzname",
 
827
                               Py_BuildValue("(zz)",
 
828
                                             janname, julyname));
 
829
        }
 
830
    }
831
831
#else
832
832
#endif /* HAVE_STRUCT_TM_TM_ZONE */
833
833
#ifdef __CYGWIN__
834
 
        tzset();
835
 
        PyModule_AddIntConstant(m, "timezone", _timezone);
836
 
        PyModule_AddIntConstant(m, "altzone", _timezone-3600);
837
 
        PyModule_AddIntConstant(m, "daylight", _daylight);
838
 
        PyModule_AddObject(m, "tzname",
839
 
                           Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
 
834
    tzset();
 
835
    PyModule_AddIntConstant(m, "timezone", _timezone);
 
836
    PyModule_AddIntConstant(m, "altzone", _timezone-3600);
 
837
    PyModule_AddIntConstant(m, "daylight", _daylight);
 
838
    PyModule_AddObject(m, "tzname",
 
839
                       Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
840
840
#endif /* __CYGWIN__ */
841
841
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
842
842
}
843
843
 
844
844
 
845
845
static PyMethodDef time_methods[] = {
846
 
        {"time",        time_time, METH_NOARGS, time_doc},
 
846
    {"time",            time_time, METH_NOARGS, time_doc},
847
847
#ifdef HAVE_CLOCK
848
 
        {"clock",       time_clock, METH_NOARGS, clock_doc},
 
848
    {"clock",           time_clock, METH_NOARGS, clock_doc},
849
849
#endif
850
 
        {"sleep",       time_sleep, METH_VARARGS, sleep_doc},
851
 
        {"gmtime",      time_gmtime, METH_VARARGS, gmtime_doc},
852
 
        {"localtime",   time_localtime, METH_VARARGS, localtime_doc},
853
 
        {"asctime",     time_asctime, METH_VARARGS, asctime_doc},
854
 
        {"ctime",       time_ctime, METH_VARARGS, ctime_doc},
 
850
    {"sleep",           time_sleep, METH_VARARGS, sleep_doc},
 
851
    {"gmtime",          time_gmtime, METH_VARARGS, gmtime_doc},
 
852
    {"localtime",       time_localtime, METH_VARARGS, localtime_doc},
 
853
    {"asctime",         time_asctime, METH_VARARGS, asctime_doc},
 
854
    {"ctime",           time_ctime, METH_VARARGS, ctime_doc},
855
855
#ifdef HAVE_MKTIME
856
 
        {"mktime",      time_mktime, METH_O, mktime_doc},
 
856
    {"mktime",          time_mktime, METH_O, mktime_doc},
857
857
#endif
858
858
#ifdef HAVE_STRFTIME
859
 
        {"strftime",    time_strftime, METH_VARARGS, strftime_doc},
 
859
    {"strftime",        time_strftime, METH_VARARGS, strftime_doc},
860
860
#endif
861
 
        {"strptime",    time_strptime, METH_VARARGS, strptime_doc},
 
861
    {"strptime",        time_strptime, METH_VARARGS, strptime_doc},
862
862
#ifdef HAVE_WORKING_TZSET
863
 
        {"tzset",       time_tzset, METH_NOARGS, tzset_doc},
 
863
    {"tzset",           time_tzset, METH_NOARGS, tzset_doc},
864
864
#endif
865
 
        {NULL,          NULL}           /* sentinel */
 
865
    {NULL,              NULL}           /* sentinel */
866
866
};
867
867
 
868
868
 
914
914
 
915
915
 
916
916
static struct PyModuleDef timemodule = {
917
 
        PyModuleDef_HEAD_INIT,
918
 
        "time",
919
 
        module_doc,
920
 
        -1,
921
 
        time_methods,
922
 
        NULL,
923
 
        NULL,
924
 
        NULL,
925
 
        NULL
 
917
    PyModuleDef_HEAD_INIT,
 
918
    "time",
 
919
    module_doc,
 
920
    -1,
 
921
    time_methods,
 
922
    NULL,
 
923
    NULL,
 
924
    NULL,
 
925
    NULL
926
926
};
927
927
 
928
928
PyMODINIT_FUNC
929
929
PyInit_time(void)
930
930
{
931
 
        PyObject *m;
932
 
        char *p;
933
 
        m = PyModule_Create(&timemodule);
934
 
        if (m == NULL)
935
 
                return NULL;
936
 
 
937
 
        /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
938
 
        p = Py_GETENV("PYTHONY2K");
939
 
        PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
940
 
        /* Squirrel away the module's dictionary for the y2k check */
941
 
        moddict = PyModule_GetDict(m);
942
 
        Py_INCREF(moddict);
943
 
 
944
 
        /* Set, or reset, module variables like time.timezone */
945
 
        PyInit_timezone(m);
 
931
    PyObject *m;
 
932
    char *p;
 
933
    m = PyModule_Create(&timemodule);
 
934
    if (m == NULL)
 
935
        return NULL;
 
936
 
 
937
    /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
 
938
    p = Py_GETENV("PYTHONY2K");
 
939
    PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
 
940
    /* Squirrel away the module's dictionary for the y2k check */
 
941
    moddict = PyModule_GetDict(m);
 
942
    Py_INCREF(moddict);
 
943
 
 
944
    /* Set, or reset, module variables like time.timezone */
 
945
    PyInit_timezone(m);
946
946
 
947
947
#ifdef MS_WINDOWS
948
 
        /* Helper to allow interrupts for Windows.
949
 
           If Ctrl+C event delivered while not sleeping
950
 
           it will be ignored.
951
 
        */
952
 
        main_thread = PyThread_get_thread_ident();
953
 
        hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
954
 
        SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
 
948
    /* Helper to allow interrupts for Windows.
 
949
       If Ctrl+C event delivered while not sleeping
 
950
       it will be ignored.
 
951
    */
 
952
    main_thread = PyThread_get_thread_ident();
 
953
    hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
 
954
    SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
955
955
#endif /* MS_WINDOWS */
956
 
        if (!initialized) {
957
 
                PyStructSequence_InitType(&StructTimeType,
958
 
                                          &struct_time_type_desc);
959
 
        }
960
 
        Py_INCREF(&StructTimeType);
961
 
        PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
962
 
        initialized = 1;
963
 
        return m;
 
956
    if (!initialized) {
 
957
        PyStructSequence_InitType(&StructTimeType,
 
958
                                  &struct_time_type_desc);
 
959
    }
 
960
    Py_INCREF(&StructTimeType);
 
961
    PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
 
962
    initialized = 1;
 
963
    return m;
964
964
}
965
965
 
966
966
 
969
969
static double
970
970
floattime(void)
971
971
{
972
 
        /* There are three ways to get the time:
973
 
          (1) gettimeofday() -- resolution in microseconds
974
 
          (2) ftime() -- resolution in milliseconds
975
 
          (3) time() -- resolution in seconds
976
 
          In all cases the return value is a float in seconds.
977
 
          Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
978
 
          fail, so we fall back on ftime() or time().
979
 
          Note: clock resolution does not imply clock accuracy! */
 
972
    /* There are three ways to get the time:
 
973
      (1) gettimeofday() -- resolution in microseconds
 
974
      (2) ftime() -- resolution in milliseconds
 
975
      (3) time() -- resolution in seconds
 
976
      In all cases the return value is a float in seconds.
 
977
      Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
 
978
      fail, so we fall back on ftime() or time().
 
979
      Note: clock resolution does not imply clock accuracy! */
980
980
#ifdef HAVE_GETTIMEOFDAY
981
 
        {
982
 
                struct timeval t;
 
981
    {
 
982
        struct timeval t;
983
983
#ifdef GETTIMEOFDAY_NO_TZ
984
 
                if (gettimeofday(&t) == 0)
985
 
                        return (double)t.tv_sec + t.tv_usec*0.000001;
 
984
        if (gettimeofday(&t) == 0)
 
985
            return (double)t.tv_sec + t.tv_usec*0.000001;
986
986
#else /* !GETTIMEOFDAY_NO_TZ */
987
 
                if (gettimeofday(&t, (struct timezone *)NULL) == 0)
988
 
                        return (double)t.tv_sec + t.tv_usec*0.000001;
 
987
        if (gettimeofday(&t, (struct timezone *)NULL) == 0)
 
988
            return (double)t.tv_sec + t.tv_usec*0.000001;
989
989
#endif /* !GETTIMEOFDAY_NO_TZ */
990
 
        }
 
990
    }
991
991
 
992
992
#endif /* !HAVE_GETTIMEOFDAY */
993
 
        {
 
993
    {
994
994
#if defined(HAVE_FTIME)
995
 
                struct timeb t;
996
 
                ftime(&t);
997
 
                return (double)t.time + (double)t.millitm * (double)0.001;
 
995
        struct timeb t;
 
996
        ftime(&t);
 
997
        return (double)t.time + (double)t.millitm * (double)0.001;
998
998
#else /* !HAVE_FTIME */
999
 
                time_t secs;
1000
 
                time(&secs);
1001
 
                return (double)secs;
 
999
        time_t secs;
 
1000
        time(&secs);
 
1001
        return (double)secs;
1002
1002
#endif /* !HAVE_FTIME */
1003
 
        }
 
1003
    }
1004
1004
}
1005
1005
 
1006
1006
 
1013
1013
{
1014
1014
/* XXX Should test for MS_WINDOWS first! */
1015
1015
#if defined(HAVE_SELECT) && !defined(__EMX__)
1016
 
        struct timeval t;
1017
 
        double frac;
1018
 
        frac = fmod(secs, 1.0);
1019
 
        secs = floor(secs);
1020
 
        t.tv_sec = (long)secs;
1021
 
        t.tv_usec = (long)(frac*1000000.0);
1022
 
        Py_BEGIN_ALLOW_THREADS
1023
 
        if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
 
1016
    struct timeval t;
 
1017
    double frac;
 
1018
    frac = fmod(secs, 1.0);
 
1019
    secs = floor(secs);
 
1020
    t.tv_sec = (long)secs;
 
1021
    t.tv_usec = (long)(frac*1000000.0);
 
1022
    Py_BEGIN_ALLOW_THREADS
 
1023
    if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
1024
1024
#ifdef EINTR
1025
 
                if (errno != EINTR) {
 
1025
        if (errno != EINTR) {
1026
1026
#else
1027
 
                if (1) {
 
1027
        if (1) {
1028
1028
#endif
1029
 
                        Py_BLOCK_THREADS
1030
 
                        PyErr_SetFromErrno(PyExc_IOError);
1031
 
                        return -1;
1032
 
                }
1033
 
        }
1034
 
        Py_END_ALLOW_THREADS
 
1029
            Py_BLOCK_THREADS
 
1030
            PyErr_SetFromErrno(PyExc_IOError);
 
1031
            return -1;
 
1032
        }
 
1033
    }
 
1034
    Py_END_ALLOW_THREADS
1035
1035
#elif defined(__WATCOMC__) && !defined(__QNX__)
1036
 
        /* XXX Can't interrupt this sleep */
1037
 
        Py_BEGIN_ALLOW_THREADS
1038
 
        delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
1039
 
        Py_END_ALLOW_THREADS
 
1036
    /* XXX Can't interrupt this sleep */
 
1037
    Py_BEGIN_ALLOW_THREADS
 
1038
    delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
 
1039
    Py_END_ALLOW_THREADS
1040
1040
#elif defined(MS_WINDOWS)
1041
 
        {
1042
 
                double millisecs = secs * 1000.0;
1043
 
                unsigned long ul_millis;
 
1041
    {
 
1042
        double millisecs = secs * 1000.0;
 
1043
        unsigned long ul_millis;
1044
1044
 
1045
 
                if (millisecs > (double)ULONG_MAX) {
1046
 
                        PyErr_SetString(PyExc_OverflowError,
1047
 
                                        "sleep length is too large");
1048
 
                        return -1;
1049
 
                }
1050
 
                Py_BEGIN_ALLOW_THREADS
1051
 
                /* Allow sleep(0) to maintain win32 semantics, and as decreed
1052
 
                 * by Guido, only the main thread can be interrupted.
1053
 
                 */
1054
 
                ul_millis = (unsigned long)millisecs;
1055
 
                if (ul_millis == 0 ||
1056
 
                    main_thread != PyThread_get_thread_ident())
1057
 
                        Sleep(ul_millis);
1058
 
                else {
1059
 
                        DWORD rc;
1060
 
                        ResetEvent(hInterruptEvent);
1061
 
                        rc = WaitForSingleObject(hInterruptEvent, ul_millis);
1062
 
                        if (rc == WAIT_OBJECT_0) {
1063
 
                                /* Yield to make sure real Python signal
1064
 
                                 * handler called.
1065
 
                                 */
1066
 
                                Sleep(1);
1067
 
                                Py_BLOCK_THREADS
1068
 
                                errno = EINTR;
1069
 
                                PyErr_SetFromErrno(PyExc_IOError);
1070
 
                                return -1;
1071
 
                        }
1072
 
                }
1073
 
                Py_END_ALLOW_THREADS
1074
 
        }
 
1045
        if (millisecs > (double)ULONG_MAX) {
 
1046
            PyErr_SetString(PyExc_OverflowError,
 
1047
                            "sleep length is too large");
 
1048
            return -1;
 
1049
        }
 
1050
        Py_BEGIN_ALLOW_THREADS
 
1051
        /* Allow sleep(0) to maintain win32 semantics, and as decreed
 
1052
         * by Guido, only the main thread can be interrupted.
 
1053
         */
 
1054
        ul_millis = (unsigned long)millisecs;
 
1055
        if (ul_millis == 0 ||
 
1056
            main_thread != PyThread_get_thread_ident())
 
1057
            Sleep(ul_millis);
 
1058
        else {
 
1059
            DWORD rc;
 
1060
            ResetEvent(hInterruptEvent);
 
1061
            rc = WaitForSingleObject(hInterruptEvent, ul_millis);
 
1062
            if (rc == WAIT_OBJECT_0) {
 
1063
                /* Yield to make sure real Python signal
 
1064
                 * handler called.
 
1065
                 */
 
1066
                Sleep(1);
 
1067
                Py_BLOCK_THREADS
 
1068
                errno = EINTR;
 
1069
                PyErr_SetFromErrno(PyExc_IOError);
 
1070
                return -1;
 
1071
            }
 
1072
        }
 
1073
        Py_END_ALLOW_THREADS
 
1074
    }
1075
1075
#elif defined(PYOS_OS2)
1076
 
        /* This Sleep *IS* Interruptable by Exceptions */
1077
 
        Py_BEGIN_ALLOW_THREADS
1078
 
        if (DosSleep(secs * 1000) != NO_ERROR) {
1079
 
                Py_BLOCK_THREADS
1080
 
                PyErr_SetFromErrno(PyExc_IOError);
1081
 
                return -1;
1082
 
        }
1083
 
        Py_END_ALLOW_THREADS
 
1076
    /* This Sleep *IS* Interruptable by Exceptions */
 
1077
    Py_BEGIN_ALLOW_THREADS
 
1078
    if (DosSleep(secs * 1000) != NO_ERROR) {
 
1079
        Py_BLOCK_THREADS
 
1080
        PyErr_SetFromErrno(PyExc_IOError);
 
1081
        return -1;
 
1082
    }
 
1083
    Py_END_ALLOW_THREADS
1084
1084
#elif defined(PLAN9)
1085
 
        {
1086
 
                double millisecs = secs * 1000.0;
1087
 
                if (millisecs > (double)LONG_MAX) {
1088
 
                        PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
1089
 
                        return -1;
1090
 
                }
1091
 
                /* This sleep *CAN BE* interrupted. */
1092
 
                Py_BEGIN_ALLOW_THREADS
1093
 
                if(sleep((long)millisecs) < 0){
1094
 
                        Py_BLOCK_THREADS
1095
 
                        PyErr_SetFromErrno(PyExc_IOError);
1096
 
                        return -1;
1097
 
                }
1098
 
                Py_END_ALLOW_THREADS
1099
 
        }
 
1085
    {
 
1086
        double millisecs = secs * 1000.0;
 
1087
        if (millisecs > (double)LONG_MAX) {
 
1088
            PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
 
1089
            return -1;
 
1090
        }
 
1091
        /* This sleep *CAN BE* interrupted. */
 
1092
        Py_BEGIN_ALLOW_THREADS
 
1093
        if(sleep((long)millisecs) < 0){
 
1094
            Py_BLOCK_THREADS
 
1095
            PyErr_SetFromErrno(PyExc_IOError);
 
1096
            return -1;
 
1097
        }
 
1098
        Py_END_ALLOW_THREADS
 
1099
    }
1100
1100
#else
1101
 
        /* XXX Can't interrupt this sleep */
1102
 
        Py_BEGIN_ALLOW_THREADS
1103
 
        sleep((int)secs);
1104
 
        Py_END_ALLOW_THREADS
 
1101
    /* XXX Can't interrupt this sleep */
 
1102
    Py_BEGIN_ALLOW_THREADS
 
1103
    sleep((int)secs);
 
1104
    Py_END_ALLOW_THREADS
1105
1105
#endif
1106
1106
 
1107
 
        return 0;
 
1107
    return 0;
1108
1108
}