コード例 #1
0
ファイル: vdbcon.c プロジェクト: vSlipenchuk/vdb
int vdbcon_main(int npar,char **par) {
//unsigned char *p; int ok;

//vdb_static(0,"sqlite",sq_connect); // test for sqlite
vdb_static(0,"vora",ora_connect); // test for oracle


#ifdef TESTMODULE
TESTMODULE
#endif
if (npar<2) { prn_help(); return 1;}
db = db_new(); strcpy(cs,par[1]);
if (!db_connect_string(db,cs)) {
  fprintf(stderr,"-ErrOnConnect: %s\n",db->error);
  return 2;
  }
int i;
fprintf(stderr,"+vdb connected '%s'\n",cs);
for(i=2;i<npar;i++) {
 //strcpy(buf,par[i]);
 //if (!buf[0]) exit(0);
 //process(buf);
 process(par[i]);
 }
//buf[0]=0;
process_file(stdin);
/*
while(1) {
 int l;
 if (buf[0]) fprintf(stderr,">"); else fprintf(stderr,"vdb>");
 sbuf[0]=0;
 while (!kbhit()) { if (vdb_http_process()<1) msleep(100); }
 if (!fgets(sbuf,sizeof(sbuf),stdin)) break; // EOF
 if (!sbuf[0]) break;
 l=strlen(sbuf);
 while(l>0 && (strchr("\r\n",sbuf[l-1]) )) l--;
 if (buf[0] ==0 && l==0) break; // empty line in a middle
 if ((sbuf[0]=='.') && (buf[0]==0)) { // one line command
    sbuf[l]=0;
    process(sbuf);
    }
 else {
    l = strlen(buf)+strlen(sbuf);
    if (l+1>=sizeof(buf)) {
       fprintf(stderr,"too long command max:%ld\n",sizeof(buf));
       exit(2);
       }
    strcat(buf,sbuf);
    while(l>0 && (strchr("\r\n",buf[l-1]) )) l--; // rtrim
    //printf("NEWBUF:%s\n",buf);
    if ( l > 0 && buf[l-1]==';') { // ok - last here
       buf[l-1]=0;
       process(buf);
       buf[0]=0;
       }
    }
 }
 */
return 0;
}
コード例 #2
0
ファイル: main.c プロジェクト: bbehrang/CoursesRepo
int main(void) {
	// initializing first three investors for program to start with
	// initializing_END

	int PORT = 5000;
	lib_init();
	winSock = socket_new();
    db_t * db = db_new("teacher.db");
	// Checking if socket is not busy, closing app if it is
	if (socket_bind(winSock, PORT) == SOCKET_ERROR) {
		printf("Cannot bind %i port\n", PORT);
		socket_close(winSock);
		socket_free(winSock);
		return 0;
	}

	socket_listen(winSock);
	char buf[10000];
	socket_t * client = NULL;
	// main cycle of the program
	while (1) {
		printf("Awaiting for connections...\n");
		client = socket_accept(winSock);

		// Checking if client is not null, closing app if he is
		if (client == NULL) {
			printf("NULL client, closing app...\n");
			break;
		}

		int readStatus = socket_read(client, buf, sizeof(buf));

		// Skipping empty request (may appear from time to time)
		if (readStatus <= 0) {
			printf("Empty request, skipping...\n");
			socket_close(client);
			socket_free(client);
			continue;
		}

		// Printing info about the received request to console
		printf(">> Got request (readStatus: %i):\n'%s'\n", readStatus, buf);
		http_request_t request = http_request_parse(buf);

		// check the type/path of request (API/HTML) & analyze the method (GET/POST/DELETE)
		// and provide the client with proper answer
		server_analyzeRequest(&request, client, db);

		socket_free(client);
	}

	// end of program
	socket_close(winSock);
	socket_free(winSock);
	db_free(db);
	lib_free();
	return 0;
}
コード例 #3
0
ファイル: main.c プロジェクト: Armen-Arakelian/Armen
int main(void) {
    const char * dbFile = "db.db";
    patient_t patientList[100];
    db_t * db = db_new(dbFile);

    int countAllPatients = db_countPatients(db);
    printf("Students total: %i\n\n", countAllPatients);
    patient_t * pt1 = patient_new();
    pt1 = db_getPatientById(db, 1);
    patient_print(pt1);
    printf("\nnext test\n");
    int time = 5;
    char disease[100] = "s";
    int count = db_checkPatient(db, time, disease, patientList, 100);
    printf("Count of patients with time > 5 and disease 's'% d\n", count);
    patient_printList(patientList, count);
    printf("\nnext test\n");
    patient_t * pt2 = patient_new();
    strcpy(pt2->name, "a");
    strcpy(pt2->surname, "aa");
    pt2->age = 43;
    strcpy(pt2->disease, "2015-02-07");
    pt2->time = 11;
    pt2->weight = 73.4;
    strcpy(pt2->disease, "dfgd");

    patient_t * pt3 = patient_new();
    strcpy(pt3->name, "b");
    strcpy(pt3->surname, "bb");
    pt3->age = 31;
    strcpy(pt3->disease, "2015-05-07");
    pt3->time = 111;
    pt3->weight = 61.4;
    strcpy(pt3->disease, "jhgkjhgvkjgkg");

    pt2->id = db_insertPatient(db, pt2);
    printf("%d", pt2->id);
    patient_print(pt2);
    printf("\nnext test\n");

    pt2->age = 19;
    db_updatePatient(db, pt2);
    patient_print(pt2);
    db_deletePatient(db, 3);
    printf("%d", db_countPatients(db));

    db_free(db);
    return 0;
}
コード例 #4
0
ファイル: main.c プロジェクト: AndreyKrysyuk/KP52OP
int main(void) {
    const char * dbFile = "pupils.db";
    pupils_t pupilsList[100];
    db_t * db = db_new(dbFile);

    int countAllPupils = db_countPupils(db);
    int numberPupils = 2;
    int form = 10;

    printf("Pupils total: %i\n\n", countAllPupils);
    int count = db_getPupilsTask(db, numberPupils, form, pupilsList);
    printf("%i pupils with max score from %i form:\n", numberPupils, form);
    pupils_printList(pupilsList, count);

    printf("Pupil with id 5\n");
    pupils_t * pupil = db_getPupilById(db, 5);
    pupil_print(pupil);


    pupils_t * newpupil = malloc(sizeof(struct pupils_s));
    strcpy(newpupil->name, "Igor");
    strcpy(newpupil->surname, "Lastochkin");
    strcpy(newpupil->birthDate, "1990-12-12");
    newpupil->score = 11.0;
    newpupil->form = 11;
    printf("New pupil id: %i\n", db_insertPupil(db, newpupil));


    printf("Count pupils before delete: %i\n",db_countPupils(db));
    db_deletePupil(db, 6);
    printf("Count pupils after delete: %i\n",db_countPupils(db));


    pupils_t * updated_pupil = malloc(sizeof(struct pupils_s));
    strcpy(updated_pupil->name, "Igor");
    strcpy(updated_pupil->surname, "Drinkin");
    strcpy(updated_pupil->birthDate, "1999-11-13");
    updated_pupil->score = 9.0;
    updated_pupil->form = 7;
    db_updatePupil(db, updated_pupil, 12);

    free(updated_pupil);
    free(pupil);
    free(newpupil);
    db_free(db);
    return 0;

}
コード例 #5
0
ファイル: main.c プロジェクト: AndrienkoF/KPIRepo
int main(){
	const int size = 4;
	leadingList_t * newLeadingList = leadingList_new(size);
	db_t * newDb = db_new("database.db");

	int countSize = db_getSize(newDb);

	leading_t * newLeading;

	db_readList(newDb, newLeadingList);
	leadingList_print(newLeadingList);

	leading_free(newLeading );
	leadingList_free(newLeadingList);
	db_free(newDb);
    return 0;
}
コード例 #6
0
ファイル: db_update.c プロジェクト: m3y54m/32bitmicro
/*------------------------------------------------------------------------
 *  db_update - update/insert a link state advertisement
 *------------------------------------------------------------------------
 */
