1 /*
2  * Copyright (C) 2006-2009 Citrix Systems Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published
6  * by the Free Software Foundation; version 2.1 only. with the special
7  * exception on linking described in file LICENSE.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU Lesser General Public License for more details.
13  */
14 
15 #include <syslog.h>
16 #include <string.h>
17 #include <caml/fail.h>
18 #include <caml/mlvalues.h>
19 #include <caml/memory.h>
20 #include <caml/alloc.h>
21 #include <caml/custom.h>
22 #include <caml/signals.h>
23 
24 static int __syslog_level_table[] = {
25 	LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING,
26 	LOG_NOTICE, LOG_INFO, LOG_DEBUG
27 };
28 
29 static int __syslog_facility_table[] = {
30 	LOG_AUTH, LOG_AUTHPRIV, LOG_CRON, LOG_DAEMON, LOG_FTP, LOG_KERN,
31 	LOG_LOCAL0, LOG_LOCAL1, LOG_LOCAL2, LOG_LOCAL3,
32 	LOG_LOCAL4, LOG_LOCAL5, LOG_LOCAL6, LOG_LOCAL7,
33 	LOG_LPR | LOG_MAIL | LOG_NEWS | LOG_SYSLOG | LOG_USER | LOG_UUCP
34 };
35 
stub_syslog(value facility,value level,value msg)36 value stub_syslog(value facility, value level, value msg)
37 {
38 	CAMLparam3(facility, level, msg);
39 	char *c_msg = strdup(String_val(msg));
40 	char *s = c_msg, *ss;
41 	int c_facility = __syslog_facility_table[Int_val(facility)]
42 	               | __syslog_level_table[Int_val(level)];
43 
44 	if ( !c_msg )
45 		caml_raise_out_of_memory();
46 
47 	/*
48 	 * syslog() doesn't like embedded newlines, and c_msg generally
49 	 * contains them.
50 	 *
51 	 * Split the message in place by converting \n to \0, and issue one
52 	 * syslog() call per line, skipping the final iteration if c_msg ends
53 	 * with a newline anyway.
54 	 */
55 	do {
56 		ss = strchr(s, '\n');
57 		if ( ss )
58 			*ss = '\0';
59 		else if ( *s == '\0' )
60 			break;
61 
62 		caml_enter_blocking_section();
63 		syslog(c_facility, "%s", s);
64 		caml_leave_blocking_section();
65 
66 		s = ss + 1;
67 	} while ( ss );
68 
69 	free(c_msg);
70 	CAMLreturn(Val_unit);
71 }
72