コード例 #1
0
END_TEST


START_TEST (test_StringBuffer_appendInt)
{
  char *s, *t;


  StringBuffer_appendInt(SB, 1);

  fail_unless( StringBuffer_length(SB)   ==  1 );
  fail_unless( StringBuffer_capacity(SB) == 80 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "1") );

  StringBuffer_appendChar(SB, ' ');
  StringBuffer_appendInt(SB, 23);

  fail_unless( StringBuffer_length(SB)   ==  4 );
  fail_unless( StringBuffer_capacity(SB) == 80 );

  t = StringBuffer_toString(SB);

  fail_unless( !strcmp(t, "1 23") );

  safe_free(s);
  safe_free(t);
}
コード例 #2
0
ファイル: TestStringBuffer.c プロジェクト: sn248/Rcppsbml
END_TEST


START_TEST (test_StringBuffer_append)
{
  char *s, *t;


  StringBuffer_append(SB, "foo");

  fail_unless( StringBuffer_length(SB)   ==  3 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "foo") );

  StringBuffer_append(SB, "bar");

  fail_unless( StringBuffer_length(SB)   ==  6 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  t = StringBuffer_toString(SB);
  fail_unless( !strcmp(t, "foobar") );

  safe_free(s);
  safe_free(t);
}
コード例 #3
0
ファイル: TestStringBuffer.c プロジェクト: sn248/Rcppsbml
END_TEST


