Example #1
0
CAMLprim value stub_asl_new_msg() {
  CAMLparam0();
  caml_release_runtime_system();
  aslmsg msg = asl_new(ASL_TYPE_MSG);
  caml_acquire_runtime_system();
  CAMLreturn(alloc_message(msg));
}
int
main(void)
{
    kern_return_t kr;
    struct stat   statbuf;
   
    // Initialize a message for use with the Apple System Log (asl) facility.
    logmsg = asl_new(ASL_TYPE_MSG);
    asl_set(logmsg, "Facility", "Sleeper Daemon");
   
    // If the shutdown flag file exists, we are destroying the service;
    // otherwise, we are trying to be a server.
    if (stat(SERVICE_SHUTDOWN_FILE, &statbuf) == 0) {
        kr = unregister_bootstrap_service();
        MY_ASL_LOG("destroying service %s\n", SERVICE_NAME);
    } else {
        kr = register_bootstrap_service();
        MY_ASL_LOG("starting up service %s\n", SERVICE_NAME);
    }
   
    if (kr != KERN_SUCCESS) {
        // NB: When unregistering, we will get here if the unregister succeeded.
        mach_error("bootstrap_register", kr);
        exit(kr);
    }
   
    MY_ASL_LOG("server loop ready\n");
   
    while (1) // Dummy server loop.
        sleep(60);
   
    exit(0);
}
Example #3
0
void SFB::Logger::Log(levels level, const char *facility, const char *message, const char *function, const char *file, int line)
{
	if(currentLogLevel < level)
		return;

	aslmsg msg = asl_new(ASL_TYPE_MSG);

	if(facility)
		asl_set(msg, ASL_KEY_FACILITY, facility);

	if(function)
		asl_set(msg, "Function", function);

	if(file)
		asl_set(msg, "File", file);

	if(-1 != line) {
		char buf [32];
		if(snprintf(buf, sizeof(buf), "%d", line))
			asl_set(msg, "Line", buf);
	}

	asl_log(nullptr, msg, level, "%s", message);

	asl_free(msg);
}
Example #4
0
//
// MessageTracer support
//
MessageTrace::MessageTrace(const char *domain, const char *signature)
{
	mAsl = asl_new(ASL_TYPE_MSG);
	if (domain)
		asl_set(mAsl, "com.apple.message.domain", domain);
	if (signature)
		asl_set(mAsl, "com.apple.message.signature", signature);
}
Example #5
0
void __security_debug(const char *scope, const char *function,
    const char *file, int line, const char *format, ...)
{
#if !defined(NDEBUG)
	pthread_once(&__security_debug_once, __security_debug_init);

	CFStringRef scopeName = NULL;
	/* Scope NULL is always enabled. */
	if (scope) {
		/* Check if the scope is enabled. */
		if (scopeSet) {
			scopeName = copyScopeName(scope, strlen(scope));
			if (negate == CFSetContainsValue(scopeSet, scopeName)) {
				CFRelease(scopeName);
				return;
			}
		} else if (!negate) {
			return;
		}
	}

	CFStringRef formatStr = CFStringCreateWithCString(kCFAllocatorDefault,
		format, kCFStringEncodingUTF8);
	va_list args;
	va_start(args, format);
	CFStringRef message = CFStringCreateWithFormatAndArguments(
		kCFAllocatorDefault, NULL, formatStr, args);
	va_end(args);
	time_t now = time(NULL);
	char *date = ctime(&now);
	date[19] = '\0';
	CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
		CFSTR("%s %-*s %s %@\n"), date + 4, MAX_SCOPE_LENGTH - 1,
        scope ? scope : "", function, message);
	CFShow(logStr);
    char logMsg[4096];
    if (CFStringGetCString(logStr, logMsg, sizeof(logMsg), kCFStringEncodingUTF8)) {
#if 0
        asl_log(NULL, NULL, ASL_LEVEL_INFO, logMsg);
#else
        aslmsg msg = asl_new(ASL_TYPE_MSG);
        if (scope) {
            asl_set(msg, ASL_KEY_FACILITY, scope);
        }
        asl_set(msg, ASL_KEY_LEVEL, ASL_STRING_INFO);
        asl_set(msg, ASL_KEY_MSG, logMsg);
        asl_send(NULL, msg);
        asl_free(msg);
#endif
    }
	CFRelease(logStr);
	CFRelease(message);
	CFRelease(formatStr);
	if (scopeName)
		CFRelease(scopeName);
