-
Notifications
You must be signed in to change notification settings - Fork 269
/
wsgi_interp.c
2813 lines (2285 loc) · 88.9 KB
/
wsgi_interp.c
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ------------------------------------------------------------------------- */
/*
* Copyright 2007-2024 GRAHAM DUMPLETON
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* ------------------------------------------------------------------------- */
#include "wsgi_interp.h"
#include "wsgi_version.h"
#include "wsgi_apache.h"
#include "wsgi_server.h"
#include "wsgi_logger.h"
#include "wsgi_restrict.h"
#include "wsgi_stream.h"
#include "wsgi_metrics.h"
#include "wsgi_daemon.h"
#include "wsgi_metrics.h"
#include "wsgi_thread.h"
#if APR_HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifndef WIN32
#include <pwd.h>
#endif
/* ------------------------------------------------------------------------- */
/* Function to restrict access to use of signal(). */
static void SignalIntercept_dealloc(SignalInterceptObject *self)
{
Py_DECREF(self->wrapped);
}
static SignalInterceptObject *newSignalInterceptObject(PyObject *wrapped)
{
SignalInterceptObject *self = NULL;
self = PyObject_New(SignalInterceptObject, &SignalIntercept_Type);
if (self == NULL)
return NULL;
Py_INCREF(wrapped);
self->wrapped = wrapped;
return self;
}
static PyObject *SignalIntercept_call(
SignalInterceptObject *self, PyObject *args, PyObject *kwds)
{
PyObject *h = NULL;
int n = 0;
PyObject *m = NULL;
if (wsgi_daemon_pid != 0 && wsgi_daemon_pid != getpid())
return PyObject_Call(self->wrapped, args, kwds);
if (wsgi_worker_pid != 0 && wsgi_worker_pid != getpid())
return PyObject_Call(self->wrapped, args, kwds);
if (!PyArg_ParseTuple(args, "iO:signal", &n, &h))
return NULL;
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_WARNING, 0, wsgi_server,
"mod_wsgi (pid=%d): Callback registration for "
"signal %d ignored.", getpid(), n);
Py_END_ALLOW_THREADS
m = PyImport_ImportModule("traceback");
if (m) {
PyObject *d = NULL;
PyObject *o = NULL;
d = PyModule_GetDict(m);
o = PyDict_GetItemString(d, "print_stack");
if (o) {
PyObject *log = NULL;
PyObject *args = NULL;
PyObject *result = NULL;
Py_INCREF(o);
log = newLogObject(NULL, APLOG_WARNING, NULL, 0);
args = Py_BuildValue("(OOO)", Py_None, Py_None, log);
result = PyObject_CallObject(o, args);
Py_XDECREF(result);
Py_DECREF(args);
Py_DECREF(log);
Py_DECREF(o);
}
}
Py_XDECREF(m);
Py_INCREF(h);
return h;
}
PyTypeObject SignalIntercept_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mod_wsgi.SignalIntercept", /*tp_name*/
sizeof(SignalInterceptObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)SignalIntercept_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
(ternaryfunc)SignalIntercept_call, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
/* ------------------------------------------------------------------------- */
static PyObject *wsgi_system_exit(PyObject *self, PyObject *args)
{
PyErr_SetObject(PyExc_SystemExit, 0);
return NULL;
}
/* ------------------------------------------------------------------------- */
static PyMethodDef wsgi_system_exit_method[] = {
{ "system_exit", (PyCFunction)wsgi_system_exit, METH_VARARGS, 0 },
{ NULL },
};
/* ------------------------------------------------------------------------- */
/* Wrapper around Python interpreter instances. */
const char *wsgi_python_path = NULL;
const char *wsgi_python_eggs = NULL;
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4)
static void ShutdownInterpreter_dealloc(ShutdownInterpreterObject *self)
{
Py_DECREF(self->wrapped);
}
static ShutdownInterpreterObject *newShutdownInterpreterObject(
PyObject *wrapped)
{
ShutdownInterpreterObject *self = NULL;
self = PyObject_New(ShutdownInterpreterObject, &ShutdownInterpreter_Type);
if (self == NULL)
return NULL;
Py_INCREF(wrapped);
self->wrapped = wrapped;
return self;
}
static PyObject *ShutdownInterpreter_call(
ShutdownInterpreterObject *self, PyObject *args, PyObject *kwds)
{
PyObject *result = NULL;
result = PyObject_Call(self->wrapped, args, kwds);
if (result) {
PyObject *module = NULL;
PyObject *exitfunc = NULL;
PyThreadState *tstate = PyThreadState_Get();
PyThreadState *tstate_save = tstate;
PyThreadState *tstate_next = NULL;
#if PY_MAJOR_VERSION >= 3
module = PyImport_ImportModule("atexit");
if (module) {
PyObject *dict = NULL;
dict = PyModule_GetDict(module);
exitfunc = PyDict_GetItemString(dict, "_run_exitfuncs");
}
else
PyErr_Clear();
#else
exitfunc = PySys_GetObject("exitfunc");
#endif
if (exitfunc) {
PyObject *res = NULL;
Py_INCREF(exitfunc);
PySys_SetObject("exitfunc", (PyObject *)NULL);
res = PyObject_CallObject(exitfunc, (PyObject *)NULL);
if (res == NULL) {
PyObject *m = NULL;
PyObject *result = NULL;
PyObject *type = NULL;
PyObject *value = NULL;
PyObject *traceback = NULL;
if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
"mod_wsgi (pid=%d): SystemExit exception "
"raised by exit functions ignored.", getpid());
Py_END_ALLOW_THREADS
}
else {
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
"mod_wsgi (pid=%d): Exception occurred within "
"exit functions.", getpid());
Py_END_ALLOW_THREADS
}
PyErr_Fetch(&type, &value, &traceback);
PyErr_NormalizeException(&type, &value, &traceback);
if (!value) {
value = Py_None;
Py_INCREF(value);
}
if (!traceback) {
traceback = Py_None;
Py_INCREF(traceback);
}
m = PyImport_ImportModule("traceback");
if (m) {
PyObject *d = NULL;
PyObject *o = NULL;
d = PyModule_GetDict(m);
o = PyDict_GetItemString(d, "print_exception");
if (o) {
PyObject *log = NULL;
PyObject *args = NULL;
Py_INCREF(o);
log = newLogObject(NULL, APLOG_ERR, NULL, 0);
args = Py_BuildValue("(OOOOO)", type, value,
traceback, Py_None, log);
result = PyObject_CallObject(o, args);
Py_DECREF(args);
Py_DECREF(log);
Py_DECREF(o);
}
}
if (!result) {
/*
* If can't output exception and traceback then
* use PyErr_Print to dump out details of the
* exception. For SystemExit though if we do
* that the process will actually be terminated
* so can only clear the exception information
* and keep going.
*/
PyErr_Restore(type, value, traceback);
if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
PyErr_Print();
PyErr_Clear();
}
else {
PyErr_Clear();
}
}
else {
Py_XDECREF(type);
Py_XDECREF(value);
Py_XDECREF(traceback);
}
Py_XDECREF(result);
Py_XDECREF(m);
}
Py_XDECREF(res);
Py_DECREF(exitfunc);
}
Py_XDECREF(module);
/* Delete remaining thread states. */
PyThreadState_Swap(NULL);
tstate = PyInterpreterState_ThreadHead(tstate->interp);
while (tstate) {
tstate_next = PyThreadState_Next(tstate);
if (tstate != tstate_save) {
PyThreadState_Swap(tstate);
PyThreadState_Clear(tstate);
PyThreadState_Swap(NULL);
PyThreadState_Delete(tstate);
}
tstate = tstate_next;
}
tstate = tstate_save;
PyThreadState_Swap(tstate);
}
return result;
}
PyTypeObject ShutdownInterpreter_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"mod_wsgi.ShutdownInterpreter", /*tp_name*/
sizeof(ShutdownInterpreterObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)ShutdownInterpreter_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
(ternaryfunc)ShutdownInterpreter_call, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
};
#endif
PyTypeObject Interpreter_Type;
InterpreterObject *newInterpreterObject(const char *name)
{
PyInterpreterState *interp = NULL;
InterpreterObject *self = NULL;
PyThreadState *tstate = NULL;
PyThreadState *save_tstate = NULL;
PyObject *module = NULL;
PyObject *object = NULL;
PyObject *item = NULL;
int max_threads = 0;
int max_processes = 0;
int is_threaded = 0;
int is_forked = 0;
int is_service_script = 0;
const char *str = NULL;
#if defined(WIN32)
const char *python_home = 0;
#endif
/* Create handle for interpreter and local data. */
self = PyObject_New(InterpreterObject, &Interpreter_Type);
if (self == NULL)
return NULL;
/*
* If interpreter not named, then we want to bind
* to the first Python interpreter instance created.
* Give this interpreter an empty string as name.
*/
if (!name) {
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7)
interp = PyInterpreterState_Main();
#else
interp = PyInterpreterState_Head();
while (PyInterpreterState_Next(interp))
interp = PyInterpreterState_Next(interp);
#endif
name = "";
}
/* Save away the interpreter name. */
self->name = strdup(name);
if (interp) {
/*
* Interpreter provided to us so will not be
* responsible for deleting it later. This will
* be the case for the main Python interpreter.
*/
ap_log_error(APLOG_MARK, APLOG_INFO, 0, wsgi_server,
"mod_wsgi (pid=%d): Attach interpreter '%s'.",
getpid(), name);
self->interp = interp;
self->owner = 0;
/* Force import of threading module so that main
* thread attribute of module is correctly set to
* the main thread and not a secondary request
* thread.
*/
module = PyImport_ImportModule("threading");
Py_XDECREF(module);
}
else {
/*
* Remember active thread state so can restore
* it. This is actually the thread state
* associated with simplified GIL state API.
*/
save_tstate = PyThreadState_Swap(NULL);
/*
* Create the interpreter. If creation of the
* interpreter fails it will restore the
* existing active thread state for us so don't
* need to worry about it in that case.
*/
tstate = Py_NewInterpreter();
if (!tstate) {
PyErr_SetString(PyExc_RuntimeError, "Py_NewInterpreter() failed");
Py_DECREF(self);
return NULL;
}
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_INFO, 0, wsgi_server,
"mod_wsgi (pid=%d): Create interpreter '%s'.",
getpid(), name);
Py_END_ALLOW_THREADS
self->interp = tstate->interp;
self->owner = 1;
/*
* We need to replace threading._shutdown() with our own
* function which will also call atexit callbacks after
* threads are shutdown to cope with fact that Python
* itself doesn't call the atexit callbacks in sub
* interpreters.
*/
module = PyImport_ImportModule("threading");
#if PY_MAJOR_VERSION > 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4)
if (module) {
PyObject *dict = NULL;
PyObject *func = NULL;
dict = PyModule_GetDict(module);
func = PyDict_GetItemString(dict, "_shutdown");
if (func) {
PyObject *wrapper = NULL;
wrapper = (PyObject *)newShutdownInterpreterObject(func);
PyDict_SetItemString(dict, "_shutdown", wrapper);
Py_DECREF(wrapper);
}
}
#endif
Py_XDECREF(module);
}
/*
* Install restricted objects for STDIN and STDOUT,
* or log object for STDOUT as appropriate. Don't do
* this if not running on Win32 and we believe we
* are running in single process mode, otherwise
* it prevents use of interactive debuggers such as
* the 'pdb' module.
*/
object = newLogObject(NULL, APLOG_ERR, "<stderr>", 1);
PySys_SetObject("stderr", object);
Py_DECREF(object);
#ifndef WIN32
if (wsgi_parent_pid != getpid()) {
#endif
if (wsgi_server_config->restrict_stdout == 1) {
object = (PyObject *)newRestrictedObject("sys.stdout");
PySys_SetObject("stdout", object);
Py_DECREF(object);
}
else {
object = newLogObject(NULL, APLOG_ERR, "<stdout>", 1);
PySys_SetObject("stdout", object);
Py_DECREF(object);
}
if (wsgi_server_config->restrict_stdin == 1) {
object = (PyObject *)newRestrictedObject("sys.stdin");
PySys_SetObject("stdin", object);
Py_DECREF(object);
}
#ifndef WIN32
}
#endif
/*
* Set sys.argv to one element list to fake out
* modules that look there for Python command
* line arguments as appropriate.
*/
object = PyList_New(0);
#if PY_MAJOR_VERSION >= 3
item = PyUnicode_FromString("mod_wsgi");
#else
item = PyString_FromString("mod_wsgi");
#endif
PyList_Append(object, item);
PySys_SetObject("argv", object);
Py_DECREF(item);
Py_DECREF(object);
/*
* Install intercept for signal handler registration
* if appropriate. Don't do this though if number of
* threads for daemon process was set as 0, indicating
* a potential daemon process which is running a
* service script.
*/
/*
* If running in daemon mode and there are no threads
* specified, must be running with service script, in
* which case we register default signal handler for
* SIGINT which throws a SystemExit exception. If
* instead restricting signals, replace function for
* registering signal handlers so they are ignored.
*/
#if defined(MOD_WSGI_WITH_DAEMONS)
if (wsgi_daemon_process && wsgi_daemon_process->group->threads == 0) {
is_service_script = 1;
module = PyImport_ImportModule("signal");
if (module) {
PyObject *dict = NULL;
PyObject *func = NULL;
dict = PyModule_GetDict(module);
func = PyDict_GetItemString(dict, "signal");
if (func) {
PyObject *res = NULL;
PyObject *args = NULL;
PyObject *callback = NULL;
Py_INCREF(func);
callback = PyCFunction_New(&wsgi_system_exit_method[0], NULL);
args = Py_BuildValue("(iO)", SIGTERM, callback);
res = PyObject_CallObject(func, args);
if (!res) {
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
"mod_wsgi (pid=%d): Call to "
"'signal.signal()' to register exit "
"function failed, ignoring.", getpid());
Py_END_ALLOW_THREADS
}
Py_XDECREF(res);
Py_XDECREF(args);
Py_XDECREF(callback);
Py_DECREF(func);
}
}
Py_XDECREF(module);
}
#endif
if (!is_service_script && wsgi_server_config->restrict_signal != 0) {
module = PyImport_ImportModule("signal");
if (module) {
PyObject *dict = NULL;
PyObject *func = NULL;
dict = PyModule_GetDict(module);
func = PyDict_GetItemString(dict, "signal");
if (func) {
PyObject *wrapper = NULL;
wrapper = (PyObject *)newSignalInterceptObject(func);
PyDict_SetItemString(dict, "signal", wrapper);
Py_DECREF(wrapper);
}
}
Py_XDECREF(module);
}
/*
* Force loading of codecs into interpreter. This has to be
* done as not otherwise done in sub interpreters and if not
* done, code running in sub interpreters can fail on some
* platforms if a unicode string is added in sys.path and an
* import then done.
*/
item = PyCodec_Encoder("ascii");
Py_XDECREF(item);
/*
* If running in daemon process, override as appropriate
* the USER, USERNAME or LOGNAME environment variables
* so that they match the user that the process is running
* as. Need to do this else we inherit the value from the
* Apache parent process which is likely wrong as will be
* root or the user than ran sudo when Apache started.
* Can't update these for normal Apache child processes
* as that would change the expected environment of other
* Apache modules.
*/
#ifndef WIN32
if (wsgi_daemon_pool) {
module = PyImport_ImportModule("os");
if (module) {
PyObject *dict = NULL;
PyObject *key = NULL;
PyObject *value = NULL;
dict = PyModule_GetDict(module);
object = PyDict_GetItemString(dict, "environ");
if (object) {
struct passwd *pwent;
pwent = getpwuid(geteuid());
if (pwent && getenv("USER")) {
#if PY_MAJOR_VERSION >= 3
key = PyUnicode_FromString("USER");
value = PyUnicode_Decode(pwent->pw_name,
strlen(pwent->pw_name),
Py_FileSystemDefaultEncoding,
"surrogateescape");
#else
key = PyString_FromString("USER");
value = PyString_FromString(pwent->pw_name);
#endif
PyObject_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
if (pwent && getenv("USERNAME")) {
#if PY_MAJOR_VERSION >= 3
key = PyUnicode_FromString("USERNAME");
value = PyUnicode_Decode(pwent->pw_name,
strlen(pwent->pw_name),
Py_FileSystemDefaultEncoding,
"surrogateescape");
#else
key = PyString_FromString("USERNAME");
value = PyString_FromString(pwent->pw_name);
#endif
PyObject_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
if (pwent && getenv("LOGNAME")) {
#if PY_MAJOR_VERSION >= 3
key = PyUnicode_FromString("LOGNAME");
value = PyUnicode_Decode(pwent->pw_name,
strlen(pwent->pw_name),
Py_FileSystemDefaultEncoding,
"surrogateescape");
#else
key = PyString_FromString("LOGNAME");
value = PyString_FromString(pwent->pw_name);
#endif
PyObject_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
}
Py_DECREF(module);
}
}
#endif
/*
* If running in daemon process, override HOME environment
* variable so that is matches the home directory of the
* user that the process is running as. Need to do this as
* Apache will inherit HOME from root user or user that ran
* sudo and started Apache and this would be wrong. Can't
* update HOME for normal Apache child processes as that
* would change the expected environment of other Apache
* modules.
*/
#ifndef WIN32
if (wsgi_daemon_pool) {
module = PyImport_ImportModule("os");
if (module) {
PyObject *dict = NULL;
PyObject *key = NULL;
PyObject *value = NULL;
dict = PyModule_GetDict(module);
object = PyDict_GetItemString(dict, "environ");
if (object) {
struct passwd *pwent;
pwent = getpwuid(geteuid());
if (pwent) {
#if PY_MAJOR_VERSION >= 3
key = PyUnicode_FromString("HOME");
value = PyUnicode_Decode(pwent->pw_dir,
strlen(pwent->pw_dir),
Py_FileSystemDefaultEncoding,
"surrogateescape");
#else
key = PyString_FromString("HOME");
value = PyString_FromString(pwent->pw_dir);
#endif
PyObject_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
}
Py_DECREF(module);
}
}
#endif
/*
* Explicitly override the PYTHON_EGG_CACHE variable if it
* was defined by Apache configuration. For embedded processes
* this would have been done by using WSGIPythonEggs directive.
* For daemon processes the 'python-eggs' option to the
* WSGIDaemonProcess directive would have needed to be used.
*/
if (!wsgi_daemon_pool)
wsgi_python_eggs = wsgi_server_config->python_eggs;
if (wsgi_python_eggs) {
module = PyImport_ImportModule("os");
if (module) {
PyObject *dict = NULL;
PyObject *key = NULL;
PyObject *value = NULL;
dict = PyModule_GetDict(module);
object = PyDict_GetItemString(dict, "environ");
if (object) {
#if PY_MAJOR_VERSION >= 3
key = PyUnicode_FromString("PYTHON_EGG_CACHE");
value = PyUnicode_Decode(wsgi_python_eggs,
strlen(wsgi_python_eggs),
Py_FileSystemDefaultEncoding,
"surrogateescape");
#else
key = PyString_FromString("PYTHON_EGG_CACHE");
value = PyString_FromString(wsgi_python_eggs);
#endif
PyObject_SetItem(object, key, value);
Py_DECREF(key);
Py_DECREF(value);
}
Py_DECREF(module);
}
}
/*
* Install user defined Python module search path. This is
* added using site.addsitedir() so that any Python .pth
* files are opened and additional directories so defined
* are added to default Python search path as well. This
* allows virtual Python environments to work. Note that
* site.addsitedir() adds new directories at the end of
* sys.path when they really need to be added in order at
* the start. We therefore need to do a fiddle and shift
* any newly added directories to the start of sys.path.
*/
if (!wsgi_daemon_pool)
wsgi_python_path = wsgi_server_config->python_path;
/*
* We use a hack here on Windows to add the site-packages
* directory into the Python module search path as well
* as use of Python virtual environments doesn't work
* otherwise if using 'python -m venv' or any released of
* 'virtualenv' from 20.x onwards.
*/
#if defined(WIN32)
python_home = wsgi_server_config->python_home;
if (python_home && *python_home) {
if (wsgi_python_path && *wsgi_python_path) {
char delim[2];
delim[0] = DELIM;
delim[1] = '\0';
wsgi_python_path = apr_pstrcat(wsgi_server->process->pool,
python_home, "/Lib/site-packages", delim,
wsgi_python_path, NULL);
}
else {
wsgi_python_path = apr_pstrcat(wsgi_server->process->pool,
python_home, "/Lib/site-packages", NULL);
}
}
#endif
module = PyImport_ImportModule("site");
if (wsgi_python_path && *wsgi_python_path) {
PyObject *path = NULL;
path = PySys_GetObject("path");
if (module && path) {
PyObject *dict = NULL;
PyObject *old = NULL;
PyObject *new = NULL;
PyObject *tmp = NULL;
PyObject *item = NULL;
int i = 0;
old = PyList_New(0);
new = PyList_New(0);
tmp = PyList_New(0);
for (i=0; i<PyList_Size(path); i++)
PyList_Append(old, PyList_GetItem(path, i));
dict = PyModule_GetDict(module);
object = PyDict_GetItemString(dict, "addsitedir");
if (object) {
const char *start;
const char *end;
const char *value;
PyObject *item;
PyObject *args;
PyObject *result = NULL;
Py_INCREF(object);
start = wsgi_python_path;
end = strchr(start, DELIM);
if (end) {
#if PY_MAJOR_VERSION >= 3
item = PyUnicode_DecodeFSDefaultAndSize(start, end-start);
value = PyUnicode_AsUTF8(item);
#else
item = PyString_FromStringAndSize(start, end-start);
value = PyString_AsString(item);
#endif
start = end+1;
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_INFO, 0, wsgi_server,
"mod_wsgi (pid=%d): Adding '%s' to "
"path.", getpid(), value);
Py_END_ALLOW_THREADS
args = Py_BuildValue("(O)", item);
result = PyObject_CallObject(object, args);
if (!result) {
Py_BEGIN_ALLOW_THREADS
ap_log_error(APLOG_MARK, APLOG_ERR, 0, wsgi_server,
"mod_wsgi (pid=%d): Call to "
"'site.addsitedir()' failed for '%s', "
"stopping.", getpid(), value);
Py_END_ALLOW_THREADS
}
Py_XDECREF(result);
Py_DECREF(item);
Py_DECREF(args);