START_TEST (test_StringBuffer_reset)
{
  StringBuffer_append(SB, "foo");

  fail_unless( StringBuffer_length(SB)   ==  3 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  StringBuffer_reset(SB);

  fail_unless( StringBuffer_length(SB)   ==  0 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  StringBuffer_append(SB, "foobarfoobar");

  fail_unless( StringBuffer_length(SB)   == 12 );
  fail_unless( StringBuffer_capacity(SB) == 20 );

  StringBuffer_reset(SB);

  fail_unless( StringBuffer_length(SB)   ==  0 );
  fail_unless( StringBuffer_capacity(SB) == 20 );
}
コード例 #4
0
END_TEST


START_TEST (test_StringBuffer_appendReal_locale)
{
  char *s, *t;


  setlocale(LC_NUMERIC, "de_DE");

  StringBuffer_appendReal(SB, 1.2);

  fail_unless( StringBuffer_length(SB)   ==  3 );
  fail_unless( StringBuffer_capacity(SB) == 80 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "1.2") );

  StringBuffer_appendChar(SB, ' ');
  StringBuffer_appendReal(SB, 3);

  fail_unless( StringBuffer_length(SB)   ==  5 );
  fail_unless( StringBuffer_capacity(SB) == 80 );

  t = StringBuffer_toString(SB);
  fail_unless( !strcmp(t, "1.2 3") );

  setlocale(LC_NUMERIC, "C");

  safe_free(s);
  safe_free(t);
}
コード例 #5
0
ファイル: TestStringBuffer.c プロジェクト: sn248/Rcppsbml
END_TEST


START_TEST (test_StringBuffer_appendChar_grow)
{
  char *s, *t;


  StringBuffer_append(SB, "fooooooooo");

  fail_unless( StringBuffer_length(SB)   == 10 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "fooooooooo") );

  StringBuffer_appendChar(SB, '!');

  fail_unless( StringBuffer_length(SB)   == 11 );
  fail_unless( StringBuffer_capacity(SB) == 20 );

  t = StringBuffer_toString(SB);
  fail_unless( !strcmp(t, "fooooooooo!") );

  safe_free(s);
  safe_free(t);
}
コード例 #6
0
static int _doConnect(T C, URL_T url, char**  error) {
#undef ERROR
#define ERROR(e) do {*error = Str_dup(e); return false;} while (0)
#define ORAERROR(e) do{ *error = Str_dup(OracleConnection_getLastError(e)); return false;} while(0)
        const char *database, *username, *password;
        const char *host = URL_getHost(url);
        int port = URL_getPort(url);
        if (! (username = URL_getUser(url)))
                if (! (username = URL_getParameter(url, "user")))
                        ERROR("no username specified in URL");
        if (! (password = URL_getPassword(url)))
                if (! (password = URL_getParameter(url, "password")))
                        ERROR("no password specified in URL");
        if (! (database = URL_getPath(url)))
                ERROR("no database specified in URL");
        ++database;
        /* Create a thread-safe OCI environment with N' substitution turned on. */
        if (OCIEnvCreate(&C->env, OCI_THREADED | OCI_OBJECT | OCI_NCHAR_LITERAL_REPLACE_ON, 0, 0, 0, 0, 0, 0))
                ERROR("Create a OCI environment failed");
        /* allocate an error handle */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->err, OCI_HTYPE_ERROR, 0, 0))
                ERROR("Allocating error handler failed");
        /* server contexts */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->srv, OCI_HTYPE_SERVER, 0, 0))
                ERROR("Allocating server context failed");
        /* allocate a service handle */
        if (OCI_SUCCESS != OCIHandleAlloc(C->env, (dvoid**)&C->svc, OCI_HTYPE_SVCCTX, 0, 0))
                ERROR("Allocating service handle failed");
        StringBuffer_clear(C->sb);
        /* Oracle connect string is on the form: //host[:port]/service name */
        if (host) {
                StringBuffer_append(C->sb, "//%s", host);
                if (port > 0)
                        StringBuffer_append(C->sb, ":%d", port);
                StringBuffer_append(C->sb, "/%s", database);
        } else /* Or just service name */
                StringBuffer_append(C->sb, "%s", database);
        /* Create a server context */
        C->lastError = OCIServerAttach(C->srv, C->err, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), 0);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        /* Set attribute server context in the service context */
        C->lastError = OCIAttrSet(C->svc, OCI_HTYPE_SVCCTX, C->srv, 0, OCI_ATTR_SERVER, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIHandleAlloc(C->env, (void**)&C->usr, OCI_HTYPE_SESSION, 0, NULL);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIAttrSet(C->usr, OCI_HTYPE_SESSION, (dvoid *)username, (int)strlen(username), OCI_ATTR_USERNAME, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCIAttrSet(C->usr, OCI_HTYPE_SESSION, (dvoid *)password, (int)strlen(password), OCI_ATTR_PASSWORD, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        C->lastError = OCISessionBegin(C->svc, C->err, C->usr, OCI_CRED_RDBMS, OCI_DEFAULT);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                ORAERROR(C);
        OCIAttrSet(C->svc, OCI_HTYPE_SVCCTX, C->usr, 0, OCI_ATTR_SESSION, C->err);
        return true;
}
コード例 #7
0
ファイル: OracleConnection.c プロジェクト: EchoLiao/libzdb
ResultSet_T OracleConnection_executeQuery(T C, const char *sql, va_list ap) {
        OCIStmt* stmtp;
        va_list  ap_copy;
        assert(C);
        C->rowsChanged = 0;
        va_copy(ap_copy, ap);
        StringBuffer_vset(C->sb, sql, ap_copy);
        va_end(ap_copy);
        StringBuffer_trim(C->sb);
        /* Build statement */
        C->lastError = OCIHandleAlloc(C->env, (void **)&stmtp, OCI_HTYPE_STMT, 0, NULL);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                return NULL;
        C->lastError = OCIStmtPrepare(stmtp, C->err, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), OCI_NTV_SYNTAX, OCI_DEFAULT);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO) {
                OCIHandleFree(stmtp, OCI_HTYPE_STMT);
                return NULL;
        }
        /* Execute and create Result Set */
        C->lastError = OCIStmtExecute(C->svc, stmtp, C->err, 0, 0, NULL, NULL, OCI_DEFAULT);    
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO) {
                ub4 parmcnt = 0;
                OCIAttrGet(stmtp, OCI_HTYPE_STMT, &parmcnt, NULL, OCI_ATTR_PARSE_ERROR_OFFSET, C->err);
                DEBUG("Error occured in StmtExecute %d (%s), offset is %d\n", C->lastError, OracleConnection_getLastError(C), parmcnt);
                OCIHandleFree(stmtp, OCI_HTYPE_STMT);
                return NULL;
        }
        C->lastError = OCIAttrGet(stmtp, OCI_HTYPE_STMT, &C->rowsChanged, 0, OCI_ATTR_ROW_COUNT, C->err);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                DEBUG("OracleConnection_execute: Error in OCIAttrGet %d (%s)\n", C->lastError, OracleConnection_getLastError(C));
        return ResultSet_new(OracleResultSet_new(stmtp, C->env, C->usr, C->err, C->svc, true, C->maxRows), (Rop_T)&oraclerops);
}
コード例 #8
0
ResultSet_T SqlServerConnection_executeQuery(T C, const char *sql, va_list ap) {
	va_list ap_copy;
	const char *tail;
	SQLHSTMT hstmt;

	assert(C);
	StringBuffer_clear(C->sb);
	va_copy(ap_copy, ap);
	StringBuffer_vappend(C->sb, sql, ap_copy);
	va_end(ap_copy);

	C->lastError = SQLAllocStmt(C->db->hdbc,&hstmt);


	C->lastError = SQLPrepare(hstmt,
		StringBuffer_toString(C->sb), StringBuffer_length(C->sb)); 
	if(!SQLSERVERSUCCESS(C->lastError)) {
		getSqlErr(C,hstmt);
		return NULL;
	}
	C->lastError = SQLExecute(hstmt);
	if(SQLSERVERSUCCESS(C->lastError))
		return ResultSet_new(SqlServerResultSet_new(hstmt, C->maxRows, false), (Rop_T)&sqlserverrops);
	else {
		getSqlErr(C,hstmt);
	}
	return NULL;
}
コード例 #9
0
END_TEST