int
db_update(struct ospf_ar *par, struct ospf_lsa *plsa)
{
	struct ospf_db	*pdb;

	if (pdb = db_lookup(par, plsa->lsa_type, plsa->lsa_lsid)) {
	} else {
		int	hv;

		pdb = db_new(par, plsa);
		pdb->db_lnext = par->ar_dblhead;
		par->ar_dblhead = pdb;
		hv = DBHASH(pdb->db_lsa.lsa_lsid);
		pdb->db_hnext = par->ar_htable[hv];
		par->ar_htable[hv] = pdb;
	}
}
コード例 #7
0
ファイル: db.c プロジェクト: carnil/nodau
/* open an existing note */
int db_edit(char* search)
{
    char* date;
    char* name;
    char* text;
    char* crypt;
    int r;
    /* get the note by name */
    sql_result *result;
    result = db_get("SELECT * FROM nodau WHERE name = '%s'",search);

    /* nothing there */
    if (result->num_rows == 0) {
        db_result_free(result);
        if (config_read("edit_autocreate","false")) {
            printf("No notes match '%s'\n",search);
        } else {
            return db_new(search);
        }
        return 0;
    }

    /* get the data */
    date = db_gettime(result->data[COLUMN(0,COL_DATE)]);
    name = result->data[COLUMN(0,COL_NAME)];
    text = result->data[COLUMN(0,COL_TEXT)];
    crypt = result->data[COLUMN(0,COL_CRYPT)];

    /* get the passphrase if it's encrypted */
    if (!strcmp(crypt,"true")) {
        crypt = crypt_get_key();
        text = note_decrypt(text,crypt);
        if (!text)
            return 1;
    }

    /* edit the note */
    r = edit(name, date, text);

    /* free the result */
    db_result_free(result);

    return r;
}
コード例 #8
0
ファイル: ydb_public.c プロジェクト: pombredanne/ydb
struct ydb *ydb_open(const char *directory, struct ydb_options *options)
{
	struct db *db = db_new(directory);
	if (db == NULL) {
		return NULL;
	}

	struct base *base = base_new(db, db_log_dir(db), db_index_dir(db),
				     options);
	if (base == NULL) {
		db_free(db);
		return NULL;
	}
	log_info(db, "Opening YDB database \"%s\" by pid=%i.",
		 directory, getpid());

	linux_check_overcommit(db);

	struct ydb *ydb = malloc(sizeof(struct ydb));
	ydb->db = db;
	ydb->base = base;

	struct timeval tv0, tv1;
	gettimeofday(&tv0, NULL);