#endif
}
Example #6
0
// create a new ASL log
void asepsis_setup_logging(void) {
    static int asepsis_logging_initialized = 0;
    if (asepsis_logging_initialized) {
        return;
    }
    asepsis_logging_initialized = 1;
	g_asepsis_asl = asl_open("Asepsis", "dylib", 0);
	g_asepsis_log_msg = asl_new(ASL_TYPE_MSG);
	asl_set(g_asepsis_log_msg, ASL_KEY_SENDER, "Asepsis");    
}
static void
sec_debug_init() {
	char *ccEnvStdErr = getenv("CC_STDERR");
	
	if(ccEnvStdErr != NULL && strncmp(ccEnvStdErr, "yes", 3) == 0) std_options |= ASL_OPT_STDERR;
	aslhandle = asl_open(std_ident, std_facility, std_options);
	
	msgptr = asl_new(ASL_TYPE_MSG);
	asl_set(msgptr, ASL_KEY_FACILITY, "com.apple.infosec");
}
Example #8
0
void RARCH_LOG_V(const char *tag, const char *fmt, va_list ap)
{
#if TARGET_OS_IPHONE
   static int asl_inited = 0;
#if !TARGET_IPHONE_SIMULATOR
static aslclient asl_client;
#endif
#endif

   if (!RARCH_LOG_VERBOSE())
      return;
#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR
   vprintf(fmt, ap);
#else
   if (!asl_inited)
   {
      asl_client = asl_open("RetroArch", "com.apple.console", ASL_OPT_STDERR | ASL_OPT_NO_DELAY);
      asl_inited = 1;
   }
   aslmsg msg = asl_new(ASL_TYPE_MSG);
   asl_set(msg, ASL_KEY_READ_UID, "-1");
   if (tag)
      asl_log(asl_client, msg, ASL_LEVEL_NOTICE, "%s", tag);
   asl_vlog(asl_client, msg, ASL_LEVEL_NOTICE, fmt, ap);
   asl_free(msg);
#endif
#elif defined(_XBOX1)
   /* FIXME: Using arbitrary string as fmt argument is unsafe. */
   char msg_new[1024], buffer[1024];
   snprintf(msg_new, sizeof(msg_new), "%s: %s %s",
         PROGRAM_NAME,
         tag ? tag : "",
         fmt);
   wvsprintf(buffer, msg_new, ap);
   OutputDebugStringA(buffer);
#elif defined(ANDROID)
   int prio = ANDROID_LOG_INFO;
   if (tag)
   {
      if (string_is_equal("[WARN]", tag))
         prio = ANDROID_LOG_WARN;
      else if (string_is_equal("[ERROR]", tag))
         prio = ANDROID_LOG_ERROR;
   }
   __android_log_vprint(prio, PROGRAM_NAME, fmt, ap);
#else
   fprintf(LOG_FILE, "%s %s :: ", PROGRAM_NAME, tag ? tag : "[INFO]");
   vfprintf(LOG_FILE, fmt, ap);
   fflush(LOG_FILE);
#endif
}
Example #9
0
void SMBLogInfo(const char *fmt, int log_level,...)
{
    int save_errno = errno;
    va_list ap;
    aslmsg m = asl_new(ASL_TYPE_MSG);


    va_start(ap, log_level);
    asl_vlog(NULL, m, log_level, fmt, ap);
    va_end(ap);
    asl_free(m);
    errno = save_errno; /* Never let this routine change errno */
}
void _IOHIDLog(int level, const char *format, ...)
{
    aslmsg msg = NULL;
    
    if (1) {
        msg = asl_new(ASL_TYPE_MSG);
        asl_set(msg, ASL_KEY_FACILITY, "com.apple.iokit.IOHID");
    }
    va_list ap;
    va_start(ap, format);
    asl_vlog(NULL, msg, level, format, ap);
    va_end(ap);
    if (msg) {
        asl_free(msg);
    }
}
Example #11
0
static
void
sessionLogEvent (const char *domain, const char *event_msg)
{
	aslmsg m;

	if (!domain || !event_msg) {
		return;
	}

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, ASL_KEY_FACILITY, domain);
	asl_set(m, ASL_KEY_MSG, sessionString);
	asl_log(NULL, m, ASL_LEVEL_NOTICE, "SCNCController: %s", event_msg);
	asl_free(m);
}
Example #12
0
uint32_t
asl_store_statistics(asl_store_t *s, aslmsg *msg)
{
	aslmsg out;

	if (s == NULL) return ASL_STATUS_INVALID_STORE;
	if (msg == NULL) return ASL_STATUS_INVALID_ARG;

	out = asl_new(ASL_TYPE_MSG);
	if (out == NULL) return ASL_STATUS_NO_MEMORY;

	/* does nothing for now */

	*msg = out;
	return ASL_STATUS_OK;
}
Example #13
0
aslmsg createAslQuery(const QueryContext& context) {
  aslmsg query = asl_new(ASL_TYPE_QUERY);

  // Set constraints in query
  for (const auto& it : context.constraints) {
    const std::string& key = it.first;
    ColumnType col_type = it.second.affinity;
    for (const auto& constraint : it.second.getAll()) {
      addQueryOp(query,
                 key,
                 constraint.expr,
                 static_cast<ConstraintOperator>(constraint.op),
                 col_type);
    }
  }
  return query;
}
Example #14
0
static void
sessionTracerLogStop (const char *domain, const char *type, int caused_by_failure, const char *reason, u_int32_t established, u_int32_t duration)
{
	aslmsg      m;
	char *      buf;
	char		data[256] = {0};

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, "com.apple.message.domain", domain);
	asl_set(m, "com.apple.message.type", type);
	asl_set(m, ASL_KEY_FACILITY, domain);
	asl_set(m, ASL_KEY_MSG, sessionString);
	if (caused_by_failure) {
		asl_set(m, "com.apple.message.result", CONSTSTR("failure"));	// failure
	} else {
		asl_set(m, "com.apple.message.result", CONSTSTR("success"));	// success
	}
	if (reason) {
		asl_set(m, "com.apple.message.reason", reason);
	} else {
		// reason was NULL; make sure success/failure have different signature
		if (caused_by_failure) {
			asl_set(m, "com.apple.message.reason", CONSTSTR("Internal/Server-side error"));
		} else {
			asl_set(m, "com.apple.message.reason", CONSTSTR("User/System initiated the disconnect"));
		}
	}
	
	buf = sessionTracerBucketizeTime(duration);
	
	if (established) {
		asl_set(m, "com.apple.message.connectiontime", buf);	// stuff the up time into value
		snprintf(data, sizeof(data), "SCNCController: Disconnecting.");
		asl_set(m, "com.apple.message.controller", data);
		asl_log(NULL, m, ASL_LEVEL_NOTICE, "");
	} else {
		asl_set(m, "com.apple.message.negotiatingtime", buf);	/// stuff the negoing time into value2
		snprintf(data, sizeof(data), "SCNCController: Disconnecting.");
		asl_set(m, "com.apple.message.controller", data);
		asl_log(NULL, m, ASL_LEVEL_NOTICE, "");
	}
	
	asl_free(m);
}
Example #15
0
TEST_F(AslTests, test_read_asl_row) {
  aslmsg row = asl_new(ASL_TYPE_MSG);
  ASSERT_EQ(0, asl_set(row, "Sender", "foo"));
  ASSERT_EQ(0, asl_set(row, "Level", "1"));
  ASSERT_EQ(0, asl_set(row, "Message", "bar"));
  ASSERT_EQ(0, asl_set(row, "Bang", "bang_val"));

  Row r;
  readAslRow(row, r);

  ASSERT_EQ((size_t)4, r.size());

  ASSERT_EQ("foo", r["sender"]);
  ASSERT_EQ("1", r["level"]);
  ASSERT_EQ("bar", r["message"]);
  ASSERT_EQ((size_t)0, r.count("bang"));
  ASSERT_EQ("{\"Bang\":\"bang_val\"}\n", r["extra"]);

  asl_release(row);
}
Example #16
0
void __libclog_log( int level, char * fmt, va_list ap )
{
    aslmsg msg;
    
    if( __libclog_client_connected == false )
    {
        __libclog_create_client();
    }
    
    if( __libclog_client == NULL )
    {
        fprintf( stderr, "Impossible to create the ASL client\n" );
        exit( EXIT_FAILURE );
    }
    
    
    msg = asl_new( ASL_TYPE_MSG );
    
    asl_set( msg, ASL_KEY_FACILITY, "com.apple.console" );
    asl_vlog( __libclog_client, msg, level, fmt, ap );
}
Example #17
0
void
vsyslog(int pri, const char *fmt, va_list ap)
{
	int fac;
	aslmsg facmsg;
	const char *facility;

	facmsg = NULL;
	fac = pri & LOG_FACMASK;
	if (fac != 0)
	{
		facility = asl_syslog_faciliy_num_to_name(fac);
		if (facility != NULL)
		{
			facmsg = asl_new(ASL_TYPE_MSG);
			asl_set(facmsg, ASL_KEY_FACILITY, facility);
		}
	}

	asl_vlog(_sl_asl, facmsg, LOG_PRI(pri), fmt, ap);
	if (facmsg != NULL) asl_free(facmsg);
}
Example #18
0
void
sessionTracerLogEstablished (struct service *serv)
{
	if (serv) {
		aslmsg      m;
		char data[256] = {0};
		const char *type = sessionGetType(serv);
		
		if (!strcmp(type, nullString)) {
			/* We do not trace VPN */
			return;
		}
		
		const char *domain	= sessionGetConnectionLessDomain();
		
		if (sessionCheckIfEstablished(serv)) {
			// already established no need to log (mostly here due to sleep-wake)
			return;
		}
		
		sessionIsEstablished(serv);
		
		m = asl_new(ASL_TYPE_MSG);
		asl_set(m, "com.apple.message.domain", domain);
		asl_set(m, "com.apple.message.type", type);
		asl_set(m, "com.apple.message.result", CONSTSTR("success"));
		asl_set(m, "com.apple.message.reason", CONSTSTR("established"));
		asl_set(m, ASL_KEY_FACILITY, domain);
		asl_set(m, ASL_KEY_MSG, sessionString);
		
		sessionTracerLogPPPInfo(m, serv);
		
		snprintf(data, sizeof(data), "SCNCController: Connected.");
		asl_set(m, "com.apple.message.controller", data);
		asl_log(NULL, m, ASL_LEVEL_NOTICE, "");
		asl_free(m);
	}
}
Example #19
0
/*
 * Open and set up system logging.
 */