START_TEST (test_StringBuffer_toString)
{
  char *s;


  StringBuffer_append(SB, "foo");

  fail_unless( StringBuffer_length(SB)   ==  3 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "foo") );

  s[0] = 'b';

  if ( !strcmp(SB->buffer, "boo") )
  {
    fail("StringBuffer_toString() did not make a copy of its internal buffer.");
  }

  safe_free(s);
}
コード例 #10
0
END_TEST

START_TEST (test_StringBuffer_accessWithNULL)
{
  StringBuffer_append(NULL, NULL);
  StringBuffer_appendChar(NULL, ' ');
  StringBuffer_appendExp(NULL, 0.0);
  StringBuffer_appendInt(NULL, 0);
  StringBuffer_appendNumber(NULL, NULL);
  StringBuffer_appendReal(NULL, 0.0);
  
  fail_unless (StringBuffer_capacity(NULL) == 0);

  StringBuffer_ensureCapacity(NULL, 0);
  StringBuffer_free(NULL);

  fail_unless (StringBuffer_getBuffer(NULL) == NULL);

  StringBuffer_grow(NULL, 0);

  fail_unless (StringBuffer_length(NULL) == 0);

  StringBuffer_reset(NULL);

  fail_unless (StringBuffer_toString(NULL) == NULL);
}
コード例 #11
0
/**
 * Send the response to the client. If the response has already been
 * commited, this function does nothing.
 */
static void send_response(HttpResponse res) {
  Socket_T S= res->S;

  if(!res->is_committed) {
    char date[STRLEN];
    char server[STRLEN];
    char *headers= get_headers(res);
    int length = StringBuffer_length(res->outputbuffer);

    res->is_committed= TRUE;
    get_date(date, STRLEN);
    get_server(server, STRLEN);
    socket_print(S, "%s %d %s\r\n", res->protocol, res->status,
		 res->status_msg);
    socket_print(S, "Date: %s\r\n", date);
    socket_print(S, "Server: %s\r\n", server);
    socket_print(S, "Content-Length: %d\r\n", length);
    socket_print(S, "Connection: close\r\n");
    if(headers)
	socket_print(S, "%s", headers);
    socket_print(S, "\r\n");
    if(length)
	socket_write(S, (unsigned char *)StringBuffer_toString(res->outputbuffer), length);
    FREE(headers);
  }
}
コード例 #12
0
ファイル: MysqlConnection.c プロジェクト: HunterChen/libzdb
int MysqlConnection_execute(T C, const char *sql, va_list ap) {
        va_list ap_copy;
	assert(C);
        StringBuffer_clear(C->sb);
        va_copy(ap_copy, ap);
        StringBuffer_vappend(C->sb, sql, ap_copy);
        va_end(ap_copy);
        C->lastError = mysql_real_query(C->db, StringBuffer_toString(C->sb), StringBuffer_length(C->sb));
	return (C->lastError == MYSQL_OK);
}
コード例 #13
0
/**
 * Read all processes to initialize the information tree.
 * @param reference  reference of ProcessTree
 * @param pflags Process engine flags
 * @return treesize > 0 if succeeded otherwise 0.
 */
