]> git.saurik.com Git - wxWidgets.git/blob - src/unix/utilsunx.cpp
888eb203af989ca0f980371c487d092afde95596
[wxWidgets.git] / src / unix / utilsunx.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: utilsunx.cpp
3 // Purpose: generic Unix implementation of many wx functions
4 // Author: Vadim Zeitlin
5 // Id: $Id$
6 // Copyright: (c) 1998 Robert Roebling, Vadim Zeitlin
7 // Licence: wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // ============================================================================
11 // declarations
12 // ============================================================================
13
14 // ----------------------------------------------------------------------------
15 // headers
16 // ----------------------------------------------------------------------------
17
18 #include "wx/defs.h"
19 #include "wx/string.h"
20
21 #include "wx/intl.h"
22 #include "wx/log.h"
23 #include "wx/app.h"
24
25 #include "wx/utils.h"
26 #include "wx/process.h"
27 #include "wx/thread.h"
28
29 #include "wx/stream.h"
30
31 #ifdef HAVE_STATFS
32 #include <sys/vfs.h>
33 #endif // HAVE_STATFS
34
35 #if wxUSE_GUI
36 #include "wx/unix/execute.h"
37 #endif
38
39 // SGI signal.h defines signal handler arguments differently depending on
40 // whether _LANGUAGE_C_PLUS_PLUS is set or not - do set it
41 #if defined(__SGI__) && !defined(_LANGUAGE_C_PLUS_PLUS)
42 #define _LANGUAGE_C_PLUS_PLUS 1
43 #endif // SGI hack
44
45 #include <stdarg.h>
46 #include <dirent.h>
47 #include <string.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <unistd.h>
51 #include <sys/wait.h>
52 #include <pwd.h>
53 #include <errno.h>
54 #include <netdb.h>
55 #include <signal.h>
56 #include <fcntl.h> // for O_WRONLY and friends
57 #include <time.h> // nanosleep() and/or usleep()
58 #include <ctype.h> // isspace()
59 #include <sys/time.h> // needed for FD_SETSIZE
60
61 #ifdef HAVE_UNAME
62 #include <sys/utsname.h> // for uname()
63 #endif // HAVE_UNAME
64
65 // ----------------------------------------------------------------------------
66 // conditional compilation
67 // ----------------------------------------------------------------------------
68
69 // many versions of Unices have this function, but it is not defined in system
70 // headers - please add your system here if it is the case for your OS.
71 // SunOS < 5.6 (i.e. Solaris < 2.6) and DG-UX are like this.
72 #if !defined(HAVE_USLEEP) && \
73 (defined(__SUN__) && !defined(__SunOs_5_6) && \
74 !defined(__SunOs_5_7) && !defined(__SUNPRO_CC)) || \
75 defined(__osf__) || defined(__EMX__)
76 extern "C"
77 {
78 #ifdef __SUN__
79 int usleep(unsigned int usec);
80 #else // !Sun
81 #ifdef __EMX__
82 /* I copied this from the XFree86 diffs. AV. */
83 #define INCL_DOSPROCESS
84 #include <os2.h>
85 inline void usleep(unsigned long delay)
86 {
87 DosSleep(delay ? (delay/1000l) : 1l);
88 }
89 #else // !Sun && !EMX
90 void usleep(unsigned long usec);
91 #endif
92 #endif // Sun/EMX/Something else
93 };
94
95 #define HAVE_USLEEP 1
96 #endif // Unices without usleep()
97
98 // ============================================================================
99 // implementation
100 // ============================================================================
101
102 // ----------------------------------------------------------------------------
103 // sleeping
104 // ----------------------------------------------------------------------------
105
106 void wxSleep(int nSecs)
107 {
108 sleep(nSecs);
109 }
110
111 void wxUsleep(unsigned long milliseconds)
112 {
113 #if defined(HAVE_NANOSLEEP)
114 timespec tmReq;
115 tmReq.tv_sec = (time_t)(milliseconds / 1000);
116 tmReq.tv_nsec = (milliseconds % 1000) * 1000 * 1000;
117
118 // we're not interested in remaining time nor in return value
119 (void)nanosleep(&tmReq, (timespec *)NULL);
120 #elif defined(HAVE_USLEEP)
121 // uncomment this if you feel brave or if you are sure that your version
122 // of Solaris has a safe usleep() function but please notice that usleep()
123 // is known to lead to crashes in MT programs in Solaris 2.[67] and is not
124 // documented as MT-Safe
125 #if defined(__SUN__) && wxUSE_THREADS
126 #error "usleep() cannot be used in MT programs under Solaris."
127 #endif // Sun
128
129 usleep(milliseconds * 1000); // usleep(3) wants microseconds
130 #elif defined(HAVE_SLEEP)
131 // under BeOS sleep() takes seconds (what about other platforms, if any?)
132 sleep(milliseconds * 1000);
133 #else // !sleep function
134 #error "usleep() or nanosleep() function required for wxUsleep"
135 #endif // sleep function
136 }
137
138 // ----------------------------------------------------------------------------
139 // process management
140 // ----------------------------------------------------------------------------
141
142 int wxKill(long pid, wxSignal sig, wxKillError *rc)
143 {
144 int err = kill((pid_t)pid, (int)sig);
145 if ( rc )
146 {
147 switch ( err )
148 {
149 case 0:
150 *rc = wxKILL_OK;
151 break;
152
153 case EINVAL:
154 *rc = wxKILL_BAD_SIGNAL;
155 break;
156
157 case EPERM:
158 *rc = wxKILL_ACCESS_DENIED;
159 break;
160
161 case ESRCH:
162 *rc = wxKILL_NO_PROCESS;
163 break;
164
165 default:
166 // this goes against Unix98 docs so log it
167 wxLogDebug(_T("unexpected kill(2) return value %d"), err);
168
169 // something else...
170 *rc = wxKILL_ERROR;
171 }
172 }
173
174 return err;
175 }
176
177 #define WXEXECUTE_NARGS 127
178
179 long wxExecute( const wxString& command, bool sync, wxProcess *process )
180 {
181 wxCHECK_MSG( !command.IsEmpty(), 0, wxT("can't exec empty command") );
182
183 int argc = 0;
184 wxChar *argv[WXEXECUTE_NARGS];
185 wxString argument;
186 const wxChar *cptr = command.c_str();
187 wxChar quotechar = wxT('\0'); // is arg quoted?
188 bool escaped = FALSE;
189
190 // split the command line in arguments
191 do
192 {
193 argument=wxT("");
194 quotechar = wxT('\0');
195
196 // eat leading whitespace:
197 while ( wxIsspace(*cptr) )
198 cptr++;
199
200 if ( *cptr == wxT('\'') || *cptr == wxT('"') )
201 quotechar = *cptr++;
202
203 do
204 {
205 if ( *cptr == wxT('\\') && ! escaped )
206 {
207 escaped = TRUE;
208 cptr++;
209 continue;
210 }
211
212 // all other characters:
213 argument += *cptr++;
214 escaped = FALSE;
215
216 // have we reached the end of the argument?
217 if ( (*cptr == quotechar && ! escaped)
218 || (quotechar == wxT('\0') && wxIsspace(*cptr))
219 || *cptr == wxT('\0') )
220 {
221 wxASSERT_MSG( argc < WXEXECUTE_NARGS,
222 wxT("too many arguments in wxExecute") );
223
224 argv[argc] = new wxChar[argument.length() + 1];
225 wxStrcpy(argv[argc], argument.c_str());
226 argc++;
227
228 // if not at end of buffer, swallow last character:
229 if(*cptr)
230 cptr++;
231
232 break; // done with this one, start over
233 }
234 } while(*cptr);
235 } while(*cptr);
236 argv[argc] = NULL;
237
238 // do execute the command
239 long lRc = wxExecute(argv, sync, process);
240
241 // clean up
242 argc = 0;
243 while( argv[argc] )
244 delete [] argv[argc++];
245
246 return lRc;
247 }
248
249 // ----------------------------------------------------------------------------
250 // wxShell
251 // ----------------------------------------------------------------------------
252
253 static wxString wxMakeShellCommand(const wxString& command)
254 {
255 wxString cmd;
256 if ( !command )
257 {
258 // just an interactive shell
259 cmd = _T("xterm");
260 }
261 else
262 {
263 // execute command in a shell
264 cmd << _T("/bin/sh -c '") << command << _T('\'');
265 }
266
267 return cmd;
268 }
269
270 bool wxShell(const wxString& command)
271 {
272 return wxExecute(wxMakeShellCommand(command), TRUE /* sync */) == 0;
273 }
274
275 bool wxShell(const wxString& command, wxArrayString& output)
276 {
277 wxCHECK_MSG( !!command, FALSE, _T("can't exec shell non interactively") );
278
279 return wxExecute(wxMakeShellCommand(command), output);
280 }
281
282 #if wxUSE_GUI
283
284 void wxHandleProcessTermination(wxEndProcessData *proc_data)
285 {
286 int pid = (proc_data->pid > 0) ? proc_data->pid : -(proc_data->pid);
287
288 // waitpid is POSIX so should be available everywhere, however on older
289 // systems wait() might be used instead in a loop (until the right pid
290 // terminates)
291 int status = 0;
292 int rc;
293
294 // wait for child termination and if waitpid() was interrupted, try again
295 do
296 {
297 rc = waitpid(pid, &status, 0);
298 }
299 while ( rc == -1 && errno == EINTR );
300
301 // notify user about termination if required
302 if ( proc_data->process )
303 {
304 proc_data->process->OnTerminate
305 (
306 proc_data->pid,
307 (rc == 0) && WIFEXITED(status)
308 ? WEXITSTATUS(status)
309 : -1
310 );
311 }
312 // clean up
313 if ( proc_data->pid > 0 )
314 {
315 delete proc_data;
316 }
317 else
318 {
319 // wxExecute() will know about it
320 proc_data->exitcode = status;
321
322 proc_data->pid = 0;
323 }
324 }
325
326 #endif // wxUSE_GUI
327
328 // ----------------------------------------------------------------------------
329 // wxStream classes to support IO redirection in wxExecute
330 // ----------------------------------------------------------------------------
331
332 #if wxUSE_STREAMS
333
334 class wxProcessFileInputStream : public wxInputStream
335 {
336 public:
337 wxProcessFileInputStream(int fd) { m_fd = fd; }
338 ~wxProcessFileInputStream() { close(m_fd); }
339
340 virtual bool Eof() const;
341
342 protected:
343 size_t OnSysRead(void *buffer, size_t bufsize);
344
345 protected:
346 int m_fd;
347 };
348
349 class wxProcessFileOutputStream : public wxOutputStream
350 {
351 public:
352 wxProcessFileOutputStream(int fd) { m_fd = fd; }
353 ~wxProcessFileOutputStream() { close(m_fd); }
354
355 protected:
356 size_t OnSysWrite(const void *buffer, size_t bufsize);
357
358 protected:
359 int m_fd;
360 };
361
362 bool wxProcessFileInputStream::Eof() const
363 {
364 if ( m_lasterror == wxSTREAM_EOF )
365 return TRUE;
366
367 // check if there is any input available
368 struct timeval tv;
369 tv.tv_sec = 0;
370 tv.tv_usec = 0;
371
372 fd_set readfds;
373 FD_ZERO(&readfds);
374 FD_SET(m_fd, &readfds);
375 switch ( select(m_fd + 1, &readfds, NULL, NULL, &tv) )
376 {
377 case -1:
378 wxLogSysError(_("Impossible to get child process input"));
379 // fall through
380
381 case 0:
382 return TRUE;
383
384 default:
385 wxFAIL_MSG(_T("unexpected select() return value"));
386 // still fall through
387
388 case 1:
389 // input available: check if there is any
390 return wxInputStream::Eof();
391 }
392 }
393
394 size_t wxProcessFileInputStream::OnSysRead(void *buffer, size_t bufsize)
395 {
396 int ret = read(m_fd, buffer, bufsize);
397 if ( ret == 0 )
398 {
399 m_lasterror = wxSTREAM_EOF;
400 }
401 else if ( ret == -1 )
402 {
403 m_lasterror = wxSTREAM_READ_ERROR;
404 ret = 0;
405 }
406 else
407 {
408 m_lasterror = wxSTREAM_NOERROR;
409 }
410
411 return ret;
412 }
413
414 size_t wxProcessFileOutputStream::OnSysWrite(const void *buffer, size_t bufsize)
415 {
416 int ret = write(m_fd, buffer, bufsize);
417 if ( ret == -1 )
418 {
419 m_lasterror = wxSTREAM_WRITE_ERROR;
420 ret = 0;
421 }
422 else
423 {
424 m_lasterror = wxSTREAM_NOERROR;
425 }
426
427 return ret;
428 }
429
430 // ----------------------------------------------------------------------------
431 // wxStreamTempBuffer
432 // ----------------------------------------------------------------------------
433
434 /*
435 Extract of a mail to wx-users to give the context of the problem we are
436 trying to solve here:
437
438 MC> If I run the command:
439 MC> find . -name "*.h" -exec grep linux {} \;
440 MC> in the exec sample synchronously from the 'Capture command output'
441 MC> menu, wxExecute never returns. I have to xkill it. Has anyone
442 MC> else encountered this?
443
444 Yes, I can reproduce it too.
445
446 I even think I understand why it happens: before launching the external
447 command we set up a pipe with a valid file descriptor on the reading side
448 when the output is redirected. So the subprocess happily writes to it ...
449 until the pipe buffer (which is usually quite big on Unix, I think the
450 default is 4Mb) is full. Then the writing process stops and waits until we
451 read some data from the pipe to be able to continue writing to it but we
452 never do it because we wait until it terminates to start reading and so we
453 have a classical deadlock.
454
455 Here is the fix: we now read the output as soon as it appears into a temp
456 buffer (wxStreamTempBuffer object) and later just stuff it back into the
457 stream when the process terminates. See supporting code in wxExecute()
458 itself as well.
459 */
460
461 class wxStreamTempBuffer
462 {
463 public:
464 wxStreamTempBuffer();
465
466 // call to associate a stream with this buffer, otherwise nothing happens
467 // at all
468 void Init(wxInputStream *stream);
469
470 // check for input on our stream and cache it in our buffer if any
471 void Update();
472
473 ~wxStreamTempBuffer();
474
475 private:
476 // the stream we're buffering, if NULL we don't do anything at all
477 wxInputStream *m_stream;
478
479 // the buffer of size m_size (NULL if m_size == 0)
480 void *m_buffer;
481
482 // the size of the buffer
483 size_t m_size;
484 };
485
486 wxStreamTempBuffer::wxStreamTempBuffer()
487 {
488 m_stream = NULL;
489 m_buffer = NULL;
490 m_size = 0;
491 }
492
493 void wxStreamTempBuffer::Init(wxInputStream *stream)
494 {
495 m_stream = stream;
496 }
497
498 void wxStreamTempBuffer::Update()
499 {
500 if ( m_stream && !m_stream->Eof() )
501 {
502 // realloc in blocks of 1Kb - surely not the best strategy but which
503 // one is?
504 static const size_t incSize = 1024;
505
506 void *buf = realloc(m_buffer, m_size + incSize);
507 if ( !buf )
508 {
509 // don't read any more, we don't have enough memory to do it
510 m_stream = NULL;
511 }
512 else // got memory for the buffer
513 {
514 m_buffer = buf;
515 m_stream->Read((char *)m_buffer + m_size, incSize);
516 m_size += incSize;
517 }
518 }
519 }
520
521 wxStreamTempBuffer::~wxStreamTempBuffer()
522 {
523 if ( m_buffer )
524 {
525 m_stream->Ungetch(m_buffer, m_size);
526 free(m_buffer);
527 }
528 }
529
530 #endif // wxUSE_STREAMS
531
532 long wxExecute(wxChar **argv,
533 bool sync,
534 wxProcess *process)
535 {
536 // for the sync execution, we return -1 to indicate failure, but for async
537 // case we return 0 which is never a valid PID
538 //
539 // we define this as a macro, not a variable, to avoid compiler warnings
540 // about "ERROR_RETURN_CODE value may be clobbered by fork()"
541 #define ERROR_RETURN_CODE ((sync) ? -1 : 0)
542
543 wxCHECK_MSG( *argv, ERROR_RETURN_CODE, wxT("can't exec empty command") );
544
545 #if wxUSE_UNICODE
546 int mb_argc = 0;
547 char *mb_argv[WXEXECUTE_NARGS];
548
549 while (argv[mb_argc])
550 {
551 wxWX2MBbuf mb_arg = wxConvertWX2MB(argv[mb_argc]);
552 mb_argv[mb_argc] = strdup(mb_arg);
553 mb_argc++;
554 }
555 mb_argv[mb_argc] = (char *) NULL;
556
557 // this macro will free memory we used above
558 #define ARGS_CLEANUP \
559 for ( mb_argc = 0; mb_argv[mb_argc]; mb_argc++ ) \
560 free(mb_argv[mb_argc])
561 #else // ANSI
562 // no need for cleanup
563 #define ARGS_CLEANUP
564
565 wxChar **mb_argv = argv;
566 #endif // Unicode/ANSI
567
568 #if wxUSE_GUI
569 // create pipes
570 int end_proc_detect[2];
571 if ( pipe(end_proc_detect) == -1 )
572 {
573 wxLogSysError( _("Pipe creation failed") );
574 wxLogError( _("Failed to execute '%s'\n"), *argv );
575
576 ARGS_CLEANUP;
577
578 return ERROR_RETURN_CODE;
579 }
580 #endif // wxUSE_GUI
581
582 // pipes for inter process communication
583 int pipeIn[2], // stdin
584 pipeOut[2], // stdout
585 pipeErr[2]; // stderr
586
587 pipeIn[0] = pipeIn[1] =
588 pipeOut[0] = pipeOut[1] =
589 pipeErr[0] = pipeErr[1] = -1;
590
591 if ( process && process->IsRedirected() )
592 {
593 if ( pipe(pipeIn) == -1 || pipe(pipeOut) == -1 || pipe(pipeErr) == -1 )
594 {
595 #if wxUSE_GUI
596 // free previously allocated resources
597 close(end_proc_detect[0]);
598 close(end_proc_detect[1]);
599 #endif // wxUSE_GUI
600
601 wxLogSysError( _("Pipe creation failed") );
602 wxLogError( _("Failed to execute '%s'\n"), *argv );
603
604 ARGS_CLEANUP;
605
606 return ERROR_RETURN_CODE;
607 }
608 }
609
610 // fork the process
611 #ifdef HAVE_VFORK
612 pid_t pid = vfork();
613 #else
614 pid_t pid = fork();
615 #endif
616
617 if ( pid == -1 ) // error?
618 {
619 #if wxUSE_GUI
620 close(end_proc_detect[0]);
621 close(end_proc_detect[1]);
622 close(pipeIn[0]);
623 close(pipeIn[1]);
624 close(pipeOut[0]);
625 close(pipeOut[1]);
626 close(pipeErr[0]);
627 close(pipeErr[1]);
628 #endif // wxUSE_GUI
629
630 wxLogSysError( _("Fork failed") );
631
632 ARGS_CLEANUP;
633
634 return ERROR_RETURN_CODE;
635 }
636 else if ( pid == 0 ) // we're in child
637 {
638 #if wxUSE_GUI
639 close(end_proc_detect[0]); // close reading side
640 #endif // wxUSE_GUI
641
642 // These lines close the open file descriptors to to avoid any
643 // input/output which might block the process or irritate the user. If
644 // one wants proper IO for the subprocess, the right thing to do is to
645 // start an xterm executing it.
646 if ( !sync )
647 {
648 for ( int fd = 0; fd < FD_SETSIZE; fd++ )
649 {
650 if ( fd == pipeIn[0] || fd == pipeOut[1] || fd == pipeErr[1]
651 #if wxUSE_GUI
652 || fd == end_proc_detect[1]
653 #endif // wxUSE_GUI
654 )
655 {
656 // don't close this one, we still need it
657 continue;
658 }
659
660 // leave stderr opened too, it won't do any hurm
661 if ( fd != STDERR_FILENO )
662 close(fd);
663 }
664 }
665
666 // redirect stdio, stdout and stderr
667 if ( pipeIn[0] != -1 )
668 {
669 if ( dup2(pipeIn[0], STDIN_FILENO) == -1 ||
670 dup2(pipeOut[1], STDOUT_FILENO) == -1 ||
671 dup2(pipeErr[1], STDERR_FILENO) == -1 )
672 {
673 wxLogSysError(_("Failed to redirect child process input/output"));
674 }
675
676 close(pipeIn[0]);
677 close(pipeOut[1]);
678 close(pipeErr[1]);
679 }
680
681 execvp (*mb_argv, mb_argv);
682
683 // there is no return after successful exec()
684 _exit(-1);
685
686 // some compilers complain about missing return - of course, they
687 // should know that exit() doesn't return but what else can we do if
688 // they don't?
689 #if defined(__VMS) || defined(__INTEL_COMPILER)
690 return 0;
691 #endif
692 }
693 else // we're in parent
694 {
695 ARGS_CLEANUP;
696
697 // pipe initialization: construction of the wxStreams
698 #if wxUSE_STREAMS
699 wxStreamTempBuffer bufIn, bufErr;
700 #endif // wxUSE_STREAMS
701
702 if ( process && process->IsRedirected() )
703 {
704 #if wxUSE_STREAMS
705 // in/out for subprocess correspond to our out/in
706 wxOutputStream *outStream = new wxProcessFileOutputStream(pipeIn[1]);
707 wxInputStream *inStream = new wxProcessFileInputStream(pipeOut[0]);
708 wxInputStream *errStream = new wxProcessFileInputStream(pipeErr[0]);
709
710 process->SetPipeStreams(inStream, outStream, errStream);
711
712 bufIn.Init(inStream);
713 bufErr.Init(inStream);
714 #endif // wxUSE_STREAMS
715
716 close(pipeIn[0]); // close reading side
717 close(pipeOut[1]); // close writing side
718 close(pipeErr[1]); // close writing side
719 }
720
721 #if wxUSE_GUI && !defined(__WXMICROWIN__)
722 wxEndProcessData *data = new wxEndProcessData;
723
724 if ( sync )
725 {
726 // we may have process for capturing the program output, but it's
727 // not used in wxEndProcessData in the case of sync execution
728 data->process = NULL;
729
730 // sync execution: indicate it by negating the pid
731 data->pid = -pid;
732 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
733
734 close(end_proc_detect[1]); // close writing side
735
736 wxBusyCursor bc;
737 wxWindowDisabler wd;
738
739 // data->pid will be set to 0 from GTK_EndProcessDetector when the
740 // process terminates
741 while ( data->pid != 0 )
742 {
743 #if wxUSE_STREAMS
744 bufIn.Update();
745 bufErr.Update();
746 #endif // wxUSE_STREAMS
747
748 // give GTK+ a chance to call GTK_EndProcessDetector here and
749 // also repaint the GUI
750 wxYield();
751 }
752
753 int exitcode = data->exitcode;
754
755 delete data;
756
757 return exitcode;
758 }
759 else // async execution
760 {
761 // async execution, nothing special to do - caller will be
762 // notified about the process termination if process != NULL, data
763 // will be deleted in GTK_EndProcessDetector
764 data->process = process;
765 data->pid = pid;
766 data->tag = wxAddProcessCallback(data, end_proc_detect[0]);
767
768 close(end_proc_detect[1]); // close writing side
769
770 return pid;
771 }
772 #else // !wxUSE_GUI
773 wxASSERT_MSG( sync, wxT("async execution not supported yet") );
774
775 int exitcode = 0;
776 if ( waitpid(pid, &exitcode, 0) == -1 || !WIFEXITED(exitcode) )
777 {
778 wxLogSysError(_("Waiting for subprocess termination failed"));
779 }
780
781 return exitcode;
782 #endif // wxUSE_GUI
783 }
784 }
785
786 #undef ERROR_RETURN_CODE
787 #undef ARGS_CLEANUP
788
789 // ----------------------------------------------------------------------------
790 // file and directory functions
791 // ----------------------------------------------------------------------------
792
793 const wxChar* wxGetHomeDir( wxString *home )
794 {
795 *home = wxGetUserHome( wxString() );
796 wxString tmp;
797 if ( home->IsEmpty() )
798 *home = wxT("/");
799 #ifdef __VMS
800 tmp = *home;
801 if ( tmp.Last() != wxT(']'))
802 if ( tmp.Last() != wxT('/')) *home << wxT('/');
803 #endif
804 return home->c_str();
805 }
806
807 #if wxUSE_UNICODE
808 const wxMB2WXbuf wxGetUserHome( const wxString &user )
809 #else // just for binary compatibility -- there is no 'const' here
810 char *wxGetUserHome( const wxString &user )
811 #endif
812 {
813 struct passwd *who = (struct passwd *) NULL;
814
815 if ( !user )
816 {
817 wxChar *ptr;
818
819 if ((ptr = wxGetenv(wxT("HOME"))) != NULL)
820 {
821 return ptr;
822 }
823 if ((ptr = wxGetenv(wxT("USER"))) != NULL || (ptr = wxGetenv(wxT("LOGNAME"))) != NULL)
824 {
825 who = getpwnam(wxConvertWX2MB(ptr));
826 }
827
828 // We now make sure the the user exists!
829 if (who == NULL)
830 {
831 who = getpwuid(getuid());
832 }
833 }
834 else
835 {
836 who = getpwnam (user.mb_str());
837 }
838
839 return wxConvertMB2WX(who ? who->pw_dir : 0);
840 }
841
842 // ----------------------------------------------------------------------------
843 // network and user id routines
844 // ----------------------------------------------------------------------------
845
846 // retrieve either the hostname or FQDN depending on platform (caller must
847 // check whether it's one or the other, this is why this function is for
848 // private use only)
849 static bool wxGetHostNameInternal(wxChar *buf, int sz)
850 {
851 wxCHECK_MSG( buf, FALSE, wxT("NULL pointer in wxGetHostNameInternal") );
852
853 *buf = wxT('\0');
854
855 // we're using uname() which is POSIX instead of less standard sysinfo()
856 #if defined(HAVE_UNAME)
857 struct utsname uts;
858 bool ok = uname(&uts) != -1;
859 if ( ok )
860 {
861 wxStrncpy(buf, wxConvertMB2WX(uts.nodename), sz - 1);
862 buf[sz] = wxT('\0');
863 }
864 #elif defined(HAVE_GETHOSTNAME)
865 bool ok = gethostname(buf, sz) != -1;
866 #else // no uname, no gethostname
867 wxFAIL_MSG(wxT("don't know host name for this machine"));
868
869 bool ok = FALSE;
870 #endif // uname/gethostname
871
872 if ( !ok )
873 {
874 wxLogSysError(_("Cannot get the hostname"));
875 }
876
877 return ok;
878 }
879
880 bool wxGetHostName(wxChar *buf, int sz)
881 {
882 bool ok = wxGetHostNameInternal(buf, sz);
883
884 if ( ok )
885 {
886 // BSD systems return the FQDN, we only want the hostname, so extract
887 // it (we consider that dots are domain separators)
888 wxChar *dot = wxStrchr(buf, wxT('.'));
889 if ( dot )
890 {
891 // nuke it
892 *dot = wxT('\0');
893 }
894 }
895
896 return ok;
897 }
898
899 bool wxGetFullHostName(wxChar *buf, int sz)
900 {
901 bool ok = wxGetHostNameInternal(buf, sz);
902
903 if ( ok )
904 {
905 if ( !wxStrchr(buf, wxT('.')) )
906 {
907 struct hostent *host = gethostbyname(wxConvertWX2MB(buf));
908 if ( !host )
909 {
910 wxLogSysError(_("Cannot get the official hostname"));
911
912 ok = FALSE;
913 }
914 else
915 {
916 // the canonical name
917 wxStrncpy(buf, wxConvertMB2WX(host->h_name), sz);
918 }
919 }
920 //else: it's already a FQDN (BSD behaves this way)
921 }
922
923 return ok;
924 }
925
926 bool wxGetUserId(wxChar *buf, int sz)
927 {
928 struct passwd *who;
929
930 *buf = wxT('\0');
931 if ((who = getpwuid(getuid ())) != NULL)
932 {
933 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
934 return TRUE;
935 }
936
937 return FALSE;
938 }
939
940 bool wxGetUserName(wxChar *buf, int sz)
941 {
942 struct passwd *who;
943
944 *buf = wxT('\0');
945 if ((who = getpwuid (getuid ())) != NULL)
946 {
947 // pw_gecos field in struct passwd is not standard
948 #ifdef HAVE_PW_GECOS
949 char *comma = strchr(who->pw_gecos, ',');
950 if (comma)
951 *comma = '\0'; // cut off non-name comment fields
952 wxStrncpy (buf, wxConvertMB2WX(who->pw_gecos), sz - 1);
953 #else // !HAVE_PW_GECOS
954 wxStrncpy (buf, wxConvertMB2WX(who->pw_name), sz - 1);
955 #endif // HAVE_PW_GECOS/!HAVE_PW_GECOS
956 return TRUE;
957 }
958
959 return FALSE;
960 }
961
962 wxString wxGetOsDescription()
963 {
964 #ifndef WXWIN_OS_DESCRIPTION
965 #error WXWIN_OS_DESCRIPTION should be defined in config.h by configure
966 #else
967 return WXWIN_OS_DESCRIPTION;
968 #endif
969 }
970
971 // this function returns the GUI toolkit version in GUI programs, but OS
972 // version in non-GUI ones
973 #if !wxUSE_GUI
974
975 int wxGetOsVersion(int *majorVsn, int *minorVsn)
976 {
977 int major, minor;
978 char name[256];
979
980 if ( sscanf(WXWIN_OS_DESCRIPTION, "%s %d.%d", name, &major, &minor) != 3 )
981 {
982 // unreckognized uname string format
983 major = minor = -1;
984 }
985
986 if ( majorVsn )
987 *majorVsn = major;
988 if ( minorVsn )
989 *minorVsn = minor;
990
991 return wxUNIX;
992 }
993
994 #endif // !wxUSE_GUI
995
996 long wxGetFreeMemory()
997 {
998 #if defined(__LINUX__)
999 // get it from /proc/meminfo
1000 FILE *fp = fopen("/proc/meminfo", "r");
1001 if ( fp )
1002 {
1003 long memFree = -1;
1004
1005 char buf[1024];
1006 if ( fgets(buf, WXSIZEOF(buf), fp) && fgets(buf, WXSIZEOF(buf), fp) )
1007 {
1008 long memTotal, memUsed;
1009 sscanf(buf, "Mem: %ld %ld %ld", &memTotal, &memUsed, &memFree);
1010 }
1011
1012 fclose(fp);
1013
1014 return memFree;
1015 }
1016 #elif defined(__SUN__) && defined(_SC_AVPHYS_PAGES)
1017 return sysconf(_SC_AVPHYS_PAGES)*sysconf(_SC_PAGESIZE);
1018 //#elif defined(__FREEBSD__) -- might use sysctl() to find it out, probably
1019 #endif
1020
1021 // can't find it out
1022 return -1;
1023 }
1024
1025 bool wxGetDiskSpace(const wxString& path, wxLongLong *pTotal, wxLongLong *pFree)
1026 {
1027 #ifdef HAVE_STATFS
1028
1029 struct statfs fs;
1030 if ( statfs(path, &fs) != 0 )
1031 {
1032 wxLogSysError("Failed to get file system statistics");
1033
1034 return FALSE;
1035 }
1036
1037 if ( pTotal )
1038 {
1039 *pTotal = wxLongLong(fs.f_blocks) * fs.f_bsize;
1040 }
1041
1042 if ( pFree )
1043 {
1044 *pFree = wxLongLong(fs.f_bavail) * fs.f_bsize;
1045 }
1046
1047 return TRUE;
1048 #endif // HAVE_STATFS
1049
1050 return FALSE;
1051 }
1052
1053 // ----------------------------------------------------------------------------
1054 // env vars
1055 // ----------------------------------------------------------------------------
1056
1057 bool wxGetEnv(const wxString& var, wxString *value)
1058 {
1059 // wxGetenv is defined as getenv()
1060 wxChar *p = wxGetenv(var);
1061 if ( !p )
1062 return FALSE;
1063
1064 if ( value )
1065 {
1066 *value = p;
1067 }
1068
1069 return TRUE;
1070 }
1071
1072 bool wxSetEnv(const wxString& variable, const wxChar *value)
1073 {
1074 #if defined(HAVE_SETENV)
1075 return setenv(variable.mb_str(), value ? wxString(value).mb_str().data()
1076 : NULL, 1 /* overwrite */) == 0;
1077 #elif defined(HAVE_PUTENV)
1078 wxString s = variable;
1079 if ( value )
1080 s << _T('=') << value;
1081
1082 // transform to ANSI
1083 const char *p = s.mb_str();
1084
1085 // the string will be free()d by libc
1086 char *buf = (char *)malloc(strlen(p) + 1);
1087 strcpy(buf, p);
1088
1089 return putenv(buf) == 0;
1090 #else // no way to set an env var
1091 return FALSE;
1092 #endif
1093 }
1094
1095 // ----------------------------------------------------------------------------
1096 // signal handling
1097 // ----------------------------------------------------------------------------
1098
1099 #if wxUSE_ON_FATAL_EXCEPTION
1100
1101 #include <signal.h>
1102
1103 static void wxFatalSignalHandler(wxTYPE_SA_HANDLER)
1104 {
1105 if ( wxTheApp )
1106 {
1107 // give the user a chance to do something special about this
1108 wxTheApp->OnFatalException();
1109 }
1110
1111 abort();
1112 }
1113
1114 bool wxHandleFatalExceptions(bool doit)
1115 {
1116 // old sig handlers
1117 static bool s_savedHandlers = FALSE;
1118 static struct sigaction s_handlerFPE,
1119 s_handlerILL,
1120 s_handlerBUS,
1121 s_handlerSEGV;
1122
1123 bool ok = TRUE;
1124 if ( doit && !s_savedHandlers )
1125 {
1126 // install the signal handler
1127 struct sigaction act;
1128
1129 // some systems extend it with non std fields, so zero everything
1130 memset(&act, 0, sizeof(act));
1131
1132 act.sa_handler = wxFatalSignalHandler;
1133 sigemptyset(&act.sa_mask);
1134 act.sa_flags = 0;
1135
1136 ok &= sigaction(SIGFPE, &act, &s_handlerFPE) == 0;
1137 ok &= sigaction(SIGILL, &act, &s_handlerILL) == 0;
1138 ok &= sigaction(SIGBUS, &act, &s_handlerBUS) == 0;
1139 ok &= sigaction(SIGSEGV, &act, &s_handlerSEGV) == 0;
1140 if ( !ok )
1141 {
1142 wxLogDebug(_T("Failed to install our signal handler."));
1143 }
1144
1145 s_savedHandlers = TRUE;
1146 }
1147 else if ( s_savedHandlers )
1148 {
1149 // uninstall the signal handler
1150 ok &= sigaction(SIGFPE, &s_handlerFPE, NULL) == 0;
1151 ok &= sigaction(SIGILL, &s_handlerILL, NULL) == 0;
1152 ok &= sigaction(SIGBUS, &s_handlerBUS, NULL) == 0;
1153 ok &= sigaction(SIGSEGV, &s_handlerSEGV, NULL) == 0;
1154 if ( !ok )
1155 {
1156 wxLogDebug(_T("Failed to uninstall our signal handler."));
1157 }
1158
1159 s_savedHandlers = FALSE;
1160 }
1161 //else: nothing to do
1162
1163 return ok;
1164 }
1165
1166 #endif // wxUSE_ON_FATAL_EXCEPTION
1167
1168 // ----------------------------------------------------------------------------
1169 // error and debug output routines (deprecated, use wxLog)
1170 // ----------------------------------------------------------------------------
1171
1172 void wxDebugMsg( const char *format, ... )
1173 {
1174 va_list ap;
1175 va_start( ap, format );
1176 vfprintf( stderr, format, ap );
1177 fflush( stderr );
1178 va_end(ap);
1179 }
1180
1181 void wxError( const wxString &msg, const wxString &title )
1182 {
1183 wxFprintf( stderr, _("Error ") );
1184 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1185 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1186 wxFprintf( stderr, wxT(".\n") );
1187 }
1188
1189 void wxFatalError( const wxString &msg, const wxString &title )
1190 {
1191 wxFprintf( stderr, _("Error ") );
1192 if (!title.IsNull()) wxFprintf( stderr, wxT("%s "), WXSTRINGCAST(title) );
1193 if (!msg.IsNull()) wxFprintf( stderr, wxT(": %s"), WXSTRINGCAST(msg) );
1194 wxFprintf( stderr, wxT(".\n") );
1195 exit(3); // the same exit code as for abort()
1196 }
1197