void
auditd_openlog(int debug, gid_t gid)
{
	uint32_t opt = 0;	
	char *cp = NULL;

	if (debug)
		opt = ASL_OPT_STDERR;

	au_aslclient = asl_open("auditd", "com.apple.auditd", opt);
	au_aslmsg = asl_new(ASL_TYPE_MSG); 

#ifdef ASL_KEY_READ_UID
	/*
	 * Make it only so the audit administrator and members of the audit
	 * review group (if used) have access to the auditd system log messages.
	 */
	asl_set(au_aslmsg, ASL_KEY_READ_UID, "0");
	asprintf(&cp, "%u", gid);	
	if (cp != NULL) {
#ifdef ASL_KEY_READ_GID
		asl_set(au_aslmsg, ASL_KEY_READ_GID, cp);
#endif
		free(cp);
	}
#endif

	/*
	 * Set the client-side system log filtering.
	 */
	if (debug)
		asl_set_filter(au_aslclient,
		    ASL_FILTER_MASK_UPTO(ASL_LEVEL_DEBUG));
	else
		asl_set_filter(au_aslclient,
		    ASL_FILTER_MASK_UPTO(ASL_LEVEL_INFO)); 	
}
static CFMutableArrayRef get_log_handlers()
{
    static dispatch_once_t handlers_once;
    
    dispatch_once(&handlers_once, ^{
        sSecurityLogHandlers = CFArrayCreateMutableForCFTypes(kCFAllocatorDefault);
        
        CFArrayAppendValue(sSecurityLogHandlers, ^(const char *level, CFStringRef scope, const char *function,
                                                   const char *file, int line, CFStringRef message){
            CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@ %s %@\n"), scope ? scope : CFSTR(""), function, message);
            CFStringPerformWithCString(logStr, ^(const char *logMsg) {
                aslmsg msg = asl_new(ASL_TYPE_MSG);
                if (scope) {
                    CFStringPerformWithCString(scope, ^(const char *scopeStr) {
                        asl_set(msg, ASL_KEY_FACILITY, scopeStr);
                    });
                }
                asl_set(msg, ASL_KEY_LEVEL, level);
                asl_set(msg, ASL_KEY_MSG, logMsg);
                asl_send(NULL, msg);
                asl_free(msg);
            });
            CFReleaseSafe(logStr);
        });
Example #21
0
void RARCH_LOG_V(const char *tag, const char *fmt, va_list ap)
{
#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR
   vprintf(fmt, ap);
#else
   static aslclient asl_client;
   static int asl_initialized = 0;
   if (!asl_initialized)
   {
      asl_client      = asl_open(
            file_path_str(FILE_PATH_PROGRAM_NAME),
            "com.apple.console",
            ASL_OPT_STDERR | ASL_OPT_NO_DELAY);
      asl_initialized = 1;
   }
   aslmsg msg = asl_new(ASL_TYPE_MSG);
   asl_set(msg, ASL_KEY_READ_UID, "-1");
   if (tag)
      asl_log(asl_client, msg, ASL_LEVEL_NOTICE, "%s", tag);
   asl_vlog(asl_client, msg, ASL_LEVEL_NOTICE, fmt, ap);
   asl_free(msg);
#endif
#elif defined(_XBOX1)
   {
      /* FIXME: Using arbitrary string as fmt argument is unsafe. */
      char msg_new[1024];
      char buffer[1024];

      msg_new[0] = buffer[0] = '\0';
      snprintf(msg_new, sizeof(msg_new), "%s: %s %s",
            file_path_str(FILE_PATH_PROGRAM_NAME),
            tag ? tag : "",
            fmt);
      wvsprintf(buffer, msg_new, ap);
      OutputDebugStringA(buffer);
   }
#elif defined(ANDROID)
   {
      int prio = ANDROID_LOG_INFO;
      if (tag)
      {
         if (string_is_equal(file_path_str(FILE_PATH_LOG_WARN), tag))
            prio = ANDROID_LOG_WARN;
         else if (string_is_equal(file_path_str(FILE_PATH_LOG_ERROR), tag))
            prio = ANDROID_LOG_ERROR;
      }
      __android_log_vprint(prio,
            file_path_str(FILE_PATH_PROGRAM_NAME),
            fmt,
            ap);
   }
#else

   {
#ifdef HAVE_QT
      char buffer[1024];
#endif
#ifdef HAVE_FILE_LOGGER
      FILE *fp = (FILE*)retro_main_log_file();
#else
      FILE *fp = stderr;
#endif

#ifdef HAVE_QT
      buffer[0] = '\0';
      vsnprintf(buffer, sizeof(buffer), fmt, ap);

      if (fp)
      {
         fprintf(fp, "%s %s", tag ? tag : file_path_str(FILE_PATH_LOG_INFO), buffer);
         fflush(fp);
      }

      ui_companion_driver_log_msg(buffer);
#else
#if defined(NXLINK) && !defined(HAVE_FILE_LOGGER)
          if (nxlink_connected)
             mutexLock(&nxlink_mtx);
#endif
      if (fp)
      {
         fprintf(fp, "%s ",
               tag ? tag : file_path_str(FILE_PATH_LOG_INFO));
         vfprintf(fp, fmt, ap);
         fflush(fp);
      }
#if defined(NXLINK) && !defined(HAVE_FILE_LOGGER)
      if (nxlink_connected)
         mutexUnlock(&nxlink_mtx);
#endif

#endif
   }
#endif
}
Example #22
0
TEST_F(AslTests, test_add_query_op) {
  aslmsg query = asl_new(ASL_TYPE_QUERY);
  ASSERT_EQ((uint32_t)ASL_TYPE_QUERY, asl_get_type(query));
  ASSERT_EQ((size_t)0, asl_count(query));

  const char *key, *val;
  uint32_t op;

  addQueryOp(query, "sender", "bar", EQUALS, TEXT_TYPE);
  ASSERT_EQ((size_t)1, asl_count(query));

  ASSERT_EQ(0, asl_fetch_key_val_op(query, 0, &key, &val, &op));
  ASSERT_STREQ("Sender", key);
  ASSERT_STREQ("bar", val);
  ASSERT_EQ((uint32_t)ASL_QUERY_OP_EQUAL, op);

  addQueryOp(query, "level", "1", GREATER_THAN, INTEGER_TYPE);
  ASSERT_EQ((size_t)2, asl_count(query));
  ASSERT_EQ(0, asl_fetch_key_val_op(query, 1, &key, &val, &op));
  ASSERT_STREQ("Level", key);
  ASSERT_STREQ("1", val);
  ASSERT_EQ((uint32_t)(ASL_QUERY_OP_GREATER | ASL_QUERY_OP_NUMERIC), op);

  addQueryOp(query, "gid", "999", LESS_THAN, BIGINT_TYPE);
  ASSERT_EQ((size_t)3, asl_count(query));
  ASSERT_EQ(0, asl_fetch_key_val_op(query, 2, &key, &val, &op));
  ASSERT_STREQ("GID", key);
  ASSERT_STREQ("999", val);
  ASSERT_EQ((uint32_t)(ASL_QUERY_OP_LESS | ASL_QUERY_OP_NUMERIC), op);

  addQueryOp(query, "facility", "hoo", GREATER_THAN_OR_EQUALS, TEXT_TYPE);
  ASSERT_EQ((size_t)4, asl_count(query));
  ASSERT_EQ(0, asl_fetch_key_val_op(query, 3, &key, &val, &op));
  ASSERT_STREQ("Facility", key);
  ASSERT_STREQ("hoo", val);
  ASSERT_EQ((uint32_t)ASL_QUERY_OP_GREATER_EQUAL, op);

  addQueryOp(query, "pid", "30", LESS_THAN_OR_EQUALS, INTEGER_TYPE);
  ASSERT_EQ((size_t)5, asl_count(query));
  ASSERT_EQ(0, asl_fetch_key_val_op(query, 4, &key, &val, &op));
  ASSERT_STREQ("PID", key);
  ASSERT_STREQ("30", val);
  ASSERT_EQ((uint32_t)(ASL_QUERY_OP_LESS_EQUAL | ASL_QUERY_OP_NUMERIC), op);

  addQueryOp(query, "ref_proc", "%tom%", LIKE, TEXT_TYPE);
  ASSERT_EQ((size_t)6, asl_count(query));
  ASSERT_EQ(0, asl_fetch_key_val_op(query, 5, &key, &val, &op));
  ASSERT_STREQ("RefProc", key);
  ASSERT_STREQ(".*tom.*", val);
  ASSERT_EQ((uint32_t)(ASL_QUERY_OP_EQUAL | ASL_QUERY_OP_REGEX |
                       ASL_QUERY_OP_CASEFOLD),
            op);

  // Queries against the extra column should not be sent to ASL
  addQueryOp(query, "extra", "tom", EQUALS, TEXT_TYPE);
  ASSERT_EQ((size_t)6, asl_count(query));

  // Queries with unsupported operators should not be sent to ASL
  addQueryOp(query, "host", "tom", GLOB, TEXT_TYPE);
  ASSERT_EQ((size_t)6, asl_count(query));

  asl_release(query);
}
static bool OSX_SetCloudKeychainTraceValueForKey(CFStringRef key, int64_t value)
{
	bool result = false;
	
	if (NULL == key)
	{
		return result;
	}
	
	aslmsg mAsl = NULL;
	mAsl = asl_new(ASL_TYPE_MSG);
	if (NULL == mAsl)
	{
		return result;
	}
    
    
    CFStringRef key_str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@%@"), gMessageTracerPrefix, key);
    if (NULL == key_str)
    {
        asl_free(mAsl);
        return result;
    }
	
	CFStringRef value_str = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%lld"), value);
    if (NULL == value_str)
    {
        asl_free(mAsl);
        CFRelease(key_str);
        return result;
    }
    
    CFIndex key_str_numBytes = CFStringGetMaximumSizeForEncoding(CFStringGetLength(key_str), kCFStringEncodingUTF8);
    key_str_numBytes += 1; // For null
    char key_buffer[key_str_numBytes];
    memset(key_buffer, 0, key_str_numBytes);
    if (!CFStringGetCString(key_str, key_buffer, key_str_numBytes, kCFStringEncodingUTF8))
    {
        asl_free(mAsl);
        CFRelease(key_str);
        CFRelease(value_str);
        return result;
    }
    CFRelease(key_str);
    
    CFIndex value_str_numBytes = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value_str), kCFStringEncodingUTF8);
    value_str_numBytes += 1; // For null
    char value_buffer[value_str_numBytes];
    memset(value_buffer, 0, value_str_numBytes);
    if (!CFStringGetCString(value_str, value_buffer, value_str_numBytes, kCFStringEncodingUTF8))
    {
        asl_free(mAsl);
        CFRelease(value_str);
        return result;
    }
    CFRelease(value_str);
	
	asl_set(mAsl, key_buffer, value_buffer);
	asl_log(NULL, mAsl, ASL_LEVEL_NOTICE, "%s", gTopLevelKeyForiCloudKeychainTracing);
	asl_free(mAsl);
	return true;
}
Example #24
0
int main(int argc, char *argv[])
{
    OSStatus            err;
    int                 argIndex;
    Boolean             delay;
    Boolean             waitForWindowServerSession;
    Boolean             forceShow;
    Boolean             cleanExit;
    IBNibRef            nibRef;
    WindowRef           window;
    
    // Initialise our ASL state.

    gASLClient = asl_open(NULL, "PreLoginAgents", 0);
    assert(gASLClient != NULL);
    
    (void) asl_set_filter(gASLClient, ASL_FILTER_MASK_UPTO(ASL_LEVEL_INFO));
    
    gASLMessage = asl_new(ASL_TYPE_MSG);
    assert(gASLMessage != NULL);

    (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Start");

    // Parse our arguments.  We support arguments that allow you to turn off 
    // various special cases within the code.  This makes it easy to test whether 
    // the special cases are still required.
    
    delay = false;
    waitForWindowServerSession = false;
    forceShow = true;
    cleanExit = true;
    for (argIndex = 1; argIndex < argc; argIndex++) {
        if ( strcasecmp(argv[argIndex], "--nodelay") == 0 ) {
            delay = false;
        } else if ( strcasecmp(argv[argIndex], "--delay") == 0 ) {
            delay = true;
        } else if ( strcasecmp(argv[argIndex], "--nowait") == 0 ) {
            waitForWindowServerSession = false;
        } else if ( strcasecmp(argv[argIndex], "--wait") == 0 ) {
            waitForWindowServerSession = true;
        } else if ( strcasecmp(argv[argIndex], "--noforce") == 0 ) {
            forceShow = false;
        } else if ( strcasecmp(argv[argIndex], "--force") == 0 ) {
            forceShow = true;
        } else if ( strcasecmp(argv[argIndex], "--nocleanexit") == 0 ) {
            cleanExit = false;
        } else if ( strcasecmp(argv[argIndex], "--cleanexit") == 0 ) {
            cleanExit = true;
        } else {
            (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Unrecognised argument '%s'", argv[argIndex]);
        }
    }

    // Handle various options.
    
    if (waitForWindowServerSession) {
        WaitForWindowServerSession();
    } else {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Not waiting for CGSessionCopyCurrentDictionary");
    }
    
    if (delay) {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Delaying");
        
        sleep(3);
    } else {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Not delaying");
    }
    
    // Set up our UI.
    
    err = CreateNibReference(CFSTR("main"), &nibRef);
    assert(err == noErr);

    err = CreateWindowFromNib(nibRef, CFSTR("MainWindow"), &window);
    assert(err == noErr);

    DisposeNibReference(nibRef);

    // We have to set kHIWindowBitCanBeVisibleWithoutLogin to let the 
    // system know that we're not accidentally trying to display a window 
    // pre-login.
    //
    // Also, window is a utility window and, by default, these have the 
    // kWindowHideOnSuspendAttribute attribute set.  As our application is a 
    // UI element which never activates, and we want our panel to show regardless, 
    // we must clear kWindowHideOnSuspendAttribute.
    
    static const int    kAttributesToSet[] = {
        kHIWindowBitCanBeVisibleWithoutLogin, 
        0
    };
    static const int    kAttributesToClear[] = {
        kHIWindowBitHideOnSuspend, 
        0
    };
    err = HIWindowChangeAttributes(
        window,
        kAttributesToSet,
        kAttributesToClear
    );
    assert(err == noErr);

    // Due to a problem with the relationship between the UI frameworks and the 
    // window server <rdar://problem/5136400>, ShowWindow is not sufficient to 
    // show the window.  We also have to use BringToFront.
    
    ShowWindow(window);
    if (forceShow) {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Showing window with extreme prejudice");
        BringToFront(window);
    } else {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Showing window normally");
    }

    // Set up our SIGTERM handler.
    
    if (cleanExit) {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Installing SIGTERM handler");
        InstallHandleSIGTERMFromRunLoop();
    } else {
        (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Not installing SIGTERM handler");
    }

    // Go go gadget Carbon!

    (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "RunApplicationEventLoop");
    RunApplicationEventLoop();

    (void) asl_log(gASLClient, gASLMessage, ASL_LEVEL_INFO, "Stop");
    
    return EXIT_SUCCESS;
}
Example #25
0
int					/* O  - 1 if log file open */
cupsdCheckLogFile(cups_file_t **lf,	/* IO - Log file */
	          const char  *logname)	/* I  - Log filename */
{
  char		backname[1024],		/* Backup log filename */
		filename[1024],		/* Formatted log filename */
		*ptr;			/* Pointer into filename */
  const char	*logptr;		/* Pointer into log filename */


 /*
  * See if we have a log file to check...
  */

  if (!lf || !logname || !logname[0])
    return (1);

 /*
  * Handle logging to stderr...
  */

  if (!strcmp(logname, "stderr"))
  {
    *lf = LogStderr;
    return (1);
  }

 /*
  * Format the filename as needed...
  */

  if (!*lf ||
      (strncmp(logname, "/dev/", 5) && cupsFileTell(*lf) > MaxLogSize &&
       MaxLogSize > 0))
  {
   /*
    * Handle format strings...
    */

    filename[sizeof(filename) - 1] = '\0';

    if (logname[0] != '/')
    {
      strlcpy(filename, ServerRoot, sizeof(filename));
      strlcat(filename, "/", sizeof(filename));
    }
    else
      filename[0] = '\0';

    for (logptr = logname, ptr = filename + strlen(filename);
         *logptr && ptr < (filename + sizeof(filename) - 1);
	 logptr ++)
      if (*logptr == '%')
      {
       /*
        * Format spec...
	*/

        logptr ++;
	if (*logptr == 's')
	{
	 /*
	  * Insert the server name...
	  */

	  strlcpy(ptr, ServerName, sizeof(filename) - (size_t)(ptr - filename));
	  ptr += strlen(ptr);
	}
        else
	{
	 /*
	  * Otherwise just insert the character...
	  */

	  *ptr++ = *logptr;
	}
      }
      else
	*ptr++ = *logptr;

    *ptr = '\0';
  }

 /*
  * See if the log file is open...
  */

  if (!*lf)
  {
   /*
    * Nope, open the log file...
    */

    if ((*lf = cupsFileOpen(filename, "a")) == NULL)
    {
     /*
      * If the file is in CUPS_LOGDIR then try to create a missing directory...
      */

      if (!strncmp(filename, CUPS_LOGDIR, strlen(CUPS_LOGDIR)))
      {
       /*
        * Try updating the permissions of the containing log directory, using
	* the log file permissions as a basis...
	*/

        mode_t log_dir_perm = (mode_t)(0300 | LogFilePerm);
					/* LogFilePerm + owner write/search */
	if (log_dir_perm & 0040)
	  log_dir_perm |= 0010;		/* Add group search */
	if (log_dir_perm & 0004)
	  log_dir_perm |= 0001;		/* Add other search */

        cupsdCheckPermissions(CUPS_LOGDIR, NULL, log_dir_perm, RunUser, Group, 1, -1);

        *lf = cupsFileOpen(filename, "a");
      }

      if (*lf == NULL)
      {
#ifdef HAVE_ASL_H
	asl_object_t	m;		/* Log message */

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, ASL_KEY_FACILITY, "org.cups.cupsd");
	asl_log(NULL, m, ASL_LEVEL_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
	asl_release(m);

#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
        sd_journal_print(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));

#else
	syslog(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
#endif /* HAVE_ASL_H */

        if (FatalErrors & CUPSD_FATAL_LOG)
	  cupsdEndProcess(getpid(), 0);

	return (0);
      }
    }

    if (strncmp(filename, "/dev/", 5))
    {
     /*
      * Change ownership and permissions of non-device logs...
      */

      fchown(cupsFileNumber(*lf), RunUser, Group);
      fchmod(cupsFileNumber(*lf), LogFilePerm);
    }
  }

 /*
  * Do we need to rotate the log?
  */

  if (strncmp(logname, "/dev/", 5) && cupsFileTell(*lf) > MaxLogSize &&
      MaxLogSize > 0)
  {
   /*
    * Rotate log file...
    */

    cupsFileClose(*lf);

    strlcpy(backname, filename, sizeof(backname));
    strlcat(backname, ".O", sizeof(backname));

    unlink(backname);
    rename(filename, backname);

    if ((*lf = cupsFileOpen(filename, "a")) == NULL)
    {
#ifdef HAVE_ASL_H
	asl_object_t	m;		/* Log message */

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, ASL_KEY_FACILITY, "org.cups.cupsd");
	asl_log(NULL, m, ASL_LEVEL_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
	asl_release(m);

#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
        sd_journal_print(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));

#else
	syslog(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
#endif /* HAVE_ASL_H */

      if (FatalErrors & CUPSD_FATAL_LOG)
	cupsdEndProcess(getpid(), 0);

      return (0);
    }

   /*
    * Change ownership and permissions of non-device logs...
    */

    fchown(cupsFileNumber(*lf), RunUser, Group);
    fchmod(cupsFileNumber(*lf), LogFilePerm);
  }

  return (1);
}
Example #26
0
int
od_record_create(pam_handle_t *pamh, ODRecordRef *record, CFStringRef cfUser)
{
	int retval = PAM_SERVICE_ERR;
	const int attr_num = 5;

	ODNodeRef cfNode = NULL;
	CFErrorRef cferror = NULL;
	CFArrayRef attrs = NULL;
	CFTypeRef cfVals[attr_num];

	if (NULL == record || NULL == cfUser) {
		openpam_log(PAM_LOG_DEBUG, "NULL argument passed");
		retval = PAM_SERVICE_ERR;
		goto cleanup;
	}

#ifdef OPENDIRECTORY_CACHE
#define CFRECORDNAME_CACHE "CFRecordName"
#define CFRECORDNAME_NAME CFSTR("name")
#define CFRECORDNAME_RECORD CFSTR("record")

	CFDictionaryRef cfdict;
	CFStringRef cachedUser;

	if (pam_get_data(pamh, CFRECORDNAME_CACHE, (void *)&cfdict) == PAM_SUCCESS &&
	    (CFGetTypeID(cfdict) == CFDictionaryGetTypeID()) &&
	    (cachedUser = CFDictionaryGetValue(cfdict, CFRECORDNAME_NAME)) != NULL &&
	    CFGetTypeID(cachedUser) == CFStringGetTypeID() &&
	    CFStringCompare(cfUser, cachedUser, 0) == kCFCompareEqualTo &&
	    (*record = (ODRecordRef)CFDictionaryGetValue(cfdict, CFRECORDNAME_RECORD)) != NULL)
	{
		CFRetain(*record);
		return PAM_SUCCESS;
	}
#endif /* OPENDIRECTORY_CACHE */

	int current_iterations = 0;

	cfNode = ODNodeCreateWithNodeType(kCFAllocatorDefault,
					  kODSessionDefault,
					  eDSAuthenticationSearchNodeName,
					  &cferror);
	if (NULL == cfNode || NULL != cferror) {
		openpam_log(PAM_LOG_ERROR, "ODNodeCreateWithNodeType failed.");
		retval = PAM_SERVICE_ERR;
		goto cleanup;
	}

	cfVals[0] = kODAttributeTypeAuthenticationAuthority;
	cfVals[1] = kODAttributeTypeHomeDirectory;
	cfVals[2] = kODAttributeTypeNFSHomeDirectory;
	cfVals[3] = kODAttributeTypeUserShell;
	cfVals[4] = kODAttributeTypeUniqueID;
	attrs = CFArrayCreate(kCFAllocatorDefault, cfVals, (CFIndex)attr_num, &kCFTypeArrayCallBacks);
	if (NULL == attrs) {
		openpam_log(PAM_LOG_DEBUG, "CFArrayCreate() failed");
		retval = PAM_BUF_ERR;
		goto cleanup;
	}

	retval = PAM_SERVICE_ERR;
	while (current_iterations <= kMaxIterationCount) {
		CFIndex unreachable_count = 0;
		CFArrayRef unreachable_nodes = ODNodeCopyUnreachableSubnodeNames(cfNode, NULL);
		if (unreachable_nodes) {
			unreachable_count = CFArrayGetCount(unreachable_nodes);
			CFRelease(unreachable_nodes);
			openpam_log(PAM_LOG_DEBUG, "%lu OD nodes unreachable.", unreachable_count);
		}

		*record = ODNodeCopyRecord(cfNode, kODRecordTypeUsers, cfUser, attrs, &cferror);
		if (*record)
			break;
		if (0 == unreachable_count)
			break;

		openpam_log(PAM_LOG_DEBUG, "Waiting %d seconds for nodes to become reachable", kWaitSeconds);
		sleep(kWaitSeconds);
		++current_iterations;
	}

	if (*record) {
#ifdef OPENDIRECTORY_CACHE
		const void *keys[] = { CFRECORDNAME_NAME, CFRECORDNAME_RECORD };
		const void *values[] = { cfUser, *record };
		CFDictionaryRef dict;
		
		dict = CFDictionaryCreate(NULL, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
		if (dict)
			pam_set_data(pamh, CFRECORDNAME_CACHE, (void *)dict, cleanup_cache);
#endif /* OPENDIRECTORY_CACHE */
		retval = PAM_SUCCESS;
	} else {
		retval = PAM_USER_UNKNOWN;
	}

	if (current_iterations > 0) {
		char *wt = NULL, *found = NULL;
		int retval2;

		if (*record)
			found = "failure";
		else
			found = "success";

		retval2 = asprintf(&wt, "%d", kWaitSeconds * current_iterations);
		if (-1 == retval2) {
			openpam_log(PAM_LOG_DEBUG, "Failed to convert current wait time to string.");
			retval = PAM_BUF_ERR;
			goto cleanup;
		}


		aslmsg m = asl_new(ASL_TYPE_MSG);
		asl_set(m, "com.apple.message.domain", "com.apple.pam_modules.odAvailableWaitTime" );
		asl_set(m, "com.apple.message.signature", "wait_time");
		asl_set(m, "com.apple.message.value", wt);
		asl_set(m, "com.apple.message.result", found);
		asl_log(NULL, m, ASL_LEVEL_NOTICE, "OD nodes online delay: %ss. User record lookup: %s.", wt, found);
		asl_free(m);
		free(wt);
	}

cleanup:
	if (NULL != attrs) {
		CFRelease(attrs);
	}

	if (NULL != cferror) {
		CFRelease(cferror);
	}

	if (NULL != cfNode) {
		CFRelease(cfNode);
	}

	if (PAM_SUCCESS != retval) {
		openpam_log(PAM_LOG_ERROR, "failed: %d", retval);
		if (NULL != *record) {
			CFRelease(*record);
			*record = NULL;
		}
	}

	return retval;
}
Example #27
0
void RARCH_LOG_V(const char *tag, const char *fmt, va_list ap)
{
#if TARGET_OS_IPHONE
   static int asl_initialized = 0;
#if !TARGET_IPHONE_SIMULATOR
static aslclient asl_client;
#endif
#else
   FILE *fp = NULL;
   (void)fp;
#endif

   if (!verbosity_is_enabled())
      return;
#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR
   vprintf(fmt, ap);
#else
   if (!asl_initialized)
   {
      asl_client = asl_open(file_path_str(FILE_PATH_PROGRAM_NAME), "com.apple.console", ASL_OPT_STDERR | ASL_OPT_NO_DELAY);
      asl_initialized = 1;
   }
   aslmsg msg = asl_new(ASL_TYPE_MSG);
   asl_set(msg, ASL_KEY_READ_UID, "-1");
   if (tag)
      asl_log(asl_client, msg, ASL_LEVEL_NOTICE, "%s", tag);
   asl_vlog(asl_client, msg, ASL_LEVEL_NOTICE, fmt, ap);
   asl_free(msg);
#endif
#elif defined(_XBOX1)
   /* FIXME: Using arbitrary string as fmt argument is unsafe. */
   char msg_new[1024];
   char buffer[1024];

   msg_new[0] = buffer[0] = '\0';
   snprintf(msg_new, sizeof(msg_new), "%s: %s %s",
         file_path_str(FILE_PATH_PROGRAM_NAME),
         tag ? tag : "",
         fmt);
   wvsprintf(buffer, msg_new, ap);
   OutputDebugStringA(buffer);
#elif defined(ANDROID)
   int prio = ANDROID_LOG_INFO;
   if (tag)
   {
      if (string_is_equal(file_path_str(FILE_PATH_LOG_WARN), tag))
         prio = ANDROID_LOG_WARN;
      else if (string_is_equal(file_path_str(FILE_PATH_LOG_ERROR), tag))
         prio = ANDROID_LOG_ERROR;
   }
   __android_log_vprint(prio,
         file_path_str(FILE_PATH_PROGRAM_NAME),
         fmt,
         ap);
#else

#ifdef HAVE_FILE_LOGGER
   fp = (FILE*)retro_main_log_file();
#else
   fp = stderr;
#endif
   fprintf(fp, "%s %s :: ",
         file_path_str(FILE_PATH_PROGRAM_NAME),
         tag ? tag : file_path_str(FILE_PATH_LOG_INFO));
   vfprintf(fp, fmt, ap);
   fflush(fp);
#endif
}