int initprocesstree_sysdep(ProcessTree_T **reference, ProcessEngine_Flags pflags) {
        kvm_t *kvm_handle = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, prog);
        if (! kvm_handle) {
                LogError("system statistic error -- cannot initialize kvm interface\n");
                return 0;
        }

        int treesize;
        struct kinfo_proc *pinfo = kvm_getprocs(kvm_handle, KERN_PROC_ALL, 0, &treesize);
        if (! pinfo || (treesize < 1)) {
                LogError("system statistic error -- cannot get process tree\n");
                kvm_close(kvm_handle);
                return 0;
        }

        ProcessTree_T *pt = CALLOC(sizeof(ProcessTree_T), treesize);

        StringBuffer_T cmdline = NULL;
        if (pflags & ProcessEngine_CollectCommandLine)
                cmdline = StringBuffer_create(64);
        for (int i = 0; i < treesize; i++) {
                pt[i].pid          = pinfo[i].kp_pid;
                pt[i].ppid         = pinfo[i].kp_ppid;
                pt[i].cred.uid     = pinfo[i].kp_ruid;
                pt[i].cred.euid    = pinfo[i].kp_uid;
                pt[i].cred.gid     = pinfo[i].kp_rgid;
                pt[i].threads      = pinfo[i].kp_nthreads;
                pt[i].uptime       = systeminfo.time / 10. - pinfo[i].kp_start.tv_sec;
                pt[i].cpu.time     = (double)((pinfo[i].kp_lwp.kl_uticks + pinfo[i].kp_lwp.kl_sticks + pinfo[i].kp_lwp.kl_iticks) / 1000000.);
                pt[i].memory.usage = (uint64_t)pinfo[i].kp_vm_rssize * (uint64_t)pagesize;
                pt[i].zombie       = pinfo[i].kp_stat == SZOMB ? true : false;
                if (pflags & ProcessEngine_CollectCommandLine) {
                        char **args = kvm_getargv(kvm_handle, &pinfo[i], 0);
                        if (args) {
                                StringBuffer_clear(cmdline);
                                for (int j = 0; args[j]; j++)
                                        StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
                                if (StringBuffer_length(cmdline))
                                        pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
                        }
                        if (! pt[i].cmdline || ! *pt[i].cmdline) {
                                FREE(pt[i].cmdline);
                                pt[i].cmdline = Str_dup(pinfo[i].kp_comm);
                        }
                }
        }
        if (pflags & ProcessEngine_CollectCommandLine)
                StringBuffer_free(&cmdline);

        *reference = pt;
        kvm_close(kvm_handle);

        return treesize;
}
コード例 #14
0
ファイル: MysqlConnection.c プロジェクト: HunterChen/libzdb
PreparedStatement_T MysqlConnection_prepareStatement(T C, const char *sql, va_list ap) {
        va_list ap_copy;
        MYSQL_STMT *stmt = NULL;
        assert(C);
        StringBuffer_clear(C->sb);
        va_copy(ap_copy, ap);
        StringBuffer_vappend(C->sb, sql, ap_copy);
        va_end(ap_copy);
        if (prepare(C, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), &stmt))
		return PreparedStatement_new(MysqlPreparedStatement_new(stmt, C->maxRows), (Pop_T)&mysqlpops);
        return NULL;
}
コード例 #15
0
END_TEST


START_TEST (test_StringBuffer_grow)
{
  char *s;


  StringBuffer_append(SB, "foobar");

  fail_unless( StringBuffer_length(SB)   ==  6 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  StringBuffer_grow(SB, 10);

  fail_unless( StringBuffer_length(SB)   ==  6 );
  fail_unless( StringBuffer_capacity(SB) == 20 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "foobar") );

  safe_free(s);
}
コード例 #16
0
END_TEST


