int command_nick(Client *client, StringBuffer *command) { StringBuffer *msg = StringBuffer_construct(); // No arguments if (command == NULL) { StringBuffer_concat(msg, "ERROR: Keinen Nicknamen angegeben!"); sendAll(client->socket, msg->buffer, msg->size); StringBuffer_free(msg); return EXIT_FAILURE; } Client temp; temp.name = command->buffer; // Search for double names if (clientVector_contains(clientList, &temp, &equals_Client_Name) == EXIT_SUCCESS) { StringBuffer_concat(msg, "ERROR: Es existiert bereits ein Client namens '"); StringBuffer_concat(msg, command->buffer); StringBuffer_concat(msg, "'!"); sendAll(client->socket, msg->buffer, msg->size); StringBuffer_free(msg); return EXIT_FAILURE; } StringBuffer_concat(msg, "INFO: '"); StringBuffer_concat(msg, client->name); StringBuffer_concat(msg, "' nennt sich nun '"); StringBuffer_concat(msg, command->buffer); StringBuffer_concat(msg, "'."); Client_setName(client, command->buffer); broadcast(msg); StringBuffer_free(msg); return EXIT_SUCCESS; }
/** * Post event or status data message to mmonit * @param E An event object or NULL for status data * @return If failed, return HANDLER_MMONIT flag or HANDLER_SUCCEEDED flag if succeeded */ int handle_mmonit(Event_T E) { int rv = HANDLER_MMONIT; Socket_T socket = NULL; Mmonit_T C = Run.mmonits; /* The event is sent to mmonit just once - only in the case that the state changed */ if (! C || (E && ! E->state_changed)) return HANDLER_SUCCEEDED; StringBuffer_T sb = StringBuffer_create(256); for (; C; C = C->next) { if (! (socket = socket_create_t(C->url->hostname, C->url->port, SOCKET_TCP, C->ssl, C->timeout))) { LogError("M/Monit: cannot open a connection to %s -- %s\n", C->url->url, STRERROR); goto error; } status_xml(sb, E, E ? LEVEL_SUMMARY : LEVEL_FULL, 2, socket_get_local_host(socket)); if (! data_send(socket, C, StringBuffer_toString(sb))) { LogError("M/Monit: cannot send %s message to %s\n", E ? "event" : "status", C->url->url); goto error; } StringBuffer_clear(sb); socket_shutdown_write(socket); if (! data_check(socket, C)) { LogError("M/Monit: %s message to %s failed\n", E ? "event" : "status", C->url->url); goto error; } rv = HANDLER_SUCCEEDED; // Return success if at least one M/Monit succeeded DEBUG("M/Monit: %s message sent to %s\n", E ? "event" : "status", C->url->url); error: if (socket) socket_free(&socket); } StringBuffer_free(&sb); return rv; }
int command_list(Client *client, StringBuffer *command) { StringBuffer *msg = StringBuffer_construct(); StringBuffer_concat(msg, "Verbundene Clients("); char temp[15]; sprintf(temp, "%d", clientList->size); StringBuffer_concat(msg, temp); StringBuffer_concat(msg, ")\n"); int i = 0; // Build message for (i = 0; i < clientList->size - 1; ++i) { StringBuffer_concat(msg, "["); StringBuffer_concat(msg, clientVector_get(clientList, i)->name); StringBuffer_concat(msg, "]"); StringBuffer_concat(msg, ", "); } // Add last one without , StringBuffer_concat(msg, "["); StringBuffer_concat(msg, clientVector_get(clientList, i)->name); StringBuffer_concat(msg, "]"); // Send message to client sendAll(client->socket, msg->buffer, msg->size); StringBuffer_free(msg); return EXIT_SUCCESS; }
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); }
int handle_client(int socket) { // Get the client registered to the socket Client *client = search_client(socket); if (client == NULL) { perror("Unregistered client socket found! This is not in the list!"); return EXIT_FAILURE; } // Read the complete input of the client int res = read_from_client(client); if (res != EXIT_SUCCESS) return res; // Try to extract a single message from the buffer StringBuffer *msg = extract_message(client); if (msg == NULL) { return EXIT_SUCCESS; } if (is_command(client, msg) == EXIT_SUCCESS) { handle_command(client, msg); } else { broadcast_message(client, msg); } StringBuffer_free(msg); return EXIT_SUCCESS; }
int remove_client(int socket) { // Close the socket close(socket); // Remove registered socket from poll list struct pollfd tempPollfd; tempPollfd.fd = socket; pollVector_remove(pollList, &tempPollfd, &equals_pollfd); // Remove registered Client from client list Client tempClient; tempClient.socket = socket; int i; for (i = 0 ; i < clientList->size; ++i) { if (equals_Client_Socket(&tempClient, clientVector_get(clientList, i)) == 0) { clientVector_removeAt(clientList,i , &tempClient); break; } } StringBuffer *msg = StringBuffer_construct(); StringBuffer_concat(msg, tempClient.name); StringBuffer_concat(msg, " ist offline."); broadcast(msg); Client_free(&tempClient); StringBuffer_free(msg); return EXIT_SUCCESS; }
END_TEST START_TEST (test_StringBuffer_free_NULL) { StringBuffer_free(NULL); }
int handle_command(Client *client, StringBuffer *msg) { // Skip the COMMAND_START char *syntax = msg->buffer + 1; // Extract the args of the command char *args = strchr(syntax, ' '); int syn_len = 0; // Store the args in command buffer StringBuffer *command = NULL; // When command has arguments if (args != NULL) { syn_len = args - syntax; command = StringBuffer_construct(); StringBuffer_concat(command, args + 1); } else { syn_len = msg->size; } // List command if (strncmp(syntax, "list", syn_len) == 0) { command_list(client, command); } // Nick command else if (strncmp(syntax, "nick", syn_len) == 0) { command_nick(client, command); } // Message command else if (strncmp(syntax, "msg", syn_len) == 0) { command_msg(client, command); } // Unknown command! else { StringBuffer *errorMsg = StringBuffer_construct(); StringBuffer_concat(errorMsg, "ERROR: Unbekannter Befehl '"); StringBuffer_concat(errorMsg, syntax); StringBuffer_concat(errorMsg, "'!"); sendAll(client->socket, errorMsg->buffer, errorMsg->size); StringBuffer_free(errorMsg); } // Free temp memory if (command != NULL) StringBuffer_free(command); return EXIT_SUCCESS; }
/** * Free a HttpResponse object */ static void destroy_HttpResponse(HttpResponse res) { if(res) { StringBuffer_free(&(res->outputbuffer)); if(res->headers) destroy_entry(res->headers); FREE(res); } }
static void on_connect(TCPSocket* tcp) { XFDBG("Connected with fd %d", tcp->socket.fd); StringBuffer* out = StringBuffer_from_printf(100, "foobar %d", rand()); StringBuffer_write(out, tcp->socket.fd); shutdown(tcp->socket.fd, SHUT_WR); /* indicates EOF on server side */ StringBuffer* in = StringBuffer_new(1024); StringBuffer_fdload(in, tcp->socket.fd, 128); assert(StringBuffer_equals(out, in)); StringBuffer_free(out); StringBuffer_free(in); }
void PostgresqlConnection_free(T *C) { assert(C && *C); if ((*C)->res) PQclear((*C)->res); if ((*C)->db) PQfinish((*C)->db); StringBuffer_free(&(*C)->sb); FREE(*C); }
void SqlServerConnection_free(T *C) { StringBuffer_free(&(*C)->sb); SQLDisconnect((*C)->db->hdbc); SQLFreeHandle(SQL_HANDLE_DBC, (*C)->db->hdbc); SQLFreeHandle(SQL_HANDLE_ENV,(*C)->db->henv); free((*C)->db); FREE(*C); }
void Client_free( ClientConnection *client ) { if ( !client ) return; dbg_info( "Client_free" ); switch ( client->requestType ) { case ClientRequest_announce: { ClientAnnounceData_free( client->request.announce ); break; } case ClientRequest_scrape: { ScrapeData_free( client->request.scrape ); break; } } StringBuffer_free( client->readBuffer ); StringBuffer_free( client->writeBuffer ); free( client ); }
/** * 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; }
void OracleConnection_free(T* C) { assert(C && *C); if ((*C)->svc) OCISessionEnd((*C)->svc, (*C)->err, (*C)->usr, OCI_DEFAULT); if ((*C)->srv) OCIServerDetach((*C)->srv, (*C)->err, OCI_DEFAULT); if ((*C)->env) OCIHandleFree((*C)->env, OCI_HTYPE_ENV); StringBuffer_free(&(*C)->sb); FREE(*C); }
/** * Read all processes to initialize the information tree. * @param reference reference of ProcessTree * @return treesize>0 if succeeded otherwise =0. */ int initprocesstree_sysdep(ProcessTree_T **reference) { int treesize; static kvm_t *kvm_handle; ProcessTree_T *pt; struct kinfo_proc *pinfo; if (! (kvm_handle = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, prog))) { LogError("system statistic error -- cannot initialize kvm interface\n"); return 0; } pinfo = kvm_getprocs(kvm_handle, KERN_PROC_PROC, 0, &treesize); if (! pinfo || (treesize < 1)) { LogError("system statistic error -- cannot get process tree\n"); kvm_close(kvm_handle); return 0; } pt = CALLOC(sizeof(ProcessTree_T), treesize); for (int i = 0; i < treesize; i++) { StringBuffer_T cmdline = StringBuffer_create(64); pt[i].pid = pinfo[i].ki_pid; pt[i].ppid = pinfo[i].ki_ppid; pt[i].uid = pinfo[i].ki_ruid; pt[i].euid = pinfo[i].ki_uid; pt[i].gid = pinfo[i].ki_rgid; pt[i].starttime = pinfo[i].ki_start.tv_sec; pt[i].cputime = (long)(pinfo[i].ki_runtime / 100000); pt[i].mem_kbyte = (unsigned long)(pinfo[i].ki_rssize * pagesize_kbyte); int flags = pinfo[i].ki_stat; char * procname = pinfo[i].ki_comm; if (flags == SZOMB) pt[i].zombie = true; pt[i].cpu_percent = 0; pt[i].time = get_float_time(); char **args; if ((args = kvm_getargv(kvm_handle, &pinfo[i], 0))) { for (int j = 0; args[j]; j++) StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]); pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline))); } StringBuffer_free(&cmdline); if (! pt[i].cmdline || ! *pt[i].cmdline) { FREE(pt[i].cmdline); pt[i].cmdline = Str_dup(procname); } } *reference = pt; kvm_close(kvm_handle); return treesize; }
int broadcast_message(Client *client, StringBuffer *msg) { // Construct message StringBuffer *temp = StringBuffer_construct_n(msg->size); StringBuffer_concat(temp, "["); StringBuffer_concat(temp, client->name); StringBuffer_concat(temp, "]: "); StringBuffer_concat(temp, msg->buffer); // Send message to all clients broadcast(temp); StringBuffer_free(temp); return EXIT_SUCCESS; }
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); }
END_TEST START_TEST (test_FormulaFormatter_formatRational) { StringBuffer_t *sb = StringBuffer_create(10); ASTNode_t *n = ASTNode_create(); char *s; ASTNode_setRational(n, 1, 2); FormulaFormatter_formatRational(sb, n); s = StringBuffer_toString(sb); fail_unless( !strcmp(s, "(1/2)"), NULL ); safe_free(s); ASTNode_free(n); StringBuffer_free(sb); }
ClientConnection *Client_new( void ) { ClientConnection *client = malloc( sizeof(*client) ); if ( !client ) goto badClient; client->readBuffer = StringBuffer_new( ); if ( !client->readBuffer ) goto badReadBuffer; client->writeBuffer = StringBuffer_new( ); if ( !client->writeBuffer ) goto badWriteBuffer; client->request.announce = NULL; return client; badWriteBuffer: StringBuffer_free( client->readBuffer ); badReadBuffer: free( client ); badClient: return NULL; }
int accept_newClient() { // Accept new clients in the connection queue struct sockaddr_in conInfo; socklen_t conInfo_len = sizeof(struct sockaddr_in); // Get one single client from the queue int clientSocket = accept(serverSocket, (struct sockaddr*)(&conInfo), &conInfo_len); if (clientSocket < 0) { perror("accept failed!"); return EXIT_FAILURE; } // Add client to pollList struct pollfd pollfd; pollfd.fd = clientSocket; pollfd.events = POLLIN; pollVector_add(pollList, pollfd); // Add client to clientList // Convert client address to readable IP4 formatted string // This is the standard name of all new users char *ip = inet_ntoa(conInfo.sin_addr); Client *client = Client_construct(clientSocket, ip); clientVector_add(clientList, *client); StringBuffer *msg = StringBuffer_construct(); StringBuffer_concat(msg, client->name); StringBuffer_concat(msg, " ist online"); broadcast(msg); StringBuffer_free(msg); printf("Client %s connected\n", ip); return EXIT_SUCCESS; }
void MysqlConnection_free(T *C) { assert(C && *C); mysql_close((*C)->db); StringBuffer_free(&(*C)->sb); FREE(*C); }
int command_msg(Client *client, StringBuffer *command) { // No nickname in args if (command == NULL) { StringBuffer *errMsg = StringBuffer_construct(); StringBuffer_concat(errMsg, "ERROR: Keinen Nicknamen angegeben!"); sendAll(client->socket, errMsg->buffer, errMsg->size); StringBuffer_free(errMsg); return EXIT_FAILURE; } // Look if there is an message to whisper char *whisperText = strchr(command->buffer, ' '); if (whisperText == NULL) { StringBuffer *errMsg = StringBuffer_construct(); StringBuffer_concat(errMsg, "Keine Nachricht angegeben!"); sendAll(client->socket, errMsg->buffer, errMsg->size); StringBuffer_free(errMsg); return EXIT_FAILURE; } // Split string at position *whisperText = '\0'; whisperText = whisperText + 1; // Looking for receiver Client temp; temp.name = command->buffer; Client *receiver = NULL; int i = 0; for (i = 0 ; i < clientList->size; ++i) { receiver = clientVector_get(clientList, i); // Check if names are equals if (equals_Client_Name(&temp, receiver) == 0) { break; } else { receiver = NULL; } } // Receiver not found if (receiver == NULL) { StringBuffer *errMsg = StringBuffer_construct(); StringBuffer_concat(errMsg, "ERROR: Client '"); StringBuffer_concat(errMsg, command->buffer); StringBuffer_concat(errMsg, "' ist nicht online!"); sendAll(client->socket, errMsg->buffer, errMsg->size); StringBuffer_free(errMsg); return EXIT_FAILURE; } // Build message for caller // Whisper message format: [me -> RECEIVER]: MESSAGE StringBuffer *msg = StringBuffer_construct(); StringBuffer_concat(msg, "[me -> "); StringBuffer_concat(msg, receiver->name); StringBuffer_concat(msg, "]: "); StringBuffer_concat(msg, whisperText); sendAll(client->socket, msg->buffer, msg->size); StringBuffer_clear(msg); // Build message for receiver // Whisper message format: [CALLER -> me]: MESSAGE StringBuffer_concat(msg, "["); StringBuffer_concat(msg, client->name); StringBuffer_concat(msg, " -> me]: "); StringBuffer_concat(msg, whisperText); sendAll(receiver->socket, msg->buffer, msg->size); StringBuffer_free(msg); return EXIT_SUCCESS; }
void StringBufferTest_teardown (void) { StringBuffer_free(SB); }
/** * Read all processes to initialize the information tree. * @param reference reference of ProcessTree * @return treesize > 0 if succeeded otherwise = 0. */ int initprocesstree_sysdep(ProcessTree_T **reference) { int treesize; char buf[_POSIX2_LINE_MAX]; size_t size = sizeof(maxslp); int mib_proc[6] = {CTL_KERN, KERN_PROC, KERN_PROC_KTHREAD, 0, sizeof(struct kinfo_proc), 0}; static int mib_maxslp[] = {CTL_VM, VM_MAXSLP}; ProcessTree_T *pt; kvm_t *kvm_handle; static struct kinfo_proc *pinfo; if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) { LogError("system statistic error -- vm.maxslp failed"); return FALSE; } if (sysctl(mib_proc, 6, NULL, &size, NULL, 0) == -1) { LogError("system statistic error -- kern.proc #1 failed"); return FALSE; } size *= 2; // Add reserve for new processes which were created between calls of sysctl pinfo = CALLOC(1, size); mib_proc[5] = (int)(size / sizeof(struct kinfo_proc)); if (sysctl(mib_proc, 6, pinfo, &size, NULL, 0) == -1) { FREE(pinfo); LogError("system statistic error -- kern.proc #2 failed"); return FALSE; } treesize = (int)(size / sizeof(struct kinfo_proc)); pt = CALLOC(sizeof(ProcessTree_T), treesize); if (! (kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf))) { LogError("system statistic error -- kvm_openfiles failed: %s", buf); return FALSE; } for (int i = 0; i < treesize; i++) { pt[i].pid = pinfo[i].p_pid; pt[i].ppid = pinfo[i].p_ppid; pt[i].starttime = pinfo[i].p_ustart_sec; pt[i].cputime = (long)((pinfo[i].p_rtime_sec * 10) + (pinfo[i].p_rtime_usec / 100000)); pt[i].cpu_percent = 0; pt[i].mem_kbyte = (unsigned long)(pinfo[i].p_vm_rssize * pagesize_kbyte); if (pinfo[i].p_stat == SZOMB) pt[i].status_flag |= PROCESS_ZOMBIE; //FIXME: save system service flag too (kernel threads) pt[i].time = get_float_time(); char **args; if ((args = kvm_getargv(kvm_handle, &pinfo[i], 0))) { StringBuffer_T cmdline = StringBuffer_create(64);; for (int j = 0; args[j]; j++) StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]); pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline))); StringBuffer_free(&cmdline); } if (! pt[i].cmdline || ! *pt[i].cmdline) pt[i].cmdline = Str_dup(pinfo[i].p_comm); } FREE(pinfo); kvm_close(kvm_handle); *reference = pt; return treesize; }
static void _gc_service(Service_T *s) { ASSERT(s&&*s); if ((*s)->program) { if ((*s)->program->P) Process_free(&(*s)->program->P); if ((*s)->program->C) Command_free(&(*s)->program->C); if ((*s)->program->args) gccmd(&(*s)->program->args); StringBuffer_free(&((*s)->program->output)); FREE((*s)->program); } if((*s)->portlist) _gcppl(&(*s)->portlist); if((*s)->filesystemlist) _gcfilesystem(&(*s)->filesystemlist); if((*s)->icmplist) _gcicmp(&(*s)->icmplist); if((*s)->maillist) gc_mail_list(&(*s)->maillist); if((*s)->resourcelist) _gcpql(&(*s)->resourcelist); if((*s)->inf) _gc_inf(&(*s)->inf); if((*s)->timestamplist) _gcptl(&(*s)->timestamplist); if((*s)->actionratelist) _gcparl(&(*s)->actionratelist); if((*s)->sizelist) _gcso(&(*s)->sizelist); if((*s)->matchlist) _gcmatch(&(*s)->matchlist); if((*s)->matchignorelist) _gcmatch(&(*s)->matchignorelist); if((*s)->checksum) _gcchecksum(&(*s)->checksum); if((*s)->perm) _gcperm(&(*s)->perm); if ((*s)->statuslist) _gcstatus(&(*s)->statuslist); if ((*s)->every.type == EVERY_CRON || (*s)->every.type == EVERY_NOTINCRON) FREE((*s)->every.spec.cron); if((*s)->uid) _gcuid(&(*s)->uid); if((*s)->euid) _gcuid(&(*s)->euid); if((*s)->gid) _gcgid(&(*s)->gid); if((*s)->pidlist) _gcpid(&(*s)->pidlist); if((*s)->ppidlist) _gcppid(&(*s)->ppidlist); if((*s)->dependantlist) _gcpdl(&(*s)->dependantlist); if((*s)->start) gccmd(&(*s)->start); if((*s)->stop) gccmd(&(*s)->stop); if((*s)->action_DATA) _gc_eventaction(&(*s)->action_DATA); if((*s)->action_EXEC) _gc_eventaction(&(*s)->action_EXEC); if((*s)->action_INVALID) _gc_eventaction(&(*s)->action_INVALID); if((*s)->action_NONEXIST) _gc_eventaction(&(*s)->action_NONEXIST); if((*s)->action_FSFLAG) _gc_eventaction(&(*s)->action_FSFLAG); if((*s)->action_MONIT_START) _gc_eventaction(&(*s)->action_MONIT_START); if((*s)->action_MONIT_STOP) _gc_eventaction(&(*s)->action_MONIT_STOP); if((*s)->action_MONIT_RELOAD) _gc_eventaction(&(*s)->action_MONIT_RELOAD); if((*s)->action_ACTION) _gc_eventaction(&(*s)->action_ACTION); if((*s)->eventlist) gc_event(&(*s)->eventlist); FREE((*s)->name); FREE((*s)->path); (*s)->next = NULL; FREE(*s); }
/** * 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; }
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; }
END_TEST START_TEST (test_FormulaFormatter_formatReal) { StringBuffer_t *sb = StringBuffer_create(42); char *s = StringBuffer_getBuffer(sb); ASTNode_t *n = ASTNode_create(); /** 1.2 **/ ASTNode_setReal(n, 1.2); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "1.2"), NULL ); StringBuffer_reset(sb); /** 1e-100 **/ ASTNode_setRealWithExponent(n, 1, -100); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "1.000000e-100"), NULL ); StringBuffer_reset(sb); /** NaN **/ ASTNode_setReal(n, util_NaN()); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "NaN"), NULL ); StringBuffer_reset(sb); /** Inf **/ ASTNode_setReal(n, util_PosInf()); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "INF"), NULL ); StringBuffer_reset(sb); /** -Inf **/ ASTNode_setReal(n, util_NegInf()); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "-INF"), NULL ); StringBuffer_reset(sb); /** -0 **/ ASTNode_setReal(n, util_NegZero()); FormulaFormatter_formatReal(sb, n); fail_unless( !strcmp(s, "-0"), NULL ); StringBuffer_reset(sb); StringBuffer_free(sb); ASTNode_free(n); }
/** * 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; }