int main(int argc,const char* argv[]) { int sockfd; int acceptfd; struct sockaddr_in serveraddr,clientaddr; if(argc <3) { fprintf(stderr,"Usage : %s serverip port",argv[0]); return -1; } if((sockfd = socket(AF_INET,SOCK_STREAM,0)) <0) { err_log("fail to socket"); } printf("sockfd = %d\n",sockfd); serveraddr.sin_family=AF_INET; serveraddr.sin_addr.s_addr=inet_addr(argv[1]); serveraddr.sin_port=htons(atoi(argv[2])); if(connect(sockfd,(struct sockaddr*)&serveraddr,sizeof(serveraddr))<0 ) { err_log("fail to connect"); } close(sockfd); return 0; }
void save_buffers(void *src, void *dst, off_t len) { char s[MAXPATHLEN]; FILE *sf, *df; snprintf(s, sizeof s, "/tmp/dst.%d", getpid()); df = fopen(s, "w+"); if (!df) err_log(LOGERR | LOGFATAL, "could not open dst"); snprintf(s, sizeof s, "/tmp/src.%d", getpid()); sf = fopen(s, "w+"); if (!sf) err_log(LOGERR| LOGFATAL, "could not open src"); if (!fwrite(src, io_size, 1, sf)) err_log(LOGERR| LOGFATAL, "could not write /tmp/src.%d", getpid()); if (!fwrite(dst, io_size, 1, df)) err_log(LOGERR| LOGFATAL, "could not write /tmp/dst.%d", getpid()); fclose(sf); fclose(df); }
void delete_http_request(http_request* request) { int valid = 1; if (!request) { err_log("delete_http_request: got null pointer in request"); return; } if ((!request->path) || (!request->version)) { valid = 0; info_log("request->path or request->version is null"); } if (request->variables != NULL) { if (!delete_http_request_vars(request->variables)) { valid = 0; info_log("request->variables were screwed up"); } } if (request->headers != NULL) { if (!delete_http_request_header(request->headers)) { valid = 0; } } if (!valid) { err_log("delete_http_request: request structure was malformed. got illegal null pointer"); } }
int retrieve_record(db* db_p, size_t key_size, void* key_data, size_t* data_size, void** data){ int ret = 1; if(NULL == db_p || NULL == db_p->bdb_ptr){ if(db_p == NULL){ err_log("DB retrieve_record : db_p is null.\n"); } else{ err_log("DB retrieve_record : db_p->bdb_ptr is null.\n"); } goto db_retrieve_return; } DB* b_db = db_p->bdb_ptr; DBT key, db_data; memset(&key, 0, sizeof(key)); memset(&db_data, 0, sizeof(db_data)); key.data = key_data; key.size = key_size; db_data.flags = DB_DBT_MALLOC; if((ret = b_db->get(b_db, NULL, &key, &db_data, 0)) == 0){ }else{ err_log("DB : %s.\n", db_strerror(ret)); goto db_retrieve_return; } if(!db_data.size){ goto db_retrieve_return; } *data = db_data.data; *data_size = db_data.size; db_retrieve_return: return ret; }
int main(int argc, const char *argv[]) { int sockfd; int acceptfd; struct sockaddr_un serveraddr, clientaddr; char buf[N] = {}; if((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { err_log("fail to socket"); } printf("sockfd = %d\n", sockfd); serveraddr.sun_family = AF_UNIX; strcpy(serveraddr.sun_path , "mysocket"); if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { err_log("fail to bind"); } if(listen(sockfd, 15) < 0) { err_log("fail to listen"); } socklen_t addrlen = sizeof(struct sockaddr); if((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr,&addrlen)) < 0) { err_log("fail to accept"); } printf("acceptfd = %d\n", acceptfd); printf("clientaddr.sun_path:%s\n", clientaddr.sun_path); while(1) { recv(acceptfd, buf, N, 0); printf("server:%s\n", buf); if(strncmp(buf, "quit", 4) == 0) break; strcat(buf, " from server."); send(acceptfd, buf, N, 0); } close(acceptfd); close(sockfd); return 0; }
int store_record(db* db_p, size_t key_size, void* key_data, size_t data_size, void* data){ int ret = 1; if((NULL == db_p)||(NULL == db_p->bdb_ptr)){ if(db_p == NULL){ err_log("DB store_record : db_p is null.\n"); } else{ err_log("DB store_recor : db_p->bdb_ptr is null.\n"); } goto db_store_return; } DB* b_db = db_p->bdb_ptr; DBT key,db_data; memset(&key, 0, sizeof(key)); memset(&db_data, 0, sizeof(db_data)); key.data = key_data; key.size = key_size; db_data.data = data; db_data.size = data_size; if ((ret = b_db->put(b_db,NULL,&key,&db_data,DB_AUTO_COMMIT)) == 0){ } else{ err_log("DB : %s.\n", db_strerror(ret)); } db_store_return: return ret; }
int main(int argc, const char *argv[]) { int sockfd; struct sockaddr_in serveraddr, clientaddr; char buf[N] = {}; if(argc < 3) { fprintf(stderr, "usage:%s serverip port.\n", argv[0]); return -1; } if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { err_log("fail to socket"); } printf("sockfd = %d\n", sockfd); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr(argv[1]); serveraddr.sin_port = htons(atoi(argv[2])); if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) { err_log("fail to bind"); } socklen_t addrlen = sizeof(struct sockaddr); while(1) { if(recvfrom(sockfd, buf, N, 0, (struct sockaddr*)&clientaddr, &addrlen) < 0) { err_log("fail to recvfrom"); } printf("%s\n", buf); if(strncmp(buf, "quit", 4) == 0) break; strcat(buf, " from server."); if(sendto(sockfd, buf, N, 0, (struct sockaddr *)&clientaddr, addrlen) < 0) { err_log("fail to sendto"); } } close(sockfd); return 0; }
db* initialize_db(const char* db_name, uint32_t flag){ db* db_ptr = NULL; DB* b_db; DB_ENV* dbenv; int ret; char* full_path = NULL; if((ret = mkdir(db_dir,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) != 0){ if(errno!=EEXIST){ err_log("DB : Dir Creation Failed\n"); goto db_init_return; } } full_path = (char*)malloc(strlen(db_dir) + strlen(db_name) + 2); mk_path(full_path, db_dir, db_name); #ifdef ENV if ((ret = db_env_create(&dbenv, 0)) != 0) { dbenv->err(dbenv, ret, "Environment Created: %s", db_dir); goto db_init_return; } if ((ret = dbenv->open(dbenv, db_dir, DB_CREATE|DB_INIT_CDB|DB_INIT_MPOOL|DB_THREAD, 0)) != 0) { //dbenv->err(dbenv, ret, "Environment Open: %s", db_dir); goto db_init_return; } /* Initialize the DB handle */ if((ret = db_create(&b_db,dbenv,flag)) != 0){ err_log("DB : %s.\n", db_strerror(ret)); goto db_init_return; } #else /* Initialize the DB handle */ if((ret = db_create(&b_db,NULL,flag)) != 0){ err_log("DB : %s.\n", db_strerror(ret)); goto db_init_return; } #endif if((ret = b_db->set_pagesize(b_db, pagesize)) != 0){ err_log("DB : %s.\n", db_strerror(ret)); goto db_init_return; } if((ret = b_db->open(b_db, NULL, db_name, NULL, DB_BTREE, DB_THREAD|DB_CREATE,0)) != 0){ // db_name is the on-disk file that holds the database //b_db->err(b_db,ret,"%s","test.db"); goto db_init_return; } db_ptr = (db*)(malloc(sizeof(db))); db_ptr->bdb_ptr = b_db; db_init_return: if(full_path != NULL){ free(full_path); } if(db_ptr != NULL){ ; } return db_ptr; }
/* * get_orig_file_name() */ parse_code_e get_orig_file_name(const char * dir_name, const char * prefix, const char * suffix, char * ret_file_name) { int ret; DIR * pdir = NULL; struct dirent * pdirent; struct stat stat_buff; char tmp_file_name[MAX_FILENAME]; ret = PARSE_UNMATCH; if(dir_name == NULL) { err_log("get_orig_file_name: dir name is null\n"); ret = PARSE_FAIL; goto Exit_Pro; } pdir = opendir(dir_name); if(pdir == NULL) { err_log("get_orig_file_name: opendir fail\n"); ret = PARSE_FAIL; goto Exit_Pro; } while( (pdirent = readdir(pdir)) != NULL ) { /* 前后缀匹配检查 */ if( pre_suf_check(pdirent->d_name, prefix, suffix) != PARSE_MATCH ) continue; /* 文件检查 */ strcpy(tmp_file_name, dir_name); strcat(tmp_file_name, "/"); strcat(tmp_file_name, pdirent->d_name); if(stat(tmp_file_name, &stat_buff) == -1) { err_log("get_orig_file_name: stat %s fail\n", pdirent->d_name); ret = PARSE_FAIL; break; } if(S_ISREG(stat_buff.st_mode)) { strcpy(ret_file_name, pdirent->d_name); ret = PARSE_MATCH; break; } } Exit_Pro: if(pdir != NULL) closedir(pdir); return ret; }
void handle_http_get_request(http_client* client, http_request* request) { if ((!client) || (!request)) { err_log("handle_http_get_request: got null pointer in client or request"); return; } char* sanitized_path = sanitize_path(request->path+1); /* skip '/' at beginning of path ***FIXME*** */ if (!sanitized_path) { err_log("handle_http_get_request: illegal path: %s", request->path); } if (0 == strcmp(sanitized_path, MAGIC_FILE_NAME)) { if (!canbus_modify_message(request)) err_log("handle_http_get_request: canbus_modify_message() failed"); char response_header[] = "HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"; Send(client->sock, response_header, strlen(response_header)); #ifdef SPRITZE canbus_send_message(); #endif return; } /* ***FIXME*** use absolute path, webserver root directory, etc. */ FILE* f = fopen(sanitized_path, "r"); if (!f) { char msg[] = "HTTP/1.1 404 File Not Found\r\n\r\n" "<html><title>404</title><body><h1>" "404 File Not Found</h1></body></html>\r\n"; Send(client->sock, msg, strlen(msg)); return; } struct stat file_info; if (-1 == (fstat(fileno(f), &file_info))) { fclose(f); err_sys("handle_http_get_request: fstat() failed"); return; } char response_header[MAX_HTTP_RESPONSE_LENGTH+1] = "HTTP/1.1 200 OK\r\nConnection: close\r\n"; char length[255]; snprintf(length, sizeof(length), "Content-Length: %d\r\n", (int)file_info.st_size); strncat(response_header, length, sizeof(response_header)-strlen(response_header)-1); strncat(response_header, "Content-Type: application/xml\r\n\r\n", sizeof(response_header)-strlen(response_header)-1); response_header[MAX_HTTP_RESPONSE_LENGTH] = '\0'; Send(client->sock, response_header, strlen(response_header)); send_file(client, request, f); fclose(f); /* checking return value is pointless, since if fclose() fails, */ /* we can't do anything useful about it. */ }
int main(int argc, const char *argv[]) { int sockfd; struct sockaddr_in broadcastaddr; char buf[N] = {}; int on = 1; if(argc < 3) { fprintf(stderr, "usage:%s serverip port.\n", argv[0]); return -1; } if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { err_log("fail to socket"); } printf("sockfd = %d\n", sockfd); broadcastaddr.sin_family = AF_INET; broadcastaddr.sin_addr.s_addr = inet_addr(argv[1]); broadcastaddr.sin_port = htons(atoi(argv[2])); if(setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(int)) < 0) { err_log("fail to setsockopt."); } socklen_t addrlen = sizeof(struct sockaddr); while(1) { printf("Input:"); fgets(buf, N, stdin); buf[strlen(buf)-1] = '\0'; if(sendto(sockfd, buf, N, 0, (struct sockaddr *)&broadcastaddr, sizeof(broadcastaddr)) < 0) { err_log("fail to sendto"); } if(strncmp(buf, "quit", 4) == 0) break; } close(sockfd); return 0; }
int check_passwd(const char *name, const char *passwd) { char pathname[32] = {"/home/qiong/userinfo/"}; char tmp[40]; int len; int fd; int ret; if (name == NULL || passwd == NULL) { sys_log("用户名或密码为空"); return -2; } strcat(pathname, name); if ((fd = open(pathname, O_RDONLY)) == -1) { return -1; } if (lseek(fd, 0, SEEK_END) == -1) { err_log("lseek 错误"); my_err("lseek", __LINE__); } if ((len = lseek(fd, 0, SEEK_END)) == -1) { err_log("lseek 错误"); my_err("lseek", __LINE__); } if (lseek(fd, 0, SEEK_SET) == -1) { err_log("lseek 错误"); my_err("lseek", __LINE__); } if ((ret = read(fd, tmp, len)) < 0) { err_log("read 错误"); my_err("read", __LINE__); } close(fd); return (strncmp(tmp, passwd, strlen(passwd))); //若返回0,则表示用户名和密码都正确 }
bool Task::parseListen(const TaskConfig &tc, const std::string &log_label) { auto to = tc.cfg().upper_bound("listen"); for (auto p=tc.cfg().lower_bound("listen"); p!=to; ++p) { std::istringstream s(p->second); uint16_t port; std::string ip; s >> port; if (!s) { err_log() << "Bad configuration directive: listen " << p->second; setError("bad configuration directive"); return false; } s >> ip; bool tls; if (ip.empty()) { tls = false; } else if (ip == "tls") { ip.clear(); tls = true; } else { std::string tmp; s >> tmp; tls = (tmp == "tls"); } auto sock = new ServerSocket(log_label, this, port, ip); #ifdef USE_GNUTLS if (tls) { std::string cert, key, password; s >> cert >> key >> password; if (key.empty() || !tlsSetKey(sock, cert, key, password)) { err_log() << "Bad configuration: " << p->second; setError("cannot use TLS certificate"); return false; } log() << "Port " << port << " enable TLS"; } #else if (tls) { err_log() << "cannot enable TLS, will not listen on port " << port; return false; } #endif if (!addServer(sock)) { setError("cannot listen"); return false; } } return true; }
/** * Interrumpe ejecucion del programa. Dependiendo del valor del parametro * que se le pase interrumpe mas o menos cosas. * Q == 4 : interrupcion por muerte de gpsd, cierra todo menos gpsd * Q == 3 : interrupcion por muerte del parser, cierra todo menos parser * Q == 2 : interrupcion manual (ctrl-c), cierra todo y avisa que fue manual * Q == 1 : interrupcion por muerte del sbusd, cierra todo menos sbusd * Q == 0 : interrupcion estandar, cierra todo * Q cualquier otro : igual que Q == 0. * * TODO QUE HACER CUANDO ALGO FALLA Y NECESITAMOS APAGAR LOS MOTORES! * TODO SI SE CIERRA GPSD TRATAR DE ABRIRLO DENUEVO? */ void quit(int Q) { int retval; if(Q == 2) { err_log("interrumpido manualmente (ctrl-c)"); //TODO no funco bien en la beagle } else err_log("algo salio mal, cerrando..."); if(Q != 1) { /// Terminar Demonio S-BUS retval = system(KILL_SBUS); //sprintf(str, "kill -SIGTERM %d", sbusd_child_pid); //retval = system(str); if (retval < 0) err_log("Could not terminate sbusd!"); } /* /// cerrar IO manager retval = io_deinit(io); if(retval != ERROR_OK) err_log("Could not close IO correctly!");*/ /// Kernel Messeges Queue uquad_kmsgq_deinit(kmsgq); /// Log close(log_fd); #if !SIMULATE_GPS if(Q != 4) { /// cerrar conexiones con GPSD y terminarlo retval = deinit_gps(); if(retval != ERROR_OK) err_log("Could not close gps correctly!"); } #endif // !SIMULATE_GPS #if !DISABLE_UAVTALK if(Q != 3) { /// cerrar UAVTalk retval = kill(uavtalk_child_pid, SIGKILL); if(retval != ERROR_OK) err_log("Could not close Parser correctly!"); } #endif // !DISABLE_UAVTALK exit(0); }
PollState HttpServerConnection::writeData() { if (is_websocket) return wsWriteData(); if (state == HttpState::SENDING_RESPONSE) { // TODO: don't give conn to the owner, too much that can go wrong. size_t sent; #ifdef USE_WEBROOT if (sending_static_file) sent = sendFileData(static_file_fd, remaining_bytes); else #endif sent = owner_task->sendResponseData(this, remaining_bytes); remaining_bytes -= sent; if (remaining_bytes) return PollState::WRITE; #ifdef USE_WEBROOT if (sending_static_file) { close(static_file_fd); sending_static_file = false; } #endif state = HttpState::WAITING_FOR_REQUEST; return PollState::READ; } err_log() << "HttpServerConnection::writeData() called"; return PollState::CLOSE; }
http_client* add_client(client_list* clients, SOCKET sock) { if ((!clients) || (!clients->head)) { err_log("add_client: got null pointer in clients or clients->head"); return NULL; } http_client* node = clients->head; while (node->next) node = node->next; http_client* new_node = malloc(sizeof(struct client_list_node_t)); if (!new_node) err_sys("add_client: malloc failed"); new_node->recvbuf = malloc(sizeof(char) * (MAXLINE+1)); if (!new_node->recvbuf) err_sys("add_client: malloc failed"); new_node->currpos = new_node->recvbuf; new_node->sock = sock; new_node->next = 0; node->next = new_node; clients->count++; return new_node; }
int main(int argc, const char *argv[]) { int sockfd; struct sockaddr_in serveraddr, clientaddr; char buf[N] = {}; pid_t pid; if(argc < 3) { fprintf(stderr, "usage:%s serverip port.\n", argv[0]); return -1; } sockfd= socket_init("AF_INET",argv[1],argv[2]); pid =fork(); if(pid < 0) { err_log("fail to fork\n"); } if(pid ==0) { printf("child\n"); child_process_recv(sockfd); } if(pid > 0) { parent_process_send(sockfd); } close(sockfd); return 0; }
void child_process_recv(int sockfd) { char buf[N]; struct sockaddr_in serveraddr, clientaddr; socklen_t addrlen = sizeof(struct sockaddr); DLinkList* list=DLinkList_Create(); while(1) { if(recvfrom(sockfd, &buf, N, 0, (struct sockaddr*)&clientaddr, &addrlen) < 0) { err_log("fail to recvfrom\n"); } printf("%s\n",buf); switch(buf[0]) { case 'C': we_chat(sockfd, list,buf,clientaddr); break; case 'Q': user_quit(sockfd, list,clientaddr); break; case 'L': user_login(sockfd, list,buf,clientaddr); break; } } }
int del_client(client_list* clients, SOCKET sock) { if ((!clients) || (!clients->head)) { err_log("del_client: got null pointer in clients or clients->head"); return 0; } if (0 == clients->count) return 0; http_client* node = clients->head->next; http_client* prev = clients->head; do { if (node->sock == sock) { http_client* delete_me = node; prev->next = node->next; clients->count--; if (delete_me->recvbuf != NULL) free(delete_me->recvbuf); free(delete_me); return 1; } node = node->next; prev = prev->next; } while (node); return 0; }
void control_deinit(ctrl_t *ctrl) { if (ctrl == NULL) { err_log("No memory had been allocated for ctrl"); return; } uquad_mat_free(ctrl->K); uquad_mat_free(tmp_sub_sp_x); uquad_mat_free(w_tmp); uquad_mat_free(ctrl->A); uquad_mat_free(ctrl->B); uquad_mat_free(ctrl->Q); uquad_mat_free(ctrl->R); #if !FULL_CONTROL uquad_mat_free(tmp_x_hat_partial); #endif // !FULL_CONTROL #if CTRL_INTEGRAL uquad_mat_free(ctrl->K_int); uquad_mat_free(ctrl->x_int); uquad_mat_free(x_int_tmp); #endif free(ctrl); }
PollState HttpServerConnection::got_post_data(const char *buf, size_t len) { //log() << "got_post_data " << len << " bytes, " << remaining_post_data // << " left\n" << std::string(buf, len); size_t length = std::min(remaining_post_data, len); remaining_post_data -= length; if (remaining_post_data) { if (!buffer_post_data) if (!owner_task->partialPostData(this, buf, length)) return PollState::CLOSE; } else { if (buffer_post_data) state = owner_task->lastPostData(this, buffer.c_str(), buffer.size()); else state = owner_task->lastPostData(this, buf, len); if (len > length) { err_log() << "too much post data sent"; return PollState::CLOSE; } if (state == HttpState::SENDING_RESPONSE) return PollState::WRITE; else if (state == HttpState::CLOSE) return PollState::CLOSE; } return PollState::READ; }
int CreateProc::Run() { AppSetting *setting = AppSetting::Instance(); int result; // Extract zip if ((result = ZExtractor::Extract(zipFullname, _extDir, true)) != NO_ERROR) { err_log("error : %s\n", error_msg(result)); return result; } else { if (FileSys::IsEmptyDir(_extDir)) { FileSys::DeleteFile(_extDir); return EMPTY_ZIP_FILE; } } // Level off dir FileSys::LevelOff(_extDir, FileOverride::RenameWithOrder, setting->zip_filter_regex, _leveloffDir); // Rename files _RenameFiles(); // Resize and push json _ResizeFiles(); return NO_ERROR; }
int process_list(int sockfd) { DIR *dir; struct dirent * dp; char buf[N] = {}; dir = opendir("."); if(dir == NULL) { err_log("fail to opendir"); } while((dp = readdir(dir)) != NULL) { if(dp->d_name[0] == '.') { continue; } strcpy(buf, dp->d_name); send(sockfd, buf, N, 0); usleep(15); } close(sockfd); return 0; }
void killall(void) { char s[MAXPATHLEN]; switch (fork()) { case -1: err_log(LOGERR | LOGFATAL, "could not kill all processes"); /* NOTREACHED */ break; case 0: /* * XXX: Clean this up. This will kill other none iogen * torture processes. */ sleep(2); /* wait until dad dies */ snprintf(s, sizeof s, "/usr/bin/pkill torture"); system(s); exit(0); /* NOTREACHED */ default: exit(0); /* NOTREACHED */ break; } }
void http_request_add_variable(http_request* request, char* name, char* value) { if ((!request) || (!name) || (!value)) { err_log("http_request_add_variable: got null pointer in request, name or value"); return; } http_request_vars_list* new_entry = malloc(sizeof(http_request_vars_list)); if (!new_entry) { err_sys("http_request_add_variable: malloc() failed"); return; } new_entry->name = name; new_entry->value = value; new_entry->next = 0; if (!request->variables) { request->variables = new_entry; return; } http_request_vars_list* node = request->variables; while (node->next) node = node->next; node->next = new_entry; return; }
void signal_ign_process(int signo) { pid_t pid; int stat; while (pid = waitpid(-1, &stat, WNOHANG) > 0) { err_log("child %d terminated!\n", pid); } return; }
// Create_client: pour client un client admin Client* create_client() { Client* c = (Client *)malloc(sizeof(Client)); if ( c == (Client *)NULL ) { err_log("create_client.malloc", stderr) exit(EXIT_FAILURE); } return c; }
/* * Logs the error and then frees it. This function is equivalent to * err_log(err); * err_free(err); * * Arguments: * err The error. * level The logging level. */ void err_log_and_free( ErrorObj* const err, const enum err_level level) { err_log(err, level); err_free(err); }
void Printer::handle_rr_error (rr_dev dev, int error_code, const char *msg, size_t len) { err_log(msg); // char *str = g_strndup (msg, len); // g_warning (_("Error (%d) '%s' - user popup ?"), error_code, str); // g_free (str); }
size_t HttpServerConnection::chunkedResponseComplete() { if (!sending_chunked_response) { err_log("response encoding is not chunked"); return 0; } std::string last_chunk = "0\r\n\r\n"; sending_chunked_response = false; asyncSendData(last_chunk); return last_chunk.size(); }