	int r = base_load(ydb->base);
	if (r != 0) {
		_ydb_close(ydb, 0);
		return NULL;
	}
	base_print_stats(ydb->base);
	gettimeofday(&tv1, NULL);
	log_info(db, "YDB loaded %llu items in %.3f seconds.",
		 (unsigned long long)base->used_size.count,
		 (float)TIMEVAL_MSEC_SUBTRACT(tv1, tv0) / 1000.);
	return ydb;
}
コード例 #9
0
ファイル: main.c プロジェクト: samokhvalenko/samokh-52
void server_students(socket_t * client, http_request_t * req) {
    char strbuf[10240];
    if (strcmp(req->method, "GET") == 0) {
		char allStudentsJson[10240] = "";
		char buf[1000];
        list_t persons = list_new();
		FILE * file = fopen("Untitled1.xml", "r");
		while(fgets(buf, 1000, file) != NULL)
		{
			strcat(allStudentsJson, buf);
			puts(buf);
		}
        db_t * db = db_new("worker.db");
        
        
        for(int i = 1; i < 6; i++){
            struct person * pers = malloc(sizeof(struct person));
            pers = db_getWorkerById(db, i);
            list_add(persons, pers, list_size(persons));
        }
        
        char xml_buf[10000];
        strcpy(xml_buf, list_to_xml_string(persons));
		//list_to_xml(persons);
        puts(xml_buf);
        sprintf(strbuf,
            "HTTP/1.1 200 OK\n"
            "Content-Type: text/xml\n"
            "Content-Length: %u\n"
            "Connection: keep-alive\n"
            "\n%s", strlen(xml_buf), xml_buf);
		fclose(file);
	}
    socket_write_string(client, strbuf);
    socket_close(client);
}
コード例 #10
0
ファイル: main.c プロジェクト: Konimiks/hello-world
int main()
{
    db_t* base = db_new("workers.db");
    lib_init();

    socket_t* server = socket_new();
    socket_bind(server, PORT);
    socket_listen(server);

    char buffer[10000];
    while(true)
    {
        puts("Waiting for client...!");
        socket_t* client = socket_accept(server);

        if(socket_read(client, buffer, sizeof(buffer)) <= 0)
        {
            socket_close(client);
            socket_free(client);
            continue;
        }

        printf("Request:\n%s\n", buffer);

        http_request_t request = http_request_parse(buffer);

        server_answerRequest(request, client, base);

        socket_free(client);
    }

    socket_free(server);
    lib_free();
    db_free(base);
    return 0;
}
コード例 #11
0
ファイル: main.c プロジェクト: vSlipenchuk/httpdb
int main(int npar,char **par) {

//    return httpGetTest();

    db = db_new();
    if (db_connect_string(db,"/@my.db#./sq3u.so")<=0) {
        printf("Fail connect to db err=%s\n",db->error);
        return 1;
       }
    printf("db connected OK\n");

//return tcpEventerMain(npar,par);

tcpEventerMainBegin(); // create an eventer
/*
    tcpEventer *e  = tcpEventerCreate("");
      e->logLevel=10; e->srv
      tcpEventerListen(e,2020); tcpEventerProcess(e); // TEST - forewer
*/

    return MicroHttpMain(npar,par);
    //printf("Hello world!\n");
    return 0;
}
コード例 #12
0
ファイル: i_chat.c プロジェクト: hengzhang/NEU_MSN
void initChatList(void)
{
    chatList = db_new(NULL);
}
コード例 #13
0
ファイル: m_broadcast.c プロジェクト: hengzhang/NEU_MSN
void initBroadcastList(void)
{
    broadcastList = db_new(NULL);
}
コード例 #14
0
ファイル: main.c プロジェクト: LobovVitaliy/CoursesRepo
int main()
{
    lib_init();
    printf("PORT: %i\n\n", PORT);
    socket_t * server = socket_new();
    socket_bind(server, PORT);
    socket_listen(server);

    char buffer[10000];
    socket_t * client = NULL;

    // работа с базой данных
    const char * dbFile = "ScrumMaster.db";
    db_t * db = db_new(dbFile);
    // работа с базой данных

    while(1)
    {
        client = socket_accept(server);
        socket_read(client, buffer, sizeof(buffer));

        if(strlen(buffer) != 0)
        {
            printf(">> Got request:\n%s\n", buffer);
            http_request_t request = http_request_parse(buffer);

            if (strcmp(request.uri, "/") == 0)
            {
                server_homepage(client);
            }
            else if (strcmp(request.uri, "/api/ScrumMasters") == 0)  // else if (strncmp(request.uri, "/api/ScrumMasters?", 18) == 0)
            {
                server_masters(client, &request, db);
            }
            else if (strncmp(request.uri, "/api/ScrumMasters/", 18) == 0)
            {
                server_mastersByID(client, &request, db);
            }
            else if (strcmp(request.uri, "/ScrumMasters") == 0)
            {
                server_mastersHtml(client, &request, db);
            }
            else if (strncmp(request.uri, "/ScrumMasters/", 14) == 0)
            {
                server_mastersHtmlByID(client, &request, db);
            }
            else if (strcmp(request.uri, "/new-ScrumMaster") == 0)
            {
                server_mastersHtmlPOST(client, &request, db);
            }
            else
            {
                server_notFound(client);
            }
        }
    }

    db_free(db);
    socket_free(client);
    socket_free(server);
    lib_free();
    return 0;
}
コード例 #15
0
ファイル: m_readMsg.c プロジェクト: hengzhang/NEU_MSN
void initReadMsgList(void)
{
    readMsgList = db_new(NULL);
}
コード例 #16
0
ファイル: main.c プロジェクト: Zabrane/SPOCP
int
main(int argc, char **argv)
{
	int             debug = 0, conftest = 0, nodaemon = 0;
	int             i = 0;
	unsigned int    clilen;
	struct sockaddr_in cliaddr;
	struct timeval  start, end;
	char           *cnfg = DEF_CNFG;
	char		localhost[MAXNAMLEN + 1], path[MAXNAMLEN + 1];
	FILE           *pidfp;
	octet_t         oct;
	ruleset_t      *rs;

	/*
	 * Who am I running as ? 
	 */

	uname(&myname);

	/*
	 * spocp_err = 0 ;
	 */

	memset(&srv, 0, sizeof(srv_t));

	pthread_mutex_init(&(srv.mutex), NULL);
	pthread_mutex_init(&(srv.mlock), NULL);

	gethostname(localhost, MAXNAMLEN);
#ifdef HAVE_GETDOMAINNAME
	getdomainname(path, MAXNAMLEN);
#else
	{
		char *pos;
		if(pos = strstr(localhost, ".")) strncpy(path, pos+1, MAXNAMLEN);
		else strcpy(path, "");
	}
#endif

	if (0)
		printf("Domain: %s\n", path);

	srv.hostname = Strdup(localhost);

	/*
	 * truncating input strings to reasonable length
	 */
	for (i = 0; i < argc; i++)
		if (strlen(argv[i]) > 512)
			argv[i][512] = '\0';

	while ((i = getopt(argc, argv, "Dhrtf:d:")) != EOF) {
		switch (i) {

		case 'D':
			nodaemon = 1;
			break;

		case 'f':
			cnfg = Strdup(optarg);
			break;

		case 'd':
			debug = atoi(optarg);
			if (debug < 0)
				debug = 0;
			break;

		case 't':
			conftest = 1;
			break;

		case 'r':
			srv.readonly = 1;

		case 'h':
		default:
			fprintf(stderr, "Usage: %s [-t] ", argv[0]);
			fprintf(stderr, "[-f configfile] ");
			fprintf(stderr, "[-D] [-d debuglevel]\n");
			exit(0);
		}
	}

	srv.root = ruleset_new(0);

	if (srv_init(&srv, cnfg) < 0)
		exit(1);

	if (srv.port && srv.uds) {
		fprintf(stderr,
			"Sorry are not allowed to listen on both a unix domain socket and a port\n");
		exit(1);
	}

	if (srv.logfile)
		spocp_open_log(srv.logfile, debug);
	else if (debug)
		spocp_open_log(0, debug);

	if (srv.name){
		localcontext = (char *) Calloc(strlen(srv.name) + strlen("//") + 1,
				       sizeof(char));

		/* Flawfinder: ignore */
		sprintf(localcontext, "//%s", srv.name);		
	}
	else {
		localcontext = (char *) Calloc(strlen(localhost) + strlen("//") + 1,
				       sizeof(char));

		/* Flawfinder: ignore */
		sprintf(localcontext, "//%s", localhost);
	}

	/*
	 * where I put the access rules for access to this server and its
	 * rules 
	 */
	snprintf(path, MAXNAMLEN, "%s/server", localcontext);
	oct_assign(&oct, path);
	if ((rs = ruleset_create(&oct, srv.root)) == 0)
		exit(1);

	rs->db = db_new();

	/*
	 * access rules for operations 
	 */
	snprintf(path, MAXNAMLEN, "%s/operation", localcontext);
	oct_assign(&oct, path);
	if ((rs = ruleset_create(&oct, srv.root)) == 0)
		exit(1);

	rs->db = db_new();


	LOG(SPOCP_INFO) {
		traceLog(LOG_INFO, "Local context: \"%s\"", localcontext);
		traceLog(LOG_INFO, "initializing backends");
		if (srv.root->db)
			plugin_display(srv.plugin);
	}

	if (srv.plugin) {
		run_plugin_init(&srv);
	}

	if ( get_rules( &srv ) != SPOCP_SUCCESS ) 
		exit(1);

	/*ruleset_tree( srv.root, 0);*/

	/* If only testing configuration and rulefile this is as far as I go */
	if (conftest) {
		traceLog(LOG_INFO,"Configuration was OK");
		exit(0);
	}

	gettimeofday(&start, NULL);

	if (srv.port || srv.uds) {

		/*
		 * stdin and stdout will not be used from here on, close to
		 * save file descriptors 
		 */

		fclose(stdin);
		fclose(stdout);

#ifdef HAVE_SSL
		/*
		 * ---------------------------------------------------------- 
		 */
		/*
		 * build our SSL context, whether it will ever be used or not 
		 */

		/*
		 * mutex'es for openSSL to use 
		 */
		THREAD_setup();

		if (srv.certificateFile && srv.privateKey && srv.caList) {
			traceLog(LOG_INFO,"Initializing the TLS/SSL environment");
			if (!(srv.ctx = tls_init(&srv))) {
				return FALSE;
			}
		}

		/*
		 * ---------------------------------------------------------- 
		 */
#endif

#ifdef HAVE_SASL
		{
			int             r = sasl_server_init(sasl_cb, "spocp");
			if (r != SASL_OK) {
				traceLog( LOG_ERR,
				    "Unable to initialized SASL library: %s",
				     sasl_errstring(r, NULL, NULL));
				return FALSE;
			}
		}
#endif

		saci_init();
		if( nodaemon == 0 ) { 
#ifdef HAVE_DAEMON
			if (daemon(1, 1) < 0) {
				fprintf(stderr, "couldn't go daemon\n");
				exit(1);
			}
#else
			daemon_init("spocp", 0);
#endif
		}

		if (srv.pidfile) {
			/*
			 * Write the PID file. 
			 */
			pidfp = fopen(srv.pidfile, "w");

			if (pidfp == (FILE *) 0) {
				fprintf(stderr,
					"Couldn't open pidfile \"%s\"\n",
					srv.pidfile);
				exit(1);
			}
			fprintf(pidfp, "%d\n", (int) getpid());
			fclose(pidfp);
		}

		if (srv.port) {
			LOG(SPOCP_INFO) traceLog( LOG_INFO,
				"Asked to listen on port %d", srv.port);

			if ((srv.listen_fd =
			     spocp_stream_socket(srv.port)) < 0)
				exit(1);

			srv.id = (char *) Malloc(16);
			sprintf(srv.id, "spocp-%d", srv.port);

			srv.type = AF_INET;
		} else {
			LOG(SPOCP_INFO)
			    traceLog(LOG_INFO,"Asked to listen on unix domain socket");
			if ((srv.listen_fd =
			     spocp_unix_domain_socket(srv.uds)) < 0)
				exit(1);

			srv.id = (char *) Malloc(7 + strlen(srv.uds));
			/* Flawfinder: ignore */
			sprintf(srv.id, "spocp-%s", srv.uds);

			srv.type = AF_UNIX;
		}

		xsignal(SIGCHLD, sig_chld);
		xsignal(SIGPIPE, sig_pipe);
		xsignal(SIGINT, sig_int);
		xsignal(SIGTERM, sig_term);
		xsignal(SIGUSR1, sig_usr1);

		clilen = sizeof(cliaddr);

		DEBUG(SPOCP_DSRV) traceLog(LOG_DEBUG,"Creating threads");
		/*
		 * returns the pool the threads are picking work from 
		 */
		srv.work = tpool_init(srv.threads, 64, 1);

		spocp_srv_run(&srv);

	} else {
		conn_t         *conn;

		saci_init();
		DEBUG(SPOCP_DSRV) traceLog(LOG_DEBUG,"---->");

		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Reading STDIN");

		/*
		 * If I want to use this I have to do init_server() first
		 * conn = spocp_open_connection( STDIN_FILENO, &srv ) ; 
		 */
		/*
		 * this is much simpler 
		 */
		conn = conn_new();
		conn_setup(conn, &srv, STDIN_FILENO, "localhost", "127.0.0.1");

		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Running server");

		spocp_server((void *) conn);

		gettimeofday(&end, NULL);

		print_elapsed("query time:", start, end);

		conn_free( conn );
	}

	srv_free( &srv );
	if (cnfg != DEF_CNFG)
		Free( cnfg );

	exit(0);
}
コード例 #17
0
ファイル: nodau.c プロジェクト: carnil/nodau
int main(int argc, char** argv)
{
	char* args;
	/* no option, print usage */
	if (argc < 2) {
		usage();
		return 0;
	}

	config_load();

	/* connect to the db or error */
	if (db_connect()) {
		fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return 0;
	}

	/* compile the arguments */
	args = get_args(argc,argv);

	/* if listing notes */
	if (strcmp(argv[1],"list") == 0) {
		db_list(args);
	}else{
		/* if null argument print usage */
		if (args == NULL || argc <3) {
			usage();
		/* if creating a new note */
		}else if (strcmp(argv[1],"new") == 0 || strcmp(argv[1],"create") == 0) {
			db_new(args);
		/* if opening/editing an existing note */
		}else if (strcmp(argv[1],"open") == 0 || strcmp(argv[1],"edit") == 0) {
			db_edit(args);
		/* append to a note if data is on stdin */
		}else if (strcmp(argv[1],"append") == 0) {
			if (isatty(STDIN_FILENO)) {
				db_edit(args);
			}else{
				db_append(args);
			}
		/* encrypt a new or existing note */
		}else if (strcmp(argv[1],"encrypt") == 0) {
			db_encrypt(args);
		/* decrypt an existing note */
		}else if (strcmp(argv[1],"decrypt") == 0) {
			db_decrypt(args);
		/* display an existing note */
		}else if (strcmp(argv[1],"show") == 0) {
			db_show(args);
		/* if deleting note/s */
		}else if (strcmp(argv[1],"del") == 0) {
			db_del(args);
		/* unknown option, print usage */
		}else{
			usage();
		}
	}

	/* free args if we can */
	if (args != NULL)
		free(args);

	/* close the database */
	sqlite3_close(db);

	/* save config */
	config_save();

	return 0;
}
コード例 #18
0
ファイル: app.c プロジェクト: vovach777/shipDB
void process_commands(enum CID cid) {
    cursor_t old_c;
    char * dbName;
    switch (cid) {
        case NOPE:
              puts("-- команда не распознана --");
              break;
        case SET_NAME:              
              if (db_ship()) {
                printf("Имя>");
                strncpy(db_ship()->name,input_str(),64);
                show();
          }
            break;
        case SET_YEAR:
              if (db_ship()) {
                printf("Год>");
                db_ship()->year = strtoul( input_str(),NULL, 10);
                show();
          }
            break;
        case COPY:
             db_copy();
             break;
        case PASTE:
             db_paste();
             show();
             break;
        case ALL:
             old_c = db_get_cursor();
             db_first();             
             while (db_get_cursor() != db_get_end()) {
                 db_load();
                 if (!db_is_deleted())
                    show();
                 db_next();
             }
             db_set_cursor(old_c);
             db_load();
             break;
        case REFRESH:
             db_load();
        case SHOW:
            show();
            break;

        case NEW:
             db_new();
             show();            
             break;
        case REMOVE:
                db_delete();        
                break;
        case SAVE:
              db_save();
             break; 

        case HELP:
              show_help();
              break;
        case OPEN:        
                printf("Файл>");
                dbName = input_str();
                db_open( strlen(dbName) == 0 ?  "ships.db" : dbName);
                break;
        case CLOSE:
                db_close();
                break;
        case  FIRST:
                first:
                db_first();
                while (db_get_cursor() != db_get_end()) {                   
                   db_load();
                   if (!db_is_deleted()) {
                       show();
                       return;
                   }                   
                   db_next();
                }
                puts("-- в базе нет записей. --");                
                break;
        case  NEXT: 
                db_next();
                while (db_get_cursor() != db_get_end()) {
                    db_load();
                    if (!db_is_deleted()) {
                       show();
                       return;
                   }
                   db_next();
                }
                puts("-- больше записей нет. перемотка в начало. --");
                goto first;                 
        case PREV:              
                while (db_get_cursor() != db_get_begin()) {
                   db_prev();
                   db_load();
                   if (!db_is_deleted()) {
                       show();
                       return;
                   }
                }
                puts("-- первая запись --");                
                goto first;             
                break;
        default:
            puts("== команда не обработана ==");

    }    
}
コード例 #19
0
ファイル: config.c プロジェクト: Zabrane/SPOCP
int
read_config(char *file, srv_t * srv)
{
	FILE           *fp;
	char            s[LINEBUF], *cp, *sp, pluginname[256];
	char            section = 0, *dbname = 0, *dbload = 0;
	unsigned int    n = 0;
	long            lval;
	int             i;
	plugin_t       *plugins, *pl = 0;
	dback_t        *dbp = 0;
	const conf_com_t *ccp;
	spocp_result_t  r;

	/*
	 * should never be necessary 

	if (!srv->root)
		srv->root = ruleset_new(0);
	 */

	if (!srv->root->db)
		srv->root->db = db_new();

	plugins = srv->plugin;

	if ((fp = fopen(file, "r")) == NULL) {
		traceLog(LOG_ERR,
		    "Could not find or open the configuration file \"%s\"", file);
		return 0;
	}

	while (fgets(s, LINEBUF, fp)) {
		n++;
		rmcrlf(s);

		if (*s == 0 || *s == '#')
			continue;

		/*
		 * New section 
		 */
		if (*s == '[') {

			cp = find_balancing(s + 1, '[', ']');
			if (cp == 0) {
				traceLog(LOG_ERR, err_msg, n, "Section specification");
				return 0;
			}

			*cp = 0;
			sp = s + 1;

			if (strcasecmp(sp, "server") == 0)
				section = SYSTEM;
			else if (strcasecmp(sp, "dback") == 0)
				section = DBACK;
			else {
				section = PLUGIN;
				strlcpy(pluginname, sp, sizeof( pluginname));
				pl = 0;
			}

			continue;
		}

		/*
		 * Within a section The directives are of the form: 
		 * key *SP * "=" *SP val *(*SP val)
		 * val = 1*nonspacechar / '"' char '"' 
		 */

		rm_lt_sp(s, 1);	/* remove leading and trailing blanks */

		/*
		 * empty line or comment 
		 */
		if (*s == 0 || *s == '#')
			continue;

		cp = strchr(s, '=');
		if (cp == 0) {
			traceLog(LOG_ERR, err_msg, n, "syntax error");
			continue;
		}

		sp = cp;
		for (*cp++ = '\0'; *cp && (*cp == ' ' || *cp == '\t'); cp++)
			*cp = '\0';
		for (sp--; sp >= s && (*sp == ' ' || *sp == '\t'); sp--)
			*sp = '\0';

		/*
		 * no key, not good 
		 */
		if (*s == '\0')
			continue;

		switch (section) {
		case SYSTEM:
			for (i = 1; keyword[i]; i++)
				if (strcasecmp(keyword[i], s) == 0)
					break;

			if (keyword[i] == 0) {
#ifdef HAVE_SASL
				if((strncmp("sasl_", s, 5) == 0))
					add_overflow_directive(s, cp);
				else
#endif
				traceLog(LOG_ERR, err_msg, n, "Unknown keyword");
				continue;
			}

			switch (i) {
			case RULEFILE:
				if (srv->rulefile)
					free(srv->rulefile);
				srv->rulefile = Strdup(cp);
				break;

			case CERTIFICATE:
				if (srv->certificateFile)
					free(srv->certificateFile);
				srv->certificateFile = Strdup(cp);
				break;

			case PRIVATEKEY:
				if (srv->privateKey)
					free(srv->privateKey);
				srv->privateKey = Strdup(cp);
				break;

			case CALIST:
				if (srv->caList)
					free(srv->caList);
				srv->caList = Strdup(cp);
				break;

			case DHFILE:
				if (srv->dhFile)
					free(srv->dhFile);
				srv->dhFile = Strdup(cp);
				break;

			case ENTROPYFILE:
				if (srv->SslEntropyFile)
					free(srv->SslEntropyFile);
				srv->SslEntropyFile = Strdup(cp);
				break;

			case PASSWD:
				if (srv->passwd)
					free(srv->passwd);
				srv->passwd = Strdup(cp);
				break;

			case LOGGING:
				if (srv->logfile)
					free(srv->logfile);
				srv->logfile = Strdup(cp);
				break;

			case TIMEOUT:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval >= 0 && lval <= YEAR)
						srv->timeout =
						    (unsigned int) lval;
					else {
						traceLog(LOG_ERR, err_msg, n,
							 "Value out of range");
						srv->timeout = DEFAULT_TIMEOUT;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
					srv->timeout = DEFAULT_TIMEOUT;
				}

				break;

			case UNIXDOMAINSOCKET:
				if (srv->uds)
					free(srv->uds);
				srv->uds = Strdup(cp);
				break;

			case PORT:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L && lval < 65536) {
						srv->port =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Number out of range");
						srv->port = DEFAULT_PORT;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

			case NTHREADS:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval <= 0) {
						traceLog(LOG_ERR, err_msg, n,
							 "Value out of range");
						return 0;
					} else {
						int             level =
						    (int) lval;

						srv->threads = level;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric specification");
					return 0;
				}
				break;

			case SSLVERIFYDEPTH:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L) {
						srv->sslverifydepth =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "number out of range");
						srv->sslverifydepth = 0;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

			case PIDFILE:
				if (srv->pidfile)
					Free(srv->pidfile);
				srv->pidfile = Strdup(cp);
				break;

			case MAXCONN:
				if (numstr(cp, &lval) == SPOCP_SUCCESS) {
					if (lval > 0L) {
						srv->nconn =
						    (unsigned int) lval;
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Number out of range");
						srv->sslverifydepth = 0;
					}
				} else {
					traceLog(LOG_ERR, err_msg, n,
						 "Non numeric value");
				}
				break;

#ifdef HAVE_SSL
			case CLIENTCERT:
				if (strcasecmp(cp, "none") == 0)
					srv->clientcert = NONE;
				else if (strcasecmp(cp, "demand") == 0)
					srv->clientcert = DEMAND;
				else if (strcasecmp(cp, "hard") == 0)
					srv->clientcert = HARD;

				break;
#endif
			case NAME:
				if (srv->name)
					Free(srv->name);
				srv->name = Strdup(cp);
				break;
			}
			break;

		case PLUGIN:
			if (pl == 0) {
				if (strcmp(s, "load") != 0) {
					traceLog(LOG_ERR, err_msg, n,
						 "First directive in plugin sector has to be \"load\"");
					section = 0;
				}

				if ((pl =
				     plugin_load(plugins, pluginname,
						 cp)) == 0)
					section = 0;
				else {
					/*
					 * The last one is placed last 
					 */
					for (; pl->next; pl = pl->next);
				}

				if (plugins == 0)
					plugins = pl;
			} else {
				if (strcmp(s, "poolsize") == 0) {
					if (numstr(cp, &lval) == SPOCP_SUCCESS) {
						if (lval <= 0) {
							traceLog(LOG_ERR, err_msg, n,
								 "Value out of range");
						} else {
							int             level =
							    (int) lval;

							if (pl->dyn == 0)
								pl->dyn =
								    pdyn_new
								    (level);
							if (pl->dyn->size == 0)
								pl->dyn->size =
								    level;
						}
					} else {
						traceLog(LOG_ERR, err_msg, n,
							 "Non numeric specification");
					}
				} else if (strcmp(s, "cachetime") == 0) {
					if (plugin_add_cachedef(pl, cp) == FALSE )
						traceLog(LOG_ERR, err_msg, n,
							 "Cachetime def");
				} else if (pl->ccmds == 0) {	/* No
								 * directives
								 * allowed */
					traceLog(LOG_ERR, err_msg, n,
						 "Directive where there should not be one");
				} else {
					for (ccp = pl->ccmds; ccp; ccp++) {
						int np=0, j;
						char **arr;

						arr = strchop(cp,&np);

						for (j=0; j<np; j++)
							traceLog(LOG_ERR, "%s:%s",
							    cp, arr[j]);

						if (strcmp(ccp->name, s) == 0) {
							r = ccp->func(&pl->
								      conf,
								      ccp->
								      cmd_data,
								      np, arr);
							if (r != SPOCP_SUCCESS) {
								traceLog
								    (LOG_ERR, err_msg,
								     n,
								     ccp->
								     errmsg);
							}
							charmatrix_free( arr );
							break;
						}
					}
					if (ccp == 0) {
						traceLog(LOG_ERR,err_msg, n,
							 "Unknown directive");
					}
				}
			}
			break;

		case DBACK:
			if (dbp == 0) {
				if (strcmp(s, "name") == 0) {
					dbname = Strdup(cp);
					if (dbname && dbload) {
						dbp =
						    dback_load(dbname, dbload);
						free(dbname);
						free(dbload);
					}
				} else if (strcmp(s, "load") == 0) {
					dbload = Strdup(cp);
					if (dbname && dbload) {
						dbp =
						    dback_load(dbname, dbload);
						free(dbname);
						free(dbload);
					}
				} else
					traceLog(LOG_ERR,err_msg, n,
						 "Unknown directive");
			} else {
				for (ccp = dbp->ccmds; ccp && *ccp->name;
				     ccp++) {
					if (strcmp(ccp->name, s) == 0) {
						r = ccp->func(&dbp->conf,
							      ccp->cmd_data, 1,
							      &cp);
						if (r != SPOCP_SUCCESS) {
							traceLog(LOG_ERR,err_msg, n,
								 ccp->errmsg);
						}
						break;
					}
				}
				if (ccp == 0) {
					traceLog(LOG_ERR,err_msg, n,
						 "Unknown directive");
				}
			}
			break;
		}
	}

	fclose(fp);

	if (srv->pidfile == 0)
		srv->pidfile = Strdup("spocd.pid");
	if (srv->timeout == 0)
		srv->timeout = DEFAULT_TIMEOUT;
	if (srv->threads == 0)
		srv->threads = DEFAULT_NTHREADS;
	if (srv->sslverifydepth == 0)
		srv->sslverifydepth = DEFAULT_SSL_DEPTH;

	srv->plugin = plugins;
	srv->dback = dbp;

	return 1;
}
コード例 #20
0
ファイル: read.c プロジェクト: Zabrane/SPOCP
int
read_rules(srv_t * srv, char *file, dbcmd_t * dbc)
{
	FILE           *fp;
	char           *sp, *tmp;
	int             n = 0, f = 0, r;
	octet_t         *op;
	octarr_t       *oa = 0;
	ruleset_t      *rs = 0, *trs, *prs;
	spocp_result_t  rc = SPOCP_SUCCESS;
	spocp_charbuf_t	*buf;
	spocp_chunk_t	*chunk = 0, *ck;
	spocp_chunkwrap_t   *cw;
	spocp_ruledef_t	rdef;
	struct stat	statbuf;

	if ((fp = fopen(file, "r")) == 0) {
		LOG(SPOCP_EMERG) traceLog(LOG_ERR,"couldn't open rule file \"%s\"",
					  file);
		op = oct_new( 256, NULL);
		sp = getcwd(op->val, op->size);
		traceLog(LOG_ERR,"I'm in \"%s\"", sp);
		oct_free(op);
		return -1;
	}

	stat( file, &statbuf);

	srv->mtime = statbuf.st_mtime;
 
	/*
	 * The default ruleset should already be set 
	 */

	if (srv->root == 0) {
		srv->root = rs = ruleset_new(0);
	} else
		rs = srv->root;

	if (rs->db == 0)
		rs->db = db_new();

	buf = charbuf_new( fp, BUFSIZ );

	if (get_more(buf) == 0) return 0;

	/*
	 * have to escape CR since fgets stops reading when it hits a newline
	 * NUL also has to be escaped since I have problem otherwise finding
	 * the length of the 'string'. '\' hex hex is probably going to be the 
	 * choice 
	 */
	while (rc == SPOCP_SUCCESS ) {
	    cw = get_object( buf, 0 );
	    if (cw->status == 0) {
	        Free(cw);
	        break;
	    }
	    else if (cw->status == -1) {
	        rc = SPOCP_LOCAL_ERROR;
            Free(cw);
            break;
        }
        else {
            chunk = cw->chunk;
            Free(cw);
        }
	    
		if (oct2strcmp(chunk->val, ";include ") == 0) {	/* include
								 * file */
			ck = chunk->next;
			tmp = oct2strdup( ck->val, 0 ) ;
			LOG(SPOCP_DEBUG) traceLog(LOG_DEBUG,"include directive \"%s\"",
						  tmp);
			if ((rc = read_rules(srv, tmp, dbc)) < 0) {
				traceLog(LOG_ERR,"Include problem");
			}
		}
		else if (*chunk->val->val == '/' || *chunk->val->val == '(') {
			trs = rs;
			if (*chunk->val->val == '/') {
#ifdef AVLUS
				oct_print(LOG_INFO,"ruleset", chunk->val);
#endif
				if ((trs = ruleset_find( chunk->val, rs)) == NULL) {
					octet_t oct;

					octln( &oct, chunk->val);
					rs = ruleset_create(chunk->val, rs);
					trs = ruleset_find(&oct, rs);
					trs->db = db_new();
				}

				ck = chunk->next;
			}
			else {
				ck = chunk;
			}

			ruledef_return( &rdef, ck ) ;
			if( rdef.rule ) {
				op = chunk2sexp( rdef.rule ) ;
				oa = octarr_add(oa, op) ;
				LOG(SPOCP_DEBUG) {
					traceLog(LOG_DEBUG,"We've got a rule");
				}
			}
			
			if( rdef.bcond) {
				op = chunk2sexp( rdef.bcond ) ;
				oa = octarr_add(oa, op) ;
				LOG(SPOCP_DEBUG) {
					traceLog(LOG_DEBUG,"We've got a boundary condition");
				}
			}