START_TEST (test_StringBuffer_appendChar)
{
  char *s, *t, *u;


  StringBuffer_appendChar(SB, '*');

  fail_unless( StringBuffer_length(SB)   ==  1 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  s = StringBuffer_toString(SB);
  fail_unless( !strcmp(s, "*") );

  StringBuffer_append(SB, "foo");

  fail_unless( StringBuffer_length(SB)   ==  4 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  t = StringBuffer_toString(SB);
  fail_unless( !strcmp(t, "*foo") );

  StringBuffer_appendChar(SB, '*');

  fail_unless( StringBuffer_length(SB)   ==  5 );
  fail_unless( StringBuffer_capacity(SB) == 10 );

  u = StringBuffer_toString(SB);
  fail_unless( !strcmp(u, "*foo*") );

  safe_free(s);
  safe_free(t);
  safe_free(u);
}
コード例 #17
0
ファイル: http.c プロジェクト: Happy-Ferret/Monit
int check_http(Socket_T socket) {
        Port_T P;
        char host[STRLEN];
        char auth[STRLEN] = {};
        const char *request = NULL;
        const char *hostheader = NULL;

        ASSERT(socket);

        P = socket_get_Port(socket);

        ASSERT(P);

        request = P->request ? P->request : "/";

        hostheader = _findHostHeaderIn(P->http_headers);
        hostheader = hostheader ? hostheader : P->request_hostheader
                                ? P->request_hostheader : Util_getHTTPHostHeader(socket, host, STRLEN); // Otherwise use deprecated request_hostheader or default host
        StringBuffer_T sb = StringBuffer_create(168);
        StringBuffer_append(sb,
                            "GET %s HTTP/1.1\r\n"
                            "Host: %s\r\n"
                            "Accept: */*\r\n"
                            "User-Agent: Monit/%s\r\n"
                            "%s",
                            request, hostheader, VERSION,
                            get_auth_header(P, auth, STRLEN));
        // Add headers if we have them
        if (P->http_headers) {
                for (list_t p = P->http_headers->head; p; p = p->next) {
                        if (Str_startsWith(p->e, "Host")) // Already set contrived above
                                continue;
                        StringBuffer_append(sb, "%s\r\n", p->e);
                }
        }
        StringBuffer_append(sb, "\r\n");
        int send_status = socket_write(socket, (void*)StringBuffer_toString(sb), StringBuffer_length(sb));
        StringBuffer_free(&sb);
        if (send_status < 0) {
                socket_setError(socket, "HTTP: error sending data -- %s", STRERROR);
                return FALSE;
        }

        return check_request(socket, P);
}
コード例 #18
0
ファイル: OracleConnection.c プロジェクト: EchoLiao/libzdb
PreparedStatement_T OracleConnection_prepareStatement(T C, const char *sql, va_list ap) {
        OCIStmt *stmtp;
        va_list ap_copy;
        assert(C);
        va_copy(ap_copy, ap);
        StringBuffer_vset(C->sb, sql, ap_copy);
        va_end(ap_copy);
        StringBuffer_trim(C->sb);
        int paramCount = StringBuffer_prepare4oracle(C->sb);
        /* Build statement */
        C->lastError = OCIHandleAlloc(C->env, (void **)&stmtp, OCI_HTYPE_STMT, 0, 0);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO)
                return NULL;
        C->lastError = OCIStmtPrepare(stmtp, C->err, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), OCI_NTV_SYNTAX, OCI_DEFAULT);
        if (C->lastError != OCI_SUCCESS && C->lastError != OCI_SUCCESS_WITH_INFO) {
                OCIHandleFree(stmtp, OCI_HTYPE_STMT);
                return NULL;
        }
        return PreparedStatement_new(OraclePreparedStatement_new(stmtp, C->env, C->usr, C->err, C->svc, C->maxRows), (Pop_T)&oraclepops, paramCount);
}
コード例 #19
0
ファイル: MysqlConnection.c プロジェクト: HunterChen/libzdb
ResultSet_T MysqlConnection_executeQuery(T C, const char *sql, va_list ap) {
        va_list ap_copy;
        MYSQL_STMT *stmt = NULL;
	assert(C);
        StringBuffer_clear(C->sb);
        va_copy(ap_copy, ap);
        StringBuffer_vappend(C->sb, sql, ap_copy);
        va_end(ap_copy);
        if (prepare(C, StringBuffer_toString(C->sb), StringBuffer_length(C->sb), &stmt)) {
#if MYSQL_VERSION_ID >= 50002
                unsigned long cursor = CURSOR_TYPE_READ_ONLY;
                mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, &cursor);
#endif
                if ((C->lastError = mysql_stmt_execute(stmt))) {
                        StringBuffer_clear(C->sb);
                        StringBuffer_append(C->sb, "%s", mysql_stmt_error(stmt));
                        mysql_stmt_close(stmt);
                }
                else
                        return ResultSet_new(MysqlResultSet_new(stmt, C->maxRows, false), (Rop_T)&mysqlrops);
        }
        return NULL;
}
コード例 #20
0
/**
 * Read all processes to initialize the information tree.
 * @param reference reference of ProcessTree
 * @param pflags Process engine flags
 * @return treesize > 0 if succeeded otherwise 0
 */
