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