newlib/winsup/cygwin/syslog.cc

489 lines
12 KiB
C++
Raw Normal View History

2000-02-17 20:38:33 +01:00
/* syslog.cc
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#define __INSIDE_CYGWIN_NET__
In terms of network related functionality, rely on Winsock definitions as much as possible: * dtable.cc: Drop including sys/socket.h. * fhandler_procnet.cc: Change includes accordingly. * fhandler_socket.cc: Ditto. (fhandler_socket::listen): Avoid gcc error message initializing sin6. (LPFN_WSARECVMSG): Only define when building against w32api headers. * net.cc: Change includes accordingly. Define USE_SYS_TYPES_FD_SET and __WSA_ERR_MACROS_DEFINED. Define _INC_NETIOAPI temporarily and explain why. (struct _IP_ADAPTER_UNICAST_ADDRESS_LH): Only define when building against w32api headers. (struct _IP_ADAPTER_ADDRESSES_LH): Ditto. (SIO_GET_INTERFACE_LIST): Ditto. (ws_freeaddrinfo): Rename from freeaddrinfo so as not to collide with Winsock declaration. Change througout. (ws_getaddrinfo): Ditto. (ws_getnameinfo): Ditto. * select.cc: Include netdb.h after defining USE_SYS_TYPES_FD_SET. * syslog.cc: Drop including netinet/in.h. Define USE_SYS_TYPES_FD_SET and include ws2tcpip.h. * include/netdb.h (struct addrinfo): Don't define when building Cygwin. * include/cygwin/if.h: Don't declare if_xxx functions when building Cygwin. * include/cygwin/in.h: Disable most definitions when building Cygwin. * include/cygwin/socket.h: Disable sockaddr and sockaddr_storage definitions when building Cygwin. Same for MCAST_INCLUDE/MCAST_EXCLUDE. * libc/inet_addr.c: Don't define __INSIDE_CYGWIN__ nor __INSIDE_CYGWIN_NET__. * libc/inet_network.c: Ditto. * libc/minires.h: Drop redundant inclusion of netdb.h. Define __INSIDE_CYGWIN_NET__ only before including netdb.h and resolver headers.
2012-07-06 15:52:19 +02:00
#define USE_SYS_TYPES_FD_SET
#include "winsup.h"
In terms of network related functionality, rely on Winsock definitions as much as possible: * dtable.cc: Drop including sys/socket.h. * fhandler_procnet.cc: Change includes accordingly. * fhandler_socket.cc: Ditto. (fhandler_socket::listen): Avoid gcc error message initializing sin6. (LPFN_WSARECVMSG): Only define when building against w32api headers. * net.cc: Change includes accordingly. Define USE_SYS_TYPES_FD_SET and __WSA_ERR_MACROS_DEFINED. Define _INC_NETIOAPI temporarily and explain why. (struct _IP_ADAPTER_UNICAST_ADDRESS_LH): Only define when building against w32api headers. (struct _IP_ADAPTER_ADDRESSES_LH): Ditto. (SIO_GET_INTERFACE_LIST): Ditto. (ws_freeaddrinfo): Rename from freeaddrinfo so as not to collide with Winsock declaration. Change througout. (ws_getaddrinfo): Ditto. (ws_getnameinfo): Ditto. * select.cc: Include netdb.h after defining USE_SYS_TYPES_FD_SET. * syslog.cc: Drop including netinet/in.h. Define USE_SYS_TYPES_FD_SET and include ws2tcpip.h. * include/netdb.h (struct addrinfo): Don't define when building Cygwin. * include/cygwin/if.h: Don't declare if_xxx functions when building Cygwin. * include/cygwin/in.h: Disable most definitions when building Cygwin. * include/cygwin/socket.h: Disable sockaddr and sockaddr_storage definitions when building Cygwin. Same for MCAST_INCLUDE/MCAST_EXCLUDE. * libc/inet_addr.c: Don't define __INSIDE_CYGWIN__ nor __INSIDE_CYGWIN_NET__. * libc/inet_network.c: Ditto. * libc/minires.h: Drop redundant inclusion of netdb.h. Define __INSIDE_CYGWIN_NET__ only before including netdb.h and resolver headers.
2012-07-06 15:52:19 +02:00
#include <ws2tcpip.h>
#include <iphlpapi.h>
2000-02-17 20:38:33 +01:00
#include <stdlib.h>
#include <stdio.h>
#include <syslog.h>
#include <unistd.h>
#include <sys/un.h>
#include "cygerrno.h"
#include "security.h"
Add "path.h" include throughout, where needed. Use new path_conv methods and operators to simplify testing for directory and attributes, throughout. * path.h (path_conv::exists): New method. (path_conv::has_attribute): Ditto. (path_conv::isdir): Ditto. (path_conv::DWORD &): New operator. (path_conv::int &): Ditto. * dir.cc (rmdir): Eliminate a goto. * dtable.cc (dtable::build_fhandler): Accept opt and suffix info for path_conv.check. Return fh == NULL on path_conv error. Pass unit to set_name as appropriate. (dtable::reset_unix_path_name): New method. * dtable.h (dtable): Declare new method. Reflect arg changes to build_fhandler. * fhandler.cc (fhandler_disk_dummy_name): Eliminate. (fhandler_base::set_name): Expect paths to be NULL. Build unix_path_name from win32_path_name when it is a device. (fhandler_base::reset_unix_path_name): New method. (fhandler_base::raw_read): Report EISDIR when ERROR_INVALID_FUNCTION or ERROR_INVALID_PARAMETER and reading a directory. (fhandler_disk_file::fstat): Don't call stat_dev since we should now never be calling fhandler_disk_file methods with devices. (fhandler_base::fhandler_base): Clear {unix,win32}_path_name. (fhandler_base::~fhandler_base): Always free {unix,win32}_path_name. (fhandler_disk_file::fhandler_disk_file): Remove set_no_free_names kludge. (fhandler_disk_file::open): Ditto. * fhandler.h (fhandler_base::no_free_names): Eliminate. (fhandler_base::set_no_free_names): Ditto. * fhandler_tty.cc (fhandler_tty_slave::fhandler_tty_slave): Don't set unix_path_name here. * path.cc (fchdir): Lock fd table throughout. Use new dtable::reset_unix_path_name method to reset path. * syscalls.cc (stat_worker): Reorganize to always call fstat method. Pass path_conv method to fhandler_*::open. (chroot): Elminate a goto.
2001-10-01 06:10:07 +02:00
#include "path.h"
* devices.cc: New file. * devices.gperf: New file. * devices.shilka: New file. * cygwin-gperf: New file. * cygwin-shilka: New file. * fhandler_fifo.cc: New file. * fhandler_nodevice.cc : New file. Reorganize headers so that path.h precedes fhandler.h throughout. Remove device argument and unit arguments from fhandler constructors throughout. Remove pc arguments to fhandler functions and use internal pc element instead, throughout. Use dev element in pc throughout. Use major/minor elements rather than units and device numbers previously in fhandler class. Use correct methods for fhandler file names rather than directly accessing file name variables, throughout. * Makefile.in (DLL_OFILES): Add devices.o, fhandler_fifo.o * dcrt0.cc (dll_crt0_1): Call device::init. * devices.h: Renumber devices based on more Linux-like major/minor numbers. Add more devices. Declare standard device storage. (device): Declare struct. * dir.cc (opendir): Use new 'build_fh_name' to construct a fhandler_* type. * dtable.cc (dtable::get_debugger_info): Ditto. (cygwin_attach_handle_to_fd): Ditto. (dtable::release): Remove special FH_SOCKET case in favor of generic "need_fixup_before" test. (dtable::init_std_file_from_handle): Use either build_fh_dev or build_fh_name to build standard fhandler. (dtable::build_fh_name): Renamed from dtable::build_fhandler_from_name. Move out of dtable class. Don't accept a path_conv argument. Just build it here and pass it to: (build_fh_pc): Renamed from dtable::build_fhandler. Move out of dtable class. Use intrinsic device type in path_conv to create new fhandler. (build_fh_dev): Renamed from dtable::build_fhandler. Move out of dtable class. Simplify arguments to just take new 'device' type and a name. Just return pointer to fhandler rather than trying to insert into dtable. (dtable::dup_worker): Accommodate above build_fh name changes. (dtable::find_fifo): New (currently broken) function. (handle_to_fn): Use strechr for efficiency. * dtable.h: Reflect above build_fh name changes and argument differences. (fhandler_base *&operator []): Return self rather than copy of self. * fhandler.cc (fhandler_base::operator =): Use pc element to set normalized path. (fhandler_base::set_name): Ditto. (fhandler_base::raw_read): Use method to access name. (fhandler_base::write): Correctly use get_output_handle rather than get_handle. (handler_base::device_access_denied): New function. (fhandler_base::open): Eliminate pc argument and use pc element of fhandler_base throughout. (fhandler_base::fstat): Detect if device is based in filesystem and use fstat_fs to calculate stat, if so. (fhandler_base::fhandler_base): Eliminate handling of file names and, instead, just free appropriate component from pc. (fhandler_base::opendir): Remove path_conv parameter. * fhandler.h: Remove all device flags. (fhandler_base::pc): New element. (fhandler_base::set_name): Change argument to path_conv. (fhandler_base::error): New function. (fhandler_base::exists): New function. (fhandler_base::pc_binmode): New function. (fhandler_base::dev): New function. (fhandler_base::open_fs): New function. (fhandler_base::fstat_fs): New function. (fhandler_base::fstat_by_name): New function. (fhandler_base::fstat_by_handle): New function. (fhandler_base::isfifo): New function. (fhandler_base::is_slow): New function. (fhandler_base::is_auto_device): New function. (fhandler_base::is_fs_special): New function. (fhandler_base::device_access_denied): New function. (fhandler_base::operator DWORD&): New operator. (fhandler_base::get_name): Return normalized path from pc. (fhandler_base::get_win32_name): Return windows path from pc. (fhandler_base::isdevice): Renamed from is_device. (fhandler_base::get_native_name): Return device format. (fhandler_fifo): New class. (fhandler_nodevice): New class. (select_stuff::device_specific): Remove array. (select_stuff::device_specific_pipe): New class element. (select_stuff::device_specific_socket): New class element. (select_stuff::device_specific_serial): New class element. (select_stuff::select_stuff): Initialize new elements. * fhandler_disk_file.cc (fhandler_base::fstat_by_handle): Move to base class from fhandler_disk_file. (fhandler_base::fstat_by_name): Ditto. (fhandler_base::fstat_by_name): Ditto. (fhandler_disk_file::open): Move most functionality into fhandler_base::open_fs. (fhandler_base::open_fs): New function. (fhandler_disk_file::close): Move most functionality into fhandler_base::close_fs. (fhandler_base::close_fs): New function. * fhandler_mem.cc (fhandler_dev_mem::open): Use device name in debugging output. * fhandler_socket.cc (fhandler_socket::set_connect_secret): Copy standard urandom device into appropriate place. (fhandler_socket::accept): Reflect change in fdsock return value. * fhandler_tty.cc: See "throughouts" above. * net.cc: Accommodate fdsock change throughout. (fdsock): Return success or failure, accept fd argument and device argument. * path.cc (symlink_info::major): New element. (symlink_info::minor): New element. (symlink_info::parse_device): Declare new function. (fs_info::update): Accommodate changes in path_conv class. (path_conv::fillin): Ditto. (path_conv::return_and_clear_normalized_path): Eliminate. (path_conv::set_normalized_path): New function. (path_conv::path_conv): Set info in dev element. Use path_conv methods Check for FH_FS rather than FH_BAD to indicate when to fill in filesystem stuff. where appropriate rather than direct access. Use set_normalized_path to set normalized path. (windows_device_names): Eliminate. (get_dev): Ditto. (get_raw_device_number): Ditto. (get_device_number): Ditto. (win32_device_name): Call new device name parser to do most of the heavy lifting. (mount_info::conv_to_win32_path): Fill in dev field as appropriate. (symlink_worker): Handle new device files. (symlink_info::check): Ditto. (symlink_info::parse_device): Define new function. * path.h (executable_states): Move here from fhandler.h. (fs_info): Rename variables to *_storage and create methods for accessing same. (path_conv): Add dev element, remove devn and unit and adjust inline methods to accommodate. (set_normalized_path): Declare new function. * pinfo.cc (_pinfo::commune_recv): Add broken support for handling fifos. (_pinfo::commune_send): Ditto. * pipe.cc (fhandler_pipe::close): check for existence of handle before closing it. (handler_pipe::create): Rename from make_pipe. Change arguments to accept fhandler_pipe array. Accommodate fifos. (pipe): Rework to deal with fhandler_pipe::create changes. (_pipe): Ditto. * select.cc: Use individual device_specific types throughout rather than indexing with obsolete device number. (set_bits): Use is_socket call rather than checking device number. * shared_info.h (CURR_MOUNT_MAGIC): Update. (conv_to_win32_path): Reflect addition of device argument. * syscalls.cc (mknod_worker): New function. (open): Use build_fh_name to build fhandler. (chown_worker): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (chmod_device): New function. (chmod): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. Use chmod_device to set mode of in-filesystem devices. (stat_worker): Eliminate path_conv argument. Call build_fh_name to construct fhandler. Use fh->error() rather than pc->error to detect errors in fhandler construction. (access_worker): New function pulled from access. Accommodate in-filesystem devices. (access): Use access_worker. (fpathconf): Detect if this is an 'auto' device rather than an on-filesystem device and handle appropriately. (mknod_worker): New function. (mknod32): New function. (chroot): Free normalized path -- assuming it was actually cmalloced. * tty.cc (create_tty_master): Tweak for new device class. (tty::common_init): Ditto. * winsup.h (stat_worker): Remove. (symlink_worker): Declare. * exceptions.cc (set_process_mask): Just call sig_dispatch_pending and don't worry about pending_signals since sig_dispatch_pending should always do the right thing now. (sig_handle): Reorganize SIGCONT handling to more closely conform to SUSv3. * pinfo.h: Move __SIG enum to sigproc.h. (PICOM_FIFO): New enum element. (_pinfo): Remove 'thread2signal' stuff throughout class. (_pinfo::commune_send): Make varargs. (_pinfo::sigtodo): Eliminate. (_pinfo::thread2signal): Ditto. * signal.cc (kill_worker): Eliminate call to setthread2signal. * sigproc.cc (local_sigtodo): Eliminate. (getlocal_sigtodo): Ditto. (sigelem): New class. (pending_signals): New class. (sigqueue): New variable, start of sigqueue linked list. (sigcatch_nonmain): Eliminate. (sigcatch_main): Eliminate. (sigcatch_nosync): Eliminate. (sigcomplete_nonmain): Eliminate. (pending_signals): Eliminate. (sig_clear): Call signal thread to clear pending signals, unless already in signal thread. (sigpending): Call signal thread to get pending signals. (sig_dispatch_pending): Eliminate use of pending_signals and just check sigqueue. (sigproc_terminate): Eliminate all of the obsolete semaphore stuff. Close signal pipe handle. (sig_send): Eliminate all of the obsolete semaphore stuff and use pipe to send signals. (getevent): Eliminate. (pending_signals::add): New function. (pending_signals::del): New function. (pending_signals::next): New function. (wait_sig): Eliminate all of the obsolete semaphore stuff. Use pipe to communicate and maintain a linked list of signals. * sigproc.h: Move __SIG defines here. Add __SIGPENDING. (sig_dispatch_pending): Remove "C" specifier. (sig_handle): Accept a mask argument. * thread.cc: Remove signal handling considerations throughout.
2003-09-25 02:37:18 +02:00
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
* exceptions.cc (set_signal_mask): Redefine to not pass by address. Report calculated mask in debugging output. * sigproc.h (set_signal_mask): Reflect above change in declaration. * path.cc (mount_item::build_win32): Take path apart before feeding it to fnmunge. Throughout, change use of _reent_winsup()-> to _my_tls.locals. instead. Throughout, remove obsolete MT_SAFE/_CYG_THREAD_FAILSAFE considerations. Througout, add cygtls.h include. * Makefile.in (DLL_OFILES): Add cygtls.o. Add some more objects to the -fomit-frame-pointer list. * acconfig.h: Remove obsolete settings. * config.h.in: Ditto. * bsdlib.cc: Add cygtls.h include. * configure.in: Remove --enable-extra-threadsafe-checking. * configure: Regenerate. * cygtls.h (_local_storage): New struct renamed from _winsup_t (sic). (_threadinfo:local_clib): Add new field. (_threadinfo::locals): Ditto. (_threadinfo::init_thread): Accept second _reent * argument. (_threadinfo::call): Define as regparm. (CYGTLS_PADSIZE): Remove unnecessary slop. (_getreent): Define as a macro. * thread.h: Remove _CYG_THREAD_FAILSAFE and MT_SAFE stuff. (_winsup_t): Move to cygtls.h. (ResourceLocks::ResourceLocks): Eliminate empty constructor. (MTinterface::reents): Eliminate. (MTinterface::thread_self_key): Eliminate. (MTinterface::MTinterface): Eliminate. * dcrt0.cc: Include stdio.h for _impure_ptr initialization. (do_global_ctors): Remove run_ctors_p (sic) considerations. Don't call atexit here. (__main): Initialize destructors for user here. (dll_crt0_1): Accept a dummy argument. Don't call init_thread here. Don't set _impure_ptr here. Call do_global_ctors after more things have been initialized. (_dll_crt0): Define zeros buffer as max of needed size of CYGTLS_PADSIZE so that it can be used for two purposes while minimizing stack usage. Initialize _impure_ptr specifically, for speed. Call dll_crt0_1 with buffer argument. (cygwin_dll_init): Call dll_crt0_1 with dummy argument. * dtable.cc (dtable::find_unused_handle): Remove call to AssertResourceOwner. * exceptions.cc: Move _threadinfo stuff to new file. * cygtls.cc: New file. * gentls_offsets: Accommodate increasing complexity of cygtls.h. * hires.h (hires_base::~hires_base): Remove. * init.cc (dll_entry): Remove setting of reents. * thread.cc: Remove syslog.h include. (__getreent): Simplify to use _my_tls. (_reent_winsup): Delete. (AssertResourceOwner): Delete. (MTinterface::Init): Remove setting of _clib and _winsup, with all that entails. (MTinterface::fixup_after_fork): Ditto. (pthread::thread_init_wrapper): Ditto. Also remove call to set_tls_self_pointer. (pthread::set_tls_self_pointer): Eliminate. (pthread::get_tls_self_pointer): Just return _my_tls.tid; (__reent_t::init_clib): Eliminate. * tlsoffsets.h: Regenerate.
2003-12-23 17:26:31 +01:00
#include "cygtls.h"
#include "tls_pbuf.h"
2000-02-17 20:38:33 +01:00
#define CYGWIN_LOG_NAME L"Cygwin"
2000-02-17 20:38:33 +01:00
static struct
{
wchar_t *process_ident;
int process_logopt;
int process_facility;
int process_logmask;
} syslog_globals = { NULL, 0, 0, LOG_UPTO (LOG_DEBUG) };
/* openlog: save the passed args. Don't open the system log or /dev/log yet. */
extern "C" void
2000-02-17 20:38:33 +01:00
openlog (const char *ident, int logopt, int facility)
{
wchar_t *new_ident = NULL;
2000-02-17 20:38:33 +01:00
debug_printf ("openlog called with (%s, %d, %d)",
2013-04-23 11:44:36 +02:00
ident ? ident : "<NULL>", logopt, facility);
2000-02-17 20:38:33 +01:00
if (ident)
{
sys_mbstowcs_alloc (&new_ident, HEAP_NOTHEAP, ident);
if (!new_ident)
debug_printf ("failed to allocate memory for "
"syslog_globals.process_ident");
else
{
wchar_t *old_ident = syslog_globals.process_ident;
syslog_globals.process_ident = new_ident;
if (old_ident)
free (old_ident);
2000-02-17 20:38:33 +01:00
}
}
syslog_globals.process_logopt = logopt;
syslog_globals.process_facility = facility;
2000-02-17 20:38:33 +01:00
}
/* setlogmask: set the log priority mask and return previous mask.
If maskpri is zero, just return previous. */
int
setlogmask (int maskpri)
{
if (maskpri == 0)
return syslog_globals.process_logmask;
2000-02-17 20:38:33 +01:00
int old_mask = syslog_globals.process_logmask;
syslog_globals.process_logmask = maskpri;
2000-02-17 20:38:33 +01:00
return old_mask;
}
* exceptions.cc (set_signal_mask): Redefine to not pass by address. Report calculated mask in debugging output. * sigproc.h (set_signal_mask): Reflect above change in declaration. * path.cc (mount_item::build_win32): Take path apart before feeding it to fnmunge. Throughout, change use of _reent_winsup()-> to _my_tls.locals. instead. Throughout, remove obsolete MT_SAFE/_CYG_THREAD_FAILSAFE considerations. Througout, add cygtls.h include. * Makefile.in (DLL_OFILES): Add cygtls.o. Add some more objects to the -fomit-frame-pointer list. * acconfig.h: Remove obsolete settings. * config.h.in: Ditto. * bsdlib.cc: Add cygtls.h include. * configure.in: Remove --enable-extra-threadsafe-checking. * configure: Regenerate. * cygtls.h (_local_storage): New struct renamed from _winsup_t (sic). (_threadinfo:local_clib): Add new field. (_threadinfo::locals): Ditto. (_threadinfo::init_thread): Accept second _reent * argument. (_threadinfo::call): Define as regparm. (CYGTLS_PADSIZE): Remove unnecessary slop. (_getreent): Define as a macro. * thread.h: Remove _CYG_THREAD_FAILSAFE and MT_SAFE stuff. (_winsup_t): Move to cygtls.h. (ResourceLocks::ResourceLocks): Eliminate empty constructor. (MTinterface::reents): Eliminate. (MTinterface::thread_self_key): Eliminate. (MTinterface::MTinterface): Eliminate. * dcrt0.cc: Include stdio.h for _impure_ptr initialization. (do_global_ctors): Remove run_ctors_p (sic) considerations. Don't call atexit here. (__main): Initialize destructors for user here. (dll_crt0_1): Accept a dummy argument. Don't call init_thread here. Don't set _impure_ptr here. Call do_global_ctors after more things have been initialized. (_dll_crt0): Define zeros buffer as max of needed size of CYGTLS_PADSIZE so that it can be used for two purposes while minimizing stack usage. Initialize _impure_ptr specifically, for speed. Call dll_crt0_1 with buffer argument. (cygwin_dll_init): Call dll_crt0_1 with dummy argument. * dtable.cc (dtable::find_unused_handle): Remove call to AssertResourceOwner. * exceptions.cc: Move _threadinfo stuff to new file. * cygtls.cc: New file. * gentls_offsets: Accommodate increasing complexity of cygtls.h. * hires.h (hires_base::~hires_base): Remove. * init.cc (dll_entry): Remove setting of reents. * thread.cc: Remove syslog.h include. (__getreent): Simplify to use _my_tls. (_reent_winsup): Delete. (AssertResourceOwner): Delete. (MTinterface::Init): Remove setting of _clib and _winsup, with all that entails. (MTinterface::fixup_after_fork): Ditto. (pthread::thread_init_wrapper): Ditto. Also remove call to set_tls_self_pointer. (pthread::set_tls_self_pointer): Eliminate. (pthread::get_tls_self_pointer): Just return _my_tls.tid; (__reent_t::init_clib): Eliminate. * tlsoffsets.h: Regenerate.
2003-12-23 17:26:31 +01:00
/* Private class used to handle formatting of syslog message
It is named pass_handler because it does a two-pass handling of log
2000-02-17 20:38:33 +01:00
strings. The first pass counts the length of the string, and the second
one builds the string. */
class pass_handler
{
private:
FILE *fp_;
char *message_;
int total_len_;
void shutdown ();
/* Explicitly disallow copies */
pass_handler (const pass_handler &);
pass_handler & operator = (const pass_handler &);
public:
pass_handler ();
~pass_handler ();
int initialize (int);
int print (const char *,...);
int print_va (const char *, va_list);
char *get_message () const { return message_; }
void set_message (char *s) { message_ = s; *message_ = '\0'; }
2000-02-17 20:38:33 +01:00
};
pass_handler::pass_handler () : fp_ (0), message_ (0), total_len_ (0)
{
;
}
pass_handler::~pass_handler ()
{
shutdown ();
}
void
pass_handler::shutdown ()
{
if (fp_ != NULL)
2000-02-17 20:38:33 +01:00
{
fclose (fp_);
fp_ = 0;
}
}
int
pass_handler::initialize (int pass_number)
{
shutdown ();
if (pass_number)
return total_len_ + 1;
fp_ = fopen ("/dev/null", "wb");
setbuf (fp_, NULL);
if (fp_ == NULL)
2000-02-17 20:38:33 +01:00
{
debug_printf ("failed to open /dev/null");
return -1;
2000-02-17 20:38:33 +01:00
}
total_len_ = 0;
2000-02-17 20:38:33 +01:00
return 0;
}
int
pass_handler::print (const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
int ret = print_va (fmt, ap);
va_end (ap);
return ret;
}
int
pass_handler::print_va (const char *fmt, va_list list)
{
if (fp_ != NULL)
2000-02-17 20:38:33 +01:00
{
int len = vfprintf (fp_, fmt, list);
if (len < 0)
return -1;
total_len_ += len;
return 0;
2000-02-17 20:38:33 +01:00
}
else if (message_ != NULL)
2000-02-17 20:38:33 +01:00
{
char *printpos = &message_[strlen (message_)];
vsprintf (printpos, fmt, list);
return 0;
}
debug_printf ("FAILURE ! fp_ and message_ both 0!! ");
return -1;
}
static NO_COPY muto try_connect_guard;
static enum {
not_inited,
inited_failed,
inited_dgram,
inited_stream
} syslogd_inited;
static int syslogd_sock = -1;
extern "C" int cygwin_socket (int, int, int);
extern "C" int cygwin_connect (int, const struct sockaddr *, int);
extern int get_inet_addr (const struct sockaddr *, int,
struct sockaddr_storage *, int *,
int * = NULL, int * = NULL);
static void
connect_syslogd ()
{
int fd;
struct sockaddr_un sun;
struct sockaddr_storage sst;
int len, type;
if (syslogd_inited != not_inited && syslogd_sock >= 0)
close (syslogd_sock);
syslogd_inited = inited_failed;
syslogd_sock = -1;
sun.sun_family = AF_LOCAL;
strncpy (sun.sun_path, _PATH_LOG, sizeof sun.sun_path);
if (get_inet_addr ((struct sockaddr *) &sun, sizeof sun, &sst, &len, &type))
return;
if ((fd = cygwin_socket (AF_LOCAL, type, 0)) < 0)
return;
if (cygwin_connect (fd, (struct sockaddr *) &sun, sizeof sun) == 0)
{
/* connect on a dgram socket always succeeds. We still don't know
if syslogd is actually listening. */
if (type == SOCK_DGRAM)
2005-05-02 05:50:11 +02:00
{
tmp_pathbuf tp;
PMIB_UDPTABLE tab = (PMIB_UDPTABLE) tp.w_get ();
DWORD size = 65536;
bool found = false;
struct sockaddr_in *sa = (struct sockaddr_in *) &sst;
if (GetUdpTable (tab, &size, FALSE) == NO_ERROR)
{
for (DWORD i = 0; i < tab->dwNumEntries; ++i)
if (tab->table[i].dwLocalAddr == sa->sin_addr.s_addr
&& tab->table[i].dwLocalPort == sa->sin_port)
{
found = true;
break;
}
if (!found)
{
/* No syslogd is listening. */
close (fd);
return;
}
}
}
syslogd_inited = type == SOCK_DGRAM ? inited_dgram : inited_stream;
}
syslogd_sock = fd;
fcntl64 (syslogd_sock, F_SETFD, FD_CLOEXEC);
debug_printf ("found /dev/log, fd = %d, type = %s",
fd, syslogd_inited == inited_stream ? "STREAM" : "DGRAM");
return;
}
static int
2013-04-23 11:44:36 +02:00
try_connect_syslogd (int priority, const char *msg, size_t len)
{
ssize_t ret = -1;
try_connect_guard.init ("try_connect_guard")->acquire ();
if (syslogd_inited == not_inited)
connect_syslogd ();
if (syslogd_inited != inited_failed)
{
char pribuf[16];
sprintf (pribuf, "<%d>", priority);
struct iovec iv[2] =
{
2005-12-22 06:57:54 +01:00
{ pribuf, strlen (pribuf) },
{ (char *) msg, len }
};
ret = writev (syslogd_sock, iv, 2);
/* If the syslog daemon has been restarted and /dev/log was
2006-05-28 17:50:14 +02:00
a stream socket, the connection is broken. In this case,
try to reopen the socket and try again. */
if (ret < 0 && syslogd_inited == inited_stream)
{
connect_syslogd ();
if (syslogd_sock >= 0)
ret = writev (syslogd_sock, iv, 2);
}
/* If write fails and LOG_CONS is set, return failure to vsyslog so
2005-05-02 05:50:11 +02:00
it falls back to the usual logging method for this OS. */
if (ret >= 0 || !(syslog_globals.process_logopt & LOG_CONS))
2005-05-02 05:50:11 +02:00
ret = syslogd_sock;
}
try_connect_guard.release ();
return ret;
}
/* syslog: creates the log message and writes to /dev/log, or to the
NT system log if /dev/log isn't available.
FIXME. WinNT system log messages don't look pretty, but in order to
fix this we have to embed resources in the code and tell the NT
registry where we are, blech (what happens if we move ?). We could,
however, add the resources in Cygwin and always point to that. */
2000-02-17 20:38:33 +01:00
extern "C" void
vsyslog (int priority, const char *message, va_list ap)
2000-02-17 20:38:33 +01:00
{
2013-04-23 11:44:36 +02:00
debug_printf ("%y %s", priority, message);
/* If the priority fails the current mask, reject */
if ((LOG_MASK (LOG_PRI (priority)) & syslog_globals.process_logmask) == 0)
{
2013-04-23 11:44:36 +02:00
debug_printf ("failing message %y due to priority mask %y",
priority, syslog_globals.process_logmask);
return;
}
/* Set default facility to LOG_USER if not yet set via openlog. */
if (!syslog_globals.process_facility)
syslog_globals.process_facility = LOG_USER;
/* Add default facility if not in the given priority. */
if (!(priority & LOG_FACMASK))
priority |= syslog_globals.process_facility;
2000-02-17 20:38:33 +01:00
/* Translate %m in the message to error text */
char *errtext = strerror (get_errno ());
int errlen = strlen (errtext);
int numfound = 0;
2000-02-17 20:38:33 +01:00
for (const char *cp = message; *cp; cp++)
if (*cp == '%' && cp[1] == 'm')
numfound++;
2000-02-17 20:38:33 +01:00
char *newmessage = (char *) alloca (strlen (message) +
(errlen * numfound) + 1);
2000-02-17 20:38:33 +01:00
if (newmessage == NULL)
{
debug_printf ("failed to allocate newmessage");
return;
}
2000-02-17 20:38:33 +01:00
char *dst = newmessage;
for (const char *cp2 = message; *cp2; cp2++)
if (*cp2 == '%' && cp2[1] == 'm')
2000-02-17 20:38:33 +01:00
{
cp2++;
strcpy (dst, errtext);
while (*dst)
dst++;
2000-02-17 20:38:33 +01:00
}
else
*dst++ = *cp2;
2000-02-17 20:38:33 +01:00
*dst = '\0';
message = newmessage;
2000-02-17 20:38:33 +01:00
/* Work out the priority type - we ignore the facility for now.. */
WORD eventType;
switch (LOG_PRI (priority))
{
case LOG_EMERG:
case LOG_ALERT:
case LOG_CRIT:
case LOG_ERR:
eventType = EVENTLOG_ERROR_TYPE;
break;
case LOG_WARNING:
eventType = EVENTLOG_WARNING_TYPE;
break;
case LOG_NOTICE:
case LOG_INFO:
case LOG_DEBUG:
eventType = EVENTLOG_INFORMATION_TYPE;
break;
default:
eventType = EVENTLOG_ERROR_TYPE;
break;
}
2000-02-17 20:38:33 +01:00
/* We need to know how long the buffer needs to be.
The only legal way I can see of doing this is to
do a vfprintf to /dev/null, and count the bytes
output, then do it again to a malloc'ed string. This
is ugly, slow, but prevents core dumps :-).
*/
pass_handler pass;
for (int pass_number = 0; pass_number < 2; ++pass_number)
{
int n = pass.initialize (pass_number);
if (n == -1)
return;
else if (n > 0)
pass.set_message ((char *) alloca (n));
2000-02-17 20:38:33 +01:00
/* Deal with ident_string */
if (syslog_globals.process_ident != NULL)
{
if (pass.print ("%ls: ", syslog_globals.process_ident) == -1)
return;
}
if (syslog_globals.process_logopt & LOG_PID)
{
if (pass.print ("PID %u: ", getpid ()) == -1)
return;
}
2000-02-17 20:38:33 +01:00
/* Print out the variable part */
if (pass.print_va (message, ap) == -1)
return;
2000-02-17 20:38:33 +01:00
}
char *total_msg = pass.get_message ();
2013-04-23 11:44:36 +02:00
size_t len = strlen (total_msg);
if (len != 0 && (total_msg[len - 1] == '\n'))
total_msg[--len] = '\0';
2000-02-17 20:38:33 +01:00
if (syslog_globals.process_logopt & LOG_PERROR)
{
write (STDERR_FILENO, total_msg, len);
write (STDERR_FILENO, "\n", 1);
}
int fd;
if ((fd = try_connect_syslogd (priority, total_msg, len + 1)) < 0)
{
/* If syslogd isn't present, open the event log and send the message */
HANDLE hEventSrc;
hEventSrc = RegisterEventSourceW (NULL, syslog_globals.process_ident
?: CYGWIN_LOG_NAME);
if (!hEventSrc)
debug_printf ("RegisterEventSourceW, %E");
else
{
wchar_t *msg_strings[1];
tmp_pathbuf tp;
msg_strings[0] = tp.w_get ();
sys_mbstowcs (msg_strings[0], NT_MAX_PATH, total_msg);
if (!ReportEventW (hEventSrc, eventType, 0, 0, cygheap->user.sid (),
1, 0, (const wchar_t **) msg_strings, NULL))
debug_printf ("ReportEventW, %E");
DeregisterEventSource (hEventSrc);
}
}
2000-02-17 20:38:33 +01:00
}
extern "C" void
syslog (int priority, const char *message, ...)
{
va_list ap;
va_start (ap, message);
vsyslog (priority, message, ap);
va_end (ap);
}
static NO_COPY muto klog_guard;
fhandler_mailslot *dev_kmsg;
extern "C" void
vklog (int priority, const char *message, va_list ap)
{
/* TODO: kernel messages are under our control entirely and they should
be quick. No playing with /dev/null, but a fixed upper size for now. */
char buf[2060]; /* 2048 + a prority */
if (!(priority & ~LOG_PRIMASK))
priority = LOG_KERN | LOG_PRI (priority);
__small_sprintf (buf, "<%d>", priority);
__small_vsprintf (buf + strlen (buf), message, ap);
klog_guard.init ("klog_guard")->acquire ();
if (!dev_kmsg)
dev_kmsg = (fhandler_mailslot *) build_fh_name ("/dev/kmsg");
if (dev_kmsg && !dev_kmsg->get_handle ())
dev_kmsg->open (O_WRONLY, 0);
if (dev_kmsg && dev_kmsg->get_handle ())
dev_kmsg->write (buf, strlen (buf) + 1);
klog_guard.release ();
}
extern "C" void
klog (int priority, const char *message, ...)
{
va_list ap;
va_start (ap, message);
vklog (priority, message, ap);
va_end (ap);
}
extern "C" void
2000-02-17 20:38:33 +01:00
closelog (void)
{
try_connect_guard.init ("try_connect_guard")->acquire ();
if (syslogd_inited != not_inited && syslogd_sock >= 0)
{
close (syslogd_sock);
syslogd_sock = -1;
syslogd_inited = not_inited;
}
try_connect_guard.release ();
2000-02-17 20:38:33 +01:00
}