int initprocesstree_sysdep(ProcessTree_T **reference, ProcessEngine_Flags pflags) {
        size_t size = sizeof(maxslp);
        static int mib_maxslp[] = {CTL_VM, VM_MAXSLP};
        if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) {
                LogError("system statistic error -- vm.maxslp failed\n");
                return 0;
        }

        int mib_proc2[6] = {CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), 0};
        if (sysctl(mib_proc2, 6, NULL, &size, NULL, 0) == -1) {
                LogError("system statistic error -- kern.proc2 #1 failed\n");
                return 0;
        }

        size *= 2; // Add reserve for new processes which were created between calls of sysctl
        struct kinfo_proc2 *pinfo = CALLOC(1, size);
        mib_proc2[5] = (int)(size / sizeof(struct kinfo_proc2));
        if (sysctl(mib_proc2, 6, pinfo, &size, NULL, 0) == -1) {
                FREE(pinfo);
                LogError("system statistic error -- kern.proc2 #2 failed\n");
                return 0;
        }

        int treesize = (int)(size / sizeof(struct kinfo_proc2));

        ProcessTree_T *pt = CALLOC(sizeof(ProcessTree_T), treesize);

        char buf[_POSIX2_LINE_MAX];
        kvm_t *kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
        if (! kvm_handle) {
                FREE(pinfo);
                FREE(pt);
                LogError("system statistic error -- kvm_openfiles failed: %s\n", buf);
                return 0;
        }

        StringBuffer_T cmdline = NULL;
        if (pflags & ProcessEngine_CollectCommandLine)
                cmdline = StringBuffer_create(64);
        for (int i = 0; i < treesize; i++) {
                pt[i].pid          = pinfo[i].p_pid;
                pt[i].ppid         = pinfo[i].p_ppid;
                pt[i].cred.uid     = pinfo[i].p_ruid;
                pt[i].cred.euid    = pinfo[i].p_uid;
                pt[i].cred.gid     = pinfo[i].p_rgid;
                pt[i].threads      = pinfo[i].p_nlwps;
                pt[i].uptime       = systeminfo.time / 10. - pinfo[i].p_ustart_sec;
                pt[i].cpu.time     = pinfo[i].p_rtime_sec * 10 + (double)pinfo[i].p_rtime_usec / 100000.;
                pt[i].memory.usage = (uint64_t)pinfo[i].p_vm_rssize * (uint64_t)pagesize;
                pt[i].zombie       = pinfo[i].p_stat == SZOMB ? true : false;
                if (pflags & ProcessEngine_CollectCommandLine) {
                        char **args = kvm_getargv2(kvm_handle, &pinfo[i], 0);
                        if (args) {
                                StringBuffer_clear(cmdline);
                                for (int j = 0; args[j]; j++)
                                        StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
                                if (StringBuffer_length(cmdline))
                                        pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
                        }
                        if (! pt[i].cmdline || ! *pt[i].cmdline) {
                                FREE(pt[i].cmdline);
                                pt[i].cmdline = Str_dup(pinfo[i].p_comm);
                        }
                }
        }
        if (pflags & ProcessEngine_CollectCommandLine)
                StringBuffer_free(&cmdline);
        FREE(pinfo);
        kvm_close(kvm_handle);

        *reference = pt;

        return treesize;
}
コード例 #21
0
/**
 * Read all processes to initialize the information tree.
 * @param reference reference of ProcessTree
 * @param pflags Process engine flags
 * @return treesize > 0 if succeeded otherwise 0
 */
int initprocesstree_sysdep(ProcessTree_T **reference, ProcessEngine_Flags pflags) {
        size_t pinfo_size = 0;
        int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
        if (sysctl(mib, 4, NULL, &pinfo_size, NULL, 0) < 0) {
                LogError("system statistic error -- sysctl failed: %s\n", STRERROR);
                return 0;
        }
        struct kinfo_proc *pinfo = CALLOC(1, pinfo_size);
        if (sysctl(mib, 4, pinfo, &pinfo_size, NULL, 0)) {
                FREE(pinfo);
                LogError("system statistic error -- sysctl failed: %s\n", STRERROR);
                return 0;
        }
        size_t treesize = pinfo_size / sizeof(struct kinfo_proc);
        ProcessTree_T *pt = CALLOC(sizeof(ProcessTree_T), treesize);

        char *args = NULL;
        StringBuffer_T cmdline = NULL;
        if (pflags & ProcessEngine_CollectCommandLine) {
                cmdline = StringBuffer_create(64);
                args = CALLOC(1, systeminfo.argmax + 1);
        }
        for (int i = 0; i < treesize; i++) {
                pt[i].uptime    = systeminfo.time / 10. - pinfo[i].kp_proc.p_starttime.tv_sec;
                pt[i].zombie    = pinfo[i].kp_proc.p_stat == SZOMB ? true : false;
                pt[i].pid       = pinfo[i].kp_proc.p_pid;
                pt[i].ppid      = pinfo[i].kp_eproc.e_ppid;
                pt[i].cred.uid  = pinfo[i].kp_eproc.e_pcred.p_ruid;
                pt[i].cred.euid = pinfo[i].kp_eproc.e_ucred.cr_uid;
                pt[i].cred.gid  = pinfo[i].kp_eproc.e_pcred.p_rgid;
                if (pflags & ProcessEngine_CollectCommandLine) {
                        size_t size = systeminfo.argmax;
                        mib[0] = CTL_KERN;
                        mib[1] = KERN_PROCARGS2;
                        mib[2] = pt[i].pid;
                        if (sysctl(mib, 3, args, &size, NULL, 0) != -1) {
                                /* KERN_PROCARGS2 sysctl() returns following pseudo structure:
                                 *        struct {
                                 *                int argc
                                 *                char execname[];
                                 *                char argv[argc][];
                                 *                char env[][];
                                 *        }
                                 * The strings are terminated with '\0' and may have variable '\0' padding
                                 */
                                int argc = *args;
                                char *p = args + sizeof(int); // arguments beginning
                                StringBuffer_clear(cmdline);
                                p += strlen(p); // skip exename
                                while (argc && p < args + systeminfo.argmax) {
                                        if (*p == 0) { // skip terminating 0 and variable length 0 padding
                                                p++;
                                                continue;
                                        }
                                        StringBuffer_append(cmdline, argc-- ? "%s " : "%s", p);
                                        p += strlen(p);
                                }
                                if (StringBuffer_length(cmdline))
                                        pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
                        }
                        if (! pt[i].cmdline || ! *pt[i].cmdline) {
                                FREE(pt[i].cmdline);
                                pt[i].cmdline = Str_dup(pinfo[i].kp_proc.p_comm);
                        }
                }
                if (! pt[i].zombie) {
                        struct proc_taskinfo tinfo;
                        int rv = proc_pidinfo(pt[i].pid, PROC_PIDTASKINFO, 0, &tinfo, sizeof(tinfo)); // If the process is zombie, skip this
                        if (rv <= 0) {
                                if (errno != EPERM)
                                        DEBUG("proc_pidinfo for pid %d failed -- %s\n", pt[i].pid, STRERROR);
                        } else if (rv < sizeof(tinfo)) {
                                LogError("proc_pidinfo for pid %d -- invalid result size\n", pt[i].pid);
                        } else {
                                pt[i].memory.usage = (uint64_t)tinfo.pti_resident_size;
                                pt[i].cpu.time     = (double)(tinfo.pti_total_user + tinfo.pti_total_system) / 100000000.; // The time is in nanoseconds, we store it as 1/10s
                                pt[i].threads      = tinfo.pti_threadnum;
                        }
                }
        }
        if (pflags & ProcessEngine_CollectCommandLine) {
                StringBuffer_free(&cmdline);
                FREE(args);
        }
        FREE(pinfo);

        *reference = pt;
        
        return (int)treesize;
}
コード例 #22
0
ファイル: StringBufferTest.c プロジェクト: ezotrank/monit-src
int main(void) {
        StringBuffer_T sb;

        Bootstrap(); // Need to initialize library

        printf("============> Start StringBuffer Tests\n\n");

        printf("=> Test1: create/destroy\n");
        {
                sb= StringBuffer_new("");
                assert(sb);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
                sb= StringBuffer_create(1024);
                assert(sb);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test1: OK\n\n");

        printf("=> Test2: Append NULL value\n");
        {
                sb= StringBuffer_new("");
                assert(sb);
                StringBuffer_append(sb, NULL);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test2: OK\n\n");

        printf("=> Test3: Create with string\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                assert(StringBuffer_length(sb)==3);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test3: OK\n\n");

        printf("=> Test4: Append string value\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                printf("\tTesting StringBuffer_append:..");
                StringBuffer_append(sb, "def");
                assert(StringBuffer_length(sb)==6);
                printf("ok\n");
                printf("\tTesting StringBuffer_vappend:..");
                append(sb, "%c%s", 'g', "hi");
                assert(StringBuffer_length(sb)==9);
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdefghi"));
                printf("ok\n");
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test4: OK\n\n");

        printf("=> Test5: trim\n");
        {
                sb= StringBuffer_new("\t 'foo bar' \n ");
                assert(Str_isEqual(StringBuffer_toString(StringBuffer_trim(sb)), "'foo bar'"));
                StringBuffer_clear(sb);
                StringBuffer_append(sb, "'foo bar'");
                StringBuffer_trim(sb);
                assert(Str_isEqual(StringBuffer_toString(sb), "'foo bar'"));
                StringBuffer_clear(sb);
                StringBuffer_append(sb, "\t \r \n  ");
                assert(Str_isEqual(StringBuffer_toString(StringBuffer_trim(sb)), ""));
                StringBuffer_free(&sb);
                sb = StringBuffer_create(10);
                StringBuffer_trim(sb);
                assert(StringBuffer_toString(sb)[0] == 0);
                StringBuffer_free(&sb);
        }
        printf("=> Test5: OK\n\n");

        printf("=> Test6: deleteFrom\n");
        {
                sb= StringBuffer_new("abcdefgh");
                assert(sb);
                StringBuffer_delete(sb,3);
                assert(StringBuffer_length(sb)==3);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test6: OK\n\n");

        printf("=> Test7: indexOf and lastIndexOf\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(StringBuffer_indexOf(sb, "henrik")==4);
                assert(StringBuffer_indexOf(sb, "an")==1);
                assert(StringBuffer_indexOf(sb, "-")==3);
                assert(StringBuffer_lastIndexOf(sb, "an")==17);
                assert(StringBuffer_indexOf(sb, "")==-1);
                assert(StringBuffer_indexOf(sb, 0)==-1);
                assert(StringBuffer_indexOf(sb, "d")==19);
                assert(StringBuffer_indexOf(sb, "j")==0);
                assert(StringBuffer_lastIndexOf(sb, "d")==19);
                assert(StringBuffer_lastIndexOf(sb, "j")==0);
                assert(StringBuffer_lastIndexOf(sb, "x")==-1);
                assert(StringBuffer_indexOf(sb, "jane")==-1);
                assert(StringBuffer_indexOf(sb, "jan-henrik haukeland")==0);
                assert(StringBuffer_indexOf(sb, "haukeland")==11);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test7: OK\n\n");

        printf("=> Test8: length and clear\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(StringBuffer_length(sb)==20);
                StringBuffer_clear(sb);
                assert(StringBuffer_length(sb)==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test8: OK\n\n");

        printf("=> Test9: toString value\n");
        {
                sb= StringBuffer_new("abc");
                assert(sb);
                StringBuffer_append(sb, "def");
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdef"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test9: OK\n\n");

        printf("=> Test10: internal resize\n");
        {
                int i;
                sb= StringBuffer_new("");
                assert(sb);
                for (i= 0; i<1024; i++)
                        StringBuffer_append(sb, "a");
                assert(StringBuffer_length(sb)==1024);
                assert(StringBuffer_toString(sb)[1023]=='a');
                assert(StringBuffer_toString(sb)[1024]==0);
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test10: OK\n\n");

        printf("=> Test11: substring\n");
        {
                sb= StringBuffer_new("jan-henrik haukeland");
                assert(sb);
                assert(Str_isEqual(StringBuffer_substring(sb, StringBuffer_indexOf(sb, "-")),
                                                 "-henrik haukeland"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test11: OK\n\n");

        printf("=> Test12: replace\n");
        {
                printf("\tNothing to replace\n");
                sb= StringBuffer_new("abc?def?");
                assert(sb);
                StringBuffer_replace(sb, "x", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc?def?"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and expand\n");
                sb= StringBuffer_new("abc?def?");
                assert(sb);
                StringBuffer_replace(sb, "?", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc$xdef$x"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and shrink\n");
                sb= StringBuffer_new("abc$xdef$x");
                assert(sb);
                StringBuffer_replace(sb, "$x", "?");
                assert(Str_isEqual(StringBuffer_toString(sb), "abc?def?"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace with empty string\n");
                sb= StringBuffer_new("abc$xdef$x");
                assert(sb);
                StringBuffer_replace(sb, "$x", "");
                assert(Str_isEqual(StringBuffer_toString(sb), "abcdef"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace with same length\n");
                sb= StringBuffer_new("foo bar baz foo bar baz");
                assert(sb);
                StringBuffer_replace(sb, "baz", "bar");
                assert(Str_isEqual(StringBuffer_toString(sb), "foo bar bar foo bar bar"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tRemove words and test traceback\n");
                sb= StringBuffer_new("foo bar baz foo foo bar baz");
                assert(sb);
                StringBuffer_replace(sb, "baz", "bar");
                assert(Str_isEqual(StringBuffer_toString(sb), "foo bar bar foo foo bar bar"));
                StringBuffer_replace(sb, "foo bar ", "");
                assert(Str_isEqual(StringBuffer_toString(sb), "bar foo bar"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace all elements\n");
                sb= StringBuffer_new("aaaaaaaaaaaaaaaaaaaaaaaa");
                assert(sb);
                StringBuffer_replace(sb, "a", "b");
                assert(Str_isEqual(StringBuffer_toString(sb), "bbbbbbbbbbbbbbbbbbbbbbbb"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
                printf("\tReplace and expand with resize of StringBuffer\n");
                sb= StringBuffer_new("insert into(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) values (1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,01,2,3);");
                assert(sb);
                StringBuffer_replace(sb, "?", "$x");
                assert(Str_isEqual(StringBuffer_toString(sb), "insert into($x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x, $x) values (1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,01,2,3);"));
                StringBuffer_free(&sb);
                assert(sb==NULL);
        }
        printf("=> Test12: OK\n\n");

        printf("============> StringBuffer Tests: OK\n\n");

        return 0;
}