예제 #1
0
파일: hlog.c 프로젝트: hessu/aprsc
int rotate_log(void)
{
    char *tmp;
    int i;
    char *r1, *r2;

    if (rwl_trywrlock(&log_file_lock)) {
        fprintf(stderr, "failed to wrlock log_file_lock for rotation\n");
        return 0;
    }

    // check if still oversize and not rotated by another thread
    off_t l = lseek(log_file, 0, SEEK_CUR);
    if (l < log_rotate_size) {
        rwl_wrunlock(&log_file_lock);
        return 0;
    }

    // rename
    tmp = hmalloc(strlen(log_fname) + 6);
    sprintf(tmp, "%s.tmp", log_fname);
    if (rename(log_fname, tmp) != 0) {
        fprintf(stderr, "aprsc logger: Failed to rename %s to %s: %s\n", log_fname, tmp, strerror(errno));
        // continue anyway, try to reopen
    }

    // reopen
    if (close(log_file))
        fprintf(stderr, "aprsc logger: Could not close log file %s: %s\n", log_fname, strerror(errno));

    log_file = open(log_fname, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP);
    if (log_file < 0) {
        fprintf(stderr, "aprsc logger: Could not open %s: %s\n", log_fname, strerror(errno));
        log_file = -1;
    }

    rwl_wrunlock(&log_file_lock);

    // do the rest of the rotation
    r1 = hmalloc(strlen(log_fname) + 16);
    r2 = hmalloc(strlen(log_fname) + 16);

    for (i = log_rotate_num-1; i > 0; i--) {
        sprintf(r1, "%s.%d", log_fname, i-1);
        sprintf(r2, "%s.%d", log_fname, i);
        if (rename(r1, r2) != 0 && errno != ENOENT) {
            fprintf(stderr, "rename %s => %s failed:%s\n", r1, r2, strerror(errno));
        }
    }

    if (rename(tmp, r1) != 0) {
        fprintf(stderr, "aprsc logger: Failed to rename %s to %s: %s\n", tmp, r1, strerror(errno));
    }

    hfree(tmp);
    hfree(r1);
    hfree(r2);

    return 0;
}
예제 #2
0
파일: counterdata.c 프로젝트: snip/aprsc
struct cdata_t *cdata_alloc(const char *name)
{
    int e;
    struct cdata_t *cd;

    cd = hmalloc(sizeof(*cd));
    memset(cd, 0, sizeof(*cd));

    pthread_mutex_init(&cd->mt, NULL);
    cd->name = hstrdup(name);
    cd->last_index = -1; // no data inserted yet
    cd->is_gauge = 0;

    if ((e = pthread_mutex_lock(&counterdata_mt))) {
        hlog(LOG_CRIT, "cdata_allocate: failed to lock counterdata_mt: %s", strerror(e));
        exit(1);
    }

    cd->next = counterdata;
    if (counterdata)
        counterdata->prevp = &cd->next;
    counterdata = cd;
    cd->prevp = &counterdata;

    if ((e = pthread_mutex_unlock(&counterdata_mt))) {
        hlog(LOG_CRIT, "cdata_allocate: could not unlock counterdata_mt: %s", strerror(e));
        exit(1);
    }

    //hlog(LOG_DEBUG, "cdata: allocated: %s", cd->name);

    return cd;
}
예제 #3
0
static int *accept_rx_err_map(cJSON *rx_err_labels, int *old_rxerrs_len)
{
	int *rxerr_map = NULL;
	int i, j;

	*old_rxerrs_len = cJSON_GetArraySize(rx_err_labels);
	
	if (*old_rxerrs_len > 0) {
		rxerr_map = hmalloc(sizeof(*rxerr_map) * *old_rxerrs_len);
		for (i = 0; i < *old_rxerrs_len; i++) {
			rxerr_map[i] = -1; // default: no mapping
			
			cJSON *rxerr = cJSON_GetArrayItem(rx_err_labels, i);
			if (!rxerr || rxerr->type != cJSON_String)
				continue;
			
			for (j = 0; j < INERR_BUCKETS; j++) {
				if (strcmp(inerr_labels[j], rxerr->valuestring) == 0) {
					hlog(LOG_DEBUG, "Mapped old rxerr index %d with new index %d: %s", i, j, rxerr->valuestring);
					rxerr_map[i] = j;
				}
			}
		}
	}
	
	return rxerr_map;
}
예제 #4
0
파일: clientlist.c 프로젝트: oh2mqk/aprsc
int clientlist_add(struct client_t *c)
{
	struct clientlist_t *cl;
	int old_fd;
	
	/* allocate and fill in */
	cl = hmalloc(sizeof(*cl));
	strncpy(cl->username, c->username, sizeof(cl->username));
	cl->username[sizeof(cl->username)-1] = 0;
	cl->validated = c->validated;
	cl->fd = c->fd;
	
	/* get lock for list and insert */
	rwl_wrlock(&clientlist_lock);
	
	old_fd = check_if_validated_client(c->username, strlen(c->username));
	
	if (clientlist)
		clientlist->prevp = &cl->next;
	cl->next = clientlist;
	cl->prevp = &clientlist;
	cl->client_id = (void *)c;
	clientlist = cl;
	rwl_wrunlock(&clientlist_lock);
	
	return old_fd;
}
예제 #5
0
파일: cfg.c 프로젝트: FlavioFalcao/gnuais
int do_uplink(struct uplink_config_t **lq, int argc, char **argv)
{
	struct uplink_config_t *l;
	int uplink_proto = 0;
	
	if (argc < 3)
		return -1;
	
	if (strcasecmp(argv[2], "json") == 0) {
		uplink_proto = UPLINK_JSON;
	} else {
		hlog(LOG_ERR, "Uplink: Unsupported uplink protocol '%s'\n", argv[2]);
		return -2;
	}
	
	l = hmalloc(sizeof(*l));

	l->proto = uplink_proto;
	l->name  = hstrdup(argv[1]);
	l->url = hstrdup(argv[3]);

	/* put in the list */
	l->next = *lq;
	if (l->next)
		l->next->prevp = &l->next;
	*lq = l;
	
	return 0;
}
예제 #6
0
파일: ssl.c 프로젝트: N0NB/aprx
struct ssl_t *ssl_alloc(void)
{
	struct ssl_t *ssl;
	
	ssl = hmalloc(sizeof(*ssl));
	memset(ssl, 0, sizeof(*ssl));
	
	return ssl;
}
예제 #7
0
static struct listen_t *listener_alloc(void)
{
	struct listen_t *l = hmalloc(sizeof(*l));
	memset( l, 0, sizeof(*l) );
	l->fd = -1;
	l->id = -1;
	l->listener_id = -1;
	
	return l;
}
예제 #8
0
파일: hlog.c 프로젝트: hessu/aprsc
int open_log(char *name, int reopen)
{
    if (!reopen)
        rwl_wrlock(&log_file_lock);

    if (log_name)
        hfree(log_name);

    if (!(log_name = hstrdup(name))) {
        fprintf(stderr, "aprsc logger: out of memory!\n");
        exit(1);
    }

    if (log_basename)
        hfree(log_basename);

    log_basename = hmalloc(strlen(log_name) + 5);
    sprintf(log_basename, "%s.log", log_name);

    if (log_dest == L_SYSLOG)
        openlog(name, LOG_NDELAY|LOG_PID, log_facility);

    if (log_dest == L_FILE) {
        if (log_fname)
            hfree(log_fname);

        log_fname = hmalloc(strlen(log_dir) + strlen(log_basename) + 2);
        sprintf(log_fname, "%s/%s", log_dir, log_basename);

        log_file = open(log_fname, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP);
        if (log_file < 0) {
            fprintf(stderr, "aprsc logger: Could not open %s: %s\n", log_fname, strerror(errno));
            exit(1);
        }
    }

    rwl_wrunlock(&log_file_lock);

    if (log_dest == L_FILE)
        hlog(LOG_DEBUG, "Log file %s %sopened on fd %d", log_fname, (reopen) ? "re" : "", log_file);

    return 0;
}
예제 #9
0
파일: status.c 프로젝트: HamWAN/aprsc
void status_init(void)
{
	int i;
	char *n;
	
	static const char *cdata_start[][3] = {
		{ "totals", "clients", "g" },
		{ "totals", "connects", "c" },
		{ "totals", "tcp_bytes_rx", "c" },
		{ "totals", "tcp_bytes_tx", "c" },
		{ "totals", "udp_bytes_rx", "c" },
		{ "totals", "udp_bytes_tx", "c" },
		{ "totals", "tcp_pkts_rx", "c" },
		{ "totals", "tcp_pkts_tx", "c" },
		{ "totals", "udp_pkts_rx", "c" },
		{ "totals", "udp_pkts_tx", "c" }, 
#ifdef USE_SCTP		
		{ "totals", "sctp_bytes_rx", "c" },
		{ "totals", "sctp_bytes_tx", "c" },
		{ "totals", "sctp_pkts_rx", "c" },
		{ "totals", "sctp_pkts_tx", "c" }, 
#endif
		{ "dupecheck", "dupes_dropped", "c" },
		{ "dupecheck", "uniques_out", "c" },
		{ NULL, NULL }
	};
	
	i = 0;
	while (cdata_start[i][0] != NULL) {
		n = hmalloc(strlen(cdata_start[i][0]) + 1 + strlen(cdata_start[i][1]) + 1);
		sprintf(n, "%s.%s", cdata_start[i][0], cdata_start[i][1]);
		struct cdata_list_t *cl = hmalloc(sizeof(*cl));
		cl->tree = cdata_start[i][0];
		cl->name = cdata_start[i][1];
		cl->next = cdata_list;
		cl->cd = cdata_alloc(n);
		hfree(n);
		cl->gauge = cdata_start[i][2][0] == 'g' ? 1 : 0;
		cdata_list = cl;
		i++;
	}
}
예제 #10
0
int initSoundDecoder(int buf_len,int _time_print_stats) 
{
	sound_channels=SOUND_CHANNELS_STEREO;
	channels = sound_channels == SOUND_CHANNELS_MONO ? 1 : 2;
	time_print_stats=_time_print_stats;
	tprev=time(NULL); // for decoder statistics
    tprev_ppm=time(NULL); 
    buffer = (short *) hmalloc(channels*sizeof(short)*buf_len);
    rx_a = init_receiver('A', 2, 0);
    rx_b = init_receiver('B', 2, 1);
    return 1;
}
예제 #11
0
파일: serial.c 프로젝트: rubund/gnuais
struct serial_state_t *serial_init()
{
    struct serial_state_t *state = NULL;

    state = (struct serial_state_t *) hmalloc(sizeof(*state));

    //Returns the file descriptor on success or -1 on error.
    /* File descriptor for the port */
    state->fd = open(serial_port, O_RDWR | O_NOCTTY | O_NDELAY);
    if (state->fd == -1) {	// Could not open the port.
        hlog(LOG_CRIT, "Could not open serial port %s: %s",
             serial_port, strerror(errno));
        return NULL;
    }

    hlog(LOG_INFO, "Opened serial port %s for NMEA output", serial_port);

    /* set file status flags to 0 - why? */
    fcntl(state->fd, F_SETFL, 0);

    struct termios options;
    /* get the current options */
    if (tcgetattr(state->fd, &options))
        hlog(LOG_ERR,
             "Could not read serial port parameters on port %s: %s",
             serial_port, strerror(errno));

    //set speed 4800
    cfsetispeed(&options, B4800);
    cfsetospeed(&options, B4800);

    /* set raw input, 1 second timeout */
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;
    options.c_cc[VMIN] = 0;
    options.c_cc[VTIME] = 10;

    //No parity 8N1
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;

    /* set the options */
    if (tcsetattr(state->fd, TCSANOW, &options))
        hlog(LOG_ERR,
             "Could not configure serial port parameters on port %s: %s",
             serial_port, strerror(errno));

    return state;
}
예제 #12
0
int main (){
 void *abc = hmalloc (sizeof(int));
 int *count = (int *)((int *)abc -1); 
 printf ("%d\n", *count);
   __assert (*count== 0);
   (*count)++;
   int *count1 = (int *)((int *)abc-1);
   __assert(*count1 == 1);
   printf ("%d\n", *count1);
 hfree (abc);
 printf("success\n");
 return 0;
}
예제 #13
0
파일: heap.c 프로젝트: kellyawang/heap
/*
 * hrealloc(p,size)
 * Re-allocate memory pointed to by p to be at least size.
 * No guarantees about optimality.
 */
void *hrealloc(void *p, int size)
{
  init();
  chunk *c = (chunk*)PTR_ADD(p,-H_IS);
  if (ck_payloadSize(c) < size) {
    void *q = hmalloc(size);
    memcpy(q,p,size);
    hfree(p);
    return q;
  } else {
    return p;
  }
} 
예제 #14
0
struct receiver *init_receiver(char name, int num_ch, int ch_ofs)
{
	struct receiver *rx;

	rx = (struct receiver *) hmalloc(sizeof(struct receiver));
	memset(rx, 0, sizeof(struct receiver));

	rx->filter = filter_init(COEFFS_L, coeffs);

    rx->decoder = hmalloc(sizeof(struct demod_state_t));
	protodec_initialize(rx->decoder, NULL, name);

    rx->name = name;
	rx->lastbit = 0;
	rx->num_ch = num_ch;
	rx->ch_ofs = ch_ofs;
	rx->pll = 0;
	rx->pllinc = 0x10000 / 5;
	rx->prev = 0;
	rx->last_levellog = 0;

	return rx;
}
예제 #15
0
파일: status.c 프로젝트: HamWAN/aprsc
char *hex_encode(const char *buf, int len)
{
	static const char *lut = "0123456789abcdef";
	int i;
	char *s = hmalloc(len*2+1);
	
	for (i = 0; i < len; i++) {
		const char c = buf[i];
		s[i*2] = lut[c >> 4];
		s[i*2+1] = lut[c & 15];
	}
	s[i*2] = 0;
	
	return s;
}
예제 #16
0
파일: ssl.c 프로젝트: N0NB/aprx
static int ssl_thread_setup(void)
{
	int i;
	
	hlog(LOG_DEBUG, "Creating OpenSSL mutexes (%d)...", CRYPTO_num_locks());
	
	mutex_buf = hmalloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
	
	for (i = 0;  i < CRYPTO_num_locks();  i++)
		MUTEX_SETUP(mutex_buf[i]);
	
	CRYPTO_set_id_callback(ssl_thread_id_function);
	CRYPTO_set_locking_callback(ssl_thread_locking_function);
	
	return 0;
}
예제 #17
0
파일: Panel.cpp 프로젝트: mymy49/lss
void Panel::doIncreaseObjArr(void)
{
	unsigned short i;
	ObjSys** temp;

	temp = (ObjSys**)hmalloc(sizeof(ObjSys*)*(mMaxObj+8));

	if(mMaxObj)
	{
		for(i=0;i<mMaxObj;i++)
			temp[i] = mObjArr[i];

		hfree(mObjArr);
	}
	mMaxObj += 8;
	mObjArr = temp;
}
예제 #18
0
파일: status.c 프로젝트: HamWAN/aprsc
struct status_error_t *status_error_find(const char *err)
{
	struct status_error_t *e;
	
	for (e = status_errs; (e); e = e->next) {
		if (strcmp(e->err, err) == 0)
			return e;
	}
	
	e = hmalloc(sizeof(*e));
	e->err = hstrdup(err);
	e->next = status_errs;
	e->set = -1;
	status_errs = e;
	
	return e;
}
예제 #19
0
파일: http.c 프로젝트: snip/aprsc
static void http_send_reply_ok(struct evhttp_request *r, struct evkeyvalq *headers, char *data, int len, int allow_compress)
{
#ifdef HAVE_LIBZ
	char *compr = NULL;
	
	/* Gzipping files below 150 bytes can actually make them larger. */
	if (len > 150 && allow_compress) {
		/* Consider returning a compressed version */
		int compr_type = http_check_req_compressed(r);
		/*
		if (compr_type)
			hlog(LOG_DEBUG, "http_send_reply_ok, client supports transfer-encoding: %s", compr_type_strings[compr_type]);
		*/
		
		if (compr_type == HTTP_COMPR_GZIP) {
			/* for small files it's possible that the output is actually
			 * larger than the input
			 */
			int oblen = len + 60;
			compr = hmalloc(oblen);
			int olen = http_compress_gzip(data, len, compr, oblen);
			/* If compression succeeded, replace buffer with the compressed one and free the
			 * uncompressed one. Add HTTP header to indicate compressed response.
			 * If the file got larger, send uncompressed.
			 */
			if (olen > 0 && olen < len) {
				data = compr;
				len = olen;
				evhttp_add_header(headers, "Content-Encoding", "gzip");
			}
		}
	}
#endif
	
	struct evbuffer *buffer = evbuffer_new();
	evbuffer_add(buffer, data, len);
	
	evhttp_send_reply(r, HTTP_OK, "OK", buffer);
	evbuffer_free(buffer);

#ifdef HAVE_LIBZ
	if (compr)
		hfree(compr);
#endif
}
예제 #20
0
spkey_t symbol_db_mem(const void *s, int slen, struct sptree *spt)
{
	register spkey_t key;
	register struct syment *se, *pe;
	struct spblk *spl;

	if (s == NULL)
		return 0;

	key = crc32n(s,slen);

	/* Ok, time for the hard work.  Lets see if we have this key
	   in the symtab splay tree */

	pe = NULL;
	spl = sp_lookup(key, spt);
	if (spl != NULL) {
		/* Got it !  Now see that we really have it, and
		   not only have a hash collision */

		se = (struct syment *)spl->data;
		do {
			if (se->namelen == slen &&
			    memcmp(se->name, s, slen) == 0) {
				/* Really found it! */
				return (spkey_t)se;
			}
			pe = se;
			se = se->next;
		} while (se != NULL);
	}
	se = (struct syment *)hmalloc(sizeof (struct syment) + slen);
	memcpy((void*)se->name, s, slen);
	((char*)se->name)[slen] = 0;
	se->namelen = slen;
	se->next    = NULL;
	if (pe != NULL)
		pe->next = se;
	else {
		spl = sp_install(key, spt);
		spl->data = (void *)se;
	}
	return (spkey_t)se;
}
예제 #21
0
파일: ssl.c 프로젝트: N0NB/aprx
int ssl_create_connection(struct ssl_t *ssl, struct client_t *c, int i_am_client)
{
	struct ssl_connection_t  *sc;
	
	sc = hmalloc(sizeof(*sc));
	sc->connection = SSL_new(ssl->ctx);
	
	if (sc->connection == NULL) {
		ssl_error(LOG_ERR, "SSL_new failed");
		hfree(sc);
		return -1;
	}
	
	if (SSL_set_fd(sc->connection, c->fd) == 0) {
		ssl_error(LOG_ERR, "SSL_set_fd failed");
		SSL_free(sc->connection);
		hfree(sc);
		return -1;
	}
	
	if (i_am_client) {
		SSL_set_connect_state(sc->connection);
	} else {
		SSL_set_accept_state(sc->connection);
	}
	
	if (SSL_set_ex_data(sc->connection, ssl_connection_index, c) == 0) {
		ssl_error(LOG_ERR, "SSL_set_ex_data failed");
		SSL_free(sc->connection);
		hfree(sc);
		return -1;
	}
	
	sc->validate = ssl->validate;
	c->ssl_con = sc;
	
	return 0;
}
예제 #22
0
파일: hlog.c 프로젝트: hessu/aprsc
int accesslog_open(char *logd, int reopen)
{
    if (!reopen)
        rwl_wrlock(&accesslog_lock);

    if (accesslog_fname)
        hfree(accesslog_fname);

    if (accesslog_dir)
        hfree(accesslog_dir);

    accesslog_dir = hstrdup(logd);
    accesslog_fname = hmalloc(strlen(accesslog_dir) + strlen(accesslog_basename) + 2);
    sprintf(accesslog_fname, "%s/%s", accesslog_dir, accesslog_basename);

    accesslog_file = open(accesslog_fname, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP);
    if (accesslog_file < 0)
        hlog(LOG_CRIT, "Could not open %s: %s", accesslog_fname, strerror(errno));

    rwl_wrunlock(&accesslog_lock);

    return accesslog_file;
}
예제 #23
0
파일: heap.c 프로젝트: kellyawang/heap
/*
 * hstrdup(s).
 * Allocate new copy of string s using just the space necessary.
 */
char *hstrdup(char *s)
{
  return strcpy((char*)hmalloc(strlen(s)),s);
}
예제 #24
0
파일: ais.c 프로젝트: FlavioFalcao/gnuais
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	snd_pcm_t *handle;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
#ifdef HAVE_PULSEAUDIO
	pa_simple *pa_dev = NULL;
#endif
	
	/* command line */
	parse_cmdline(argc, argv);
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* fork a daemon */
	if (fork_a_daemon) {
		int i = fork();
		if (i < 0) {
			hlog(LOG_CRIT, "Fork to background failed: %s", strerror(errno));
			fprintf(stderr, "Fork to background failed: %s\n", strerror(errno));
			exit(1);
		} else if (i == 0) {
			/* child */
			/* write pid file, now that we have our final pid... might fail, which is critical */
			hlog(LOG_DEBUG, "Writing pid...");
			if (!writepid(pidfile))
				exit(1);
		} else {
			/* parent, quitting */
			hlog(LOG_DEBUG, "Forked daemon process %d, parent quitting", i);
			exit(0);
		}
	}
	
	
	signal(SIGINT, closedown);
	signal(SIGPIPE, brokenconnection);
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize serial port for NMEA output */
	if (serial_port)
		serial = serial_init();

	/* initialize Unix domain socket for communication with gnuaisgui */
	ipc = gnuais_ipc_init();
	if(ipc == 0){
		hlog(LOG_ERR, "Could not open Unix Domain Socket");
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,serial,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,serial,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,serial,ipc);
		channels = 1;
	}
#ifdef HAVE_PULSEAUDIO
	if(sound_device != NULL && ((strcmp("pulse",sound_device) == 0) || (strcmp("pulseaudio",sound_device) == 0))){
		if((pa_dev = pulseaudio_initialize()) == NULL){
			hlog(LOG_CRIT, "Error opening pulseaudio device");
			return -1;
		}
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	}
	else if (sound_device){
#else
	if (sound_device){
#endif

		if ((err = snd_pcm_open(&handle, sound_device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
			hlog(LOG_CRIT, "Error opening sound device (%s)", sound_device);
			return -1;
		}
		
		if (input_initialize(handle, &buffer, &buffer_l) < 0)
			return -1;
	} else if (sound_in_file) {
		if ((sound_in_fd = fopen(sound_in_file, "r")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound file %s: %s", sound_in_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Reading audio from file: %s", sound_in_file);
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	} else {
		hlog(LOG_CRIT, "Neither sound device or sound file configured.");
		return -1;
	}
	
	if (sound_out_file) {
		if ((sound_out_fd = fopen(sound_out_file, "w")) == NULL) {
			hlog(LOG_CRIT, "Could not open sound output file %s: %s", sound_out_file, strerror(errno));
			return -1;
		}
		hlog(LOG_NOTICE, "Recording audio to file: %s", sound_out_file);
	}
	
#ifdef HAVE_MYSQL
	if (mysql_db) {
		hlog(LOG_DEBUG, "Saving to MySQL database \"%s\"", mysql_db);
		if (!(my = myout_init()))
			return -1;
			
		if (mysql_keepsmall)
			hlog(LOG_DEBUG, "Updating database rows only.");
		else
			hlog(LOG_DEBUG, "Inserting data to database.");
			
		if (mysql_oldlimit)
			hlog(LOG_DEBUG, "Deleting data older than %d seconds", mysql_oldlimit);
	}
#endif
	
	hlog(LOG_NOTICE, "Started");
	
	while (!done) {
		if (sound_in_fd) {
			buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
		} 
#ifdef HAVE_PULSEAUDIO
		else if (pa_dev){
			buffer_read = pulseaudio_read(pa_dev, buffer, buffer_l);
		}
#endif
		else {
			buffer_read = input_read(handle, buffer, buffer_l);
			//printf("read %d\n", buffer_read);
		}
		if (buffer_read <= 0)
			continue;
		
		if (sound_out_fd) {
			fwrite(buffer, channels * sizeof(short), buffer_read, sound_out_fd);
		}
		
		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
#ifdef HAVE_PULSEAUDIO
	else if (pa_dev) {
		pulseaudio_cleanup(pa_dev);
	}
#endif
	else {
		input_cleanup(handle);
		handle = NULL;
	}

	
	if (sound_out_fd)
		fclose(sound_out_fd);
	
	hfree(buffer);

	gnuais_ipc_deinit(ipc);
	
	if (serial)
		serial_close(serial);
	
	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}
예제 #25
0
파일: http.c 프로젝트: snip/aprsc
static void http_route_static(struct evhttp_request *r, const char *uri)
{
	struct http_static_t *cmdp;
	struct stat st;
	char fname[HTTP_FNAME_LEN];
	char last_modified[128];
	char *contenttype;
	int fd;
	int file_size;
	char *buf;
	struct evkeyvalq *req_headers;
	const char *ims;
	
	for (cmdp = http_static_files; cmdp->name != NULL; cmdp++)
		if (strcmp(cmdp->name, uri) == 0)
			break;
			
	if (cmdp->name == NULL) {
		hlog(LOG_DEBUG, "HTTP: 404");
		evhttp_send_error(r, HTTP_NOTFOUND, "Not found");
		return;
	}
	
	snprintf(fname, HTTP_FNAME_LEN, "%s/%s", webdir, cmdp->filename);
	
	//hlog(LOG_DEBUG, "static file request %s", uri);
	
	fd = open(fname, 0, O_RDONLY);
	if (fd < 0) {
		if (errno == ENOENT) {
			/* don't complain about missing motd.html - it's optional. */
			int level = LOG_ERR;
			if (strcmp(cmdp->filename, "motd.html") == 0)
				level = LOG_DEBUG;
			hlog(level, "http static file '%s' not found", fname);
			evhttp_send_error(r, HTTP_NOTFOUND, "Not found");
			return;
		}
		
		hlog(LOG_ERR, "http static file '%s' could not be opened for reading: %s", fname, strerror(errno));
		evhttp_send_error(r, HTTP_INTERNAL, "Could not access file");
		return;
	}
	
	if (fstat(fd, &st) == -1) {
		hlog(LOG_ERR, "http static file '%s' could not fstat() after opening: %s", fname, strerror(errno));
		evhttp_send_error(r, HTTP_INTERNAL, "Could not access file");
		if (close(fd) < 0)
			hlog(LOG_ERR, "http static file '%s' could not be closed after failed stat: %s", fname, strerror(errno));
		return;
	}
	
	http_date(last_modified, sizeof(last_modified), st.st_mtime);
	
	contenttype = http_content_type(cmdp->filename);
	//hlog(LOG_DEBUG, "found content-type %s", contenttype);
	
	struct evkeyvalq *headers = evhttp_request_get_output_headers(r);
	http_header_base(headers, st.st_mtime);
	evhttp_add_header(headers, "Content-Type", contenttype);
	
	/* Consider an IMS hit */
	req_headers = evhttp_request_get_input_headers(r);
	ims = evhttp_find_header(req_headers, "If-Modified-Since");
	
	if ((ims) && strcasecmp(ims, last_modified) == 0) {
		hlog(LOG_DEBUG, "http static file '%s' IMS hit", fname);
		evhttp_send_reply(r, HTTP_NOTMODIFIED, "Not modified", NULL);
		if (close(fd) < 0)
			hlog(LOG_ERR, "http static file '%s' could not be closed after failed stat: %s", fname, strerror(errno));
		return;
	}
	
	file_size = st.st_size;
	
	/* yes, we are not going to serve large files. */
	buf = hmalloc(file_size);
	int n = read(fd, buf, file_size);
	
	if (close(fd) < 0) {
		hlog(LOG_ERR, "http static file '%s' could not be closed after reading: %s", fname, strerror(errno));
		evhttp_send_error(r, HTTP_INTERNAL, "Could not access file");
		hfree(buf);
		return;
	}
	
	if (n != file_size) {
		hlog(LOG_ERR, "http static file '%s' could only read %d of %d bytes", fname, n, file_size);
		evhttp_send_error(r, HTTP_INTERNAL, "Could not access file");
		hfree(buf);
		return;
	}
	
	int allow_compress;
	if (strncmp(contenttype, "image/", 6) == 0)
		allow_compress = 0;
	else
		allow_compress = 1;
	
	http_send_reply_ok(r, headers, buf, n, allow_compress);
	hfree(buf);
}
예제 #26
0
파일: cfg.c 프로젝트: FlavioFalcao/gnuais
int read_config(void)
{
	int failed = 0;
	char *s;
	
	if (read_cfgfile(cfgfile, cfg_cmds))
		return -1;
	
	/* these parameters will only be used when reading the configuration
	 * for the first time.
	 */
	if(log_dir){	/* Check if logdir passed from command line. In that case config file parameter should be ignored*/
		logdir = hstrdup(log_dir);	
	}
	else if(!logdir) { /* Using current directory as default if not given neither in config file or command line */
		if(log_dest == L_FILE)
			hlog(LOG_WARNING, "Config: logdir not defined. Using . as log directory");
		logdir = hstrdup(".");
	}

	/* mycall is only applied when running for the first time. */
	if (!mycall) {
		mycall = hstrdup("NOCALLDEFINED"); 
		hlog(LOG_WARNING, "Config: mycall is not defined - using: %s.",mycall);
		//failed = 1;
	} else if (!valid_aprsis_call(mycall)) {
		hlog(LOG_CRIT, "Config: mycall '%s' is not valid.", mycall);
		failed = 1;
	}
	
	if (!myemail) {
		myemail = hstrdup("notdefined@notdefined"); 
		hlog(LOG_WARNING, "Config: myemail is not defined - using: %s.",myemail);
		//failed = 1;
	}
	
	if (!sound_in_file && !sound_device) {
		sound_device = def_sound_device;
		hlog(LOG_WARNING, "Config: SoundDevice is not defined - using: %s", sound_device);
	}
	
	if (sound_in_file && sound_device) {
		if (sound_device != def_sound_device)
			hfree(sound_device);
		sound_device = NULL;
	}
	
	/* put in the new uplink config */
	free_uplink_config(&uplink_config);
	uplink_config = new_uplink_config;
	if (uplink_config)
		uplink_config->prevp = &uplink_config;
	new_uplink_config = NULL;

	if (failed)
		return -1;
	
	if (!pidfile) {
		s = hmalloc(strlen(logdir) + 1 + strlen(logname) + 3 + 2);
		sprintf(s, "%s/%s.pid", logdir, logname);
		
		pidfile = s;
	}
	
	return 0;
}
예제 #27
0
void accept_thread(void *asdf)
{
	sigset_t sigs_to_block;
	int e, n;
	struct pollfd *acceptpfd = NULL;
	struct listen_t **acceptpl = NULL;
	int listen_n = 0;
	int poll_n = 0;
	struct listen_t *l;

	pthreads_profiling_reset("accept");
	
	sigemptyset(&sigs_to_block);
	sigaddset(&sigs_to_block, SIGALRM);
	sigaddset(&sigs_to_block, SIGINT);
	sigaddset(&sigs_to_block, SIGTERM);
	sigaddset(&sigs_to_block, SIGQUIT);
	sigaddset(&sigs_to_block, SIGHUP);
	sigaddset(&sigs_to_block, SIGURG);
	sigaddset(&sigs_to_block, SIGPIPE);
	sigaddset(&sigs_to_block, SIGUSR1);
	sigaddset(&sigs_to_block, SIGUSR2);
	pthread_sigmask(SIG_BLOCK, &sigs_to_block, NULL);
	
	/* start the accept thread, which will start server threads */
	hlog(LOG_INFO, "Accept thread starting...");
	
	/* we allocate a worker structure to be used within the accept thread
	 * for parsing incoming UDP packets and passing them on to the dupecheck
	 * thread.
	 */
	udp_worker = worker_alloc();
	udp_worker->id = 81;
	
	/* we also need a client structure to be used with incoming
	 * HTTP position uploads
	 */
	udp_pseudoclient = pseudoclient_setup(81);
	udp_pseudoclient->flags |= CLFLAGS_UDPSUBMIT;
	
	accept_reconfiguring = 1;
	while (!accept_shutting_down) {
		if (accept_reconfiguring) {
			accept_reconfiguring = 0;
			listen_n -= close_removed_listeners();
			
			/* start listening on the sockets */
			listen_n += open_missing_listeners();
			
			if (listen_n < 1) {
				hlog(LOG_CRIT, "Failed to listen on any ports.");
				exit(2);
			}
			
			/* reconfiguration must scan old clients against ACL */
			rescan_client_acls();
			
			/* how many are we polling */
			poll_n = 0;
			for (l = listen_list; (l); l = l->next)
				if (!l->corepeer)
					poll_n++;
			
			hlog(LOG_DEBUG, "Generating polling list for %d/%d listeners...", poll_n, listen_n);
			
			/* array of FDs for poll() */
			if (acceptpfd)
				hfree(acceptpfd);
			acceptpfd = hmalloc(poll_n * sizeof(*acceptpfd));
			
			/* array of listeners */
			if (acceptpl)
				hfree(acceptpl);
			acceptpl = hmalloc(poll_n * sizeof(*acceptpl));
			
			n = 0;
			for (l = listen_list; (l); l = l->next) {
				/* The accept thread does not poll() UDP sockets for core peers.
				 * Worker 0 takes care of that, and processes the incoming packets.
				 */
				if (l->corepeer) {
					hlog(LOG_DEBUG, "... %d: fd %d (%s) - not polled, is corepeer", n, (l->udp) ? l->udp->fd : l->fd, l->addr_s);
					continue;
				}
				
				int fd;
				if (l->udp) {
					l->udp->polled = 1;
					fd = l->udp->fd;
				} else {
					fd = l->fd;
				}
				
				hlog(LOG_DEBUG, "... %d: fd %d (%s)", n, fd, l->addr_s);
				acceptpfd[n].fd = fd;
				acceptpfd[n].events = POLLIN|POLLPRI|POLLERR|POLLHUP;
				acceptpl[n] = l;
				n++;
			}
			hlog(LOG_INFO, "Accept thread ready.");
			
			/* stop the dupechecking and uplink threads while adjusting
			 * the amount of workers... they walk the worker list, and
			 * might get confused when workers are stopped or started.
			 */
			if (workers_running != workers_configured) {
				uplink_stop();
				dupecheck_stop();
				workers_start();
				dupecheck_start();
				uplink_start();
			}
			
			/*
			 * generate UDP peer clients
			 */
			peerip_clients_close();
			if (peerip_config)
				peerip_clients_config();
			
			/* accept liveupgrade clients */
			if (liveupgrade_status)
				accept_liveupgrade_accept();
		}
		
		/* check for new connections */
		e = poll(acceptpfd, poll_n, 200);
		if (e == 0)
			continue;
		if (e < 0) {
			if (errno == EINTR)
				continue;
			hlog(LOG_ERR, "poll() on accept failed: %s (continuing)", strerror(errno));
			continue;
		}
		
		/* now, which socket was that on? */
		for (n = 0; n < poll_n; n++) {
			l = acceptpl[n];
			if (!(l) || (l->udp ? l->udp->fd : l->fd) != acceptpfd[n].fd) {
				hlog(LOG_CRIT, "accept_thread: polling list and listener list do mot match!");
				exit(1);
			}
			if (acceptpfd[n].revents) {
				if (l->udp)
					accept_udp_recv(l); /* receive UDP packets */
				else
					do_accept(l); /* accept a single connection */
			}
		}
	}
	
	if (accept_shutting_down == 2)
		worker_shutdown_clients = cJSON_CreateArray();
	
	hlog(LOG_DEBUG, "Accept thread shutting down listening sockets and worker threads...");
	uplink_stop();
	close_listeners();
	dupecheck_stop();
	http_shutting_down = 1;
	workers_stop(accept_shutting_down);
	hfree(acceptpfd);
	hfree(acceptpl);
	acceptpfd = NULL;
	acceptpl = NULL;
	
	/* free up the pseudo-client */
	client_free(udp_pseudoclient);
	udp_pseudoclient = NULL;
	
	/* free up the pseudo-worker structure, after dupecheck is long dead */
	worker_free_buffers(udp_worker);
	hfree(udp_worker);
	udp_worker = NULL;
}
예제 #28
0
파일: client_heard.c 프로젝트: oh2mqk/aprsc
static void heard_list_update(struct client_t *c, struct pbuf_t *pb, struct client_heard_t **list, int *entrycount, char *which)
{
	struct client_heard_t *h;
	int call_len;
	uint32_t hash, idx;
	int i;
	
	call_len = pb->srccall_end - pb->data;
	hash = keyhashuc(pb->data, call_len, 0);
	idx = hash;
	// "CLIENT_HEARD_BUCKETS" is 16..
	idx ^= (idx >> 16);
	idx ^= (idx >>  8);
	idx ^= (idx >>  4);
	i = idx % CLIENT_HEARD_BUCKETS;
	
	//DLOG(LOG_DEBUG, "heard_list_update fd %d %s: updating heard table for %.*s (hash %u i %d)", c->fd, which, call_len, pb->data, hash, i);
	
	for (h = list[i]; (h); h = h->next) {
		if (h->hash == hash && call_len == h->call_len
		    && strncasecmp(pb->data, h->callsign, h->call_len) == 0) {
			// OK, found it from the list

			//DLOG(LOG_DEBUG, "heard_list_update fd %d %s: found, updating %.*s", c->fd, which, call_len, pb->data);
			h->last_heard = pb->t;
			
			/* Because of digipeating we'll see the same station
			 * really quickly again, and the less active stations are, well, less active,
			 * let's move it in the beginning of the list to find it quicker.
			 */
			 
			 if (list[i] != h) {
				//DLOG(LOG_DEBUG, "heard_list_update fd %d %s: moving to front %.*s", c->fd, which, call_len, pb->data);
				*h->prevp = h->next;
				if (h->next)
					h->next->prevp = h->prevp;
				
				h->next = list[i];
				h->prevp = &list[i];
				if (h->next)
					h->next->prevp = &h->next;
				list[i] = h;
			}
			
			return;
		}
	}
	
	/* Not found, insert. */
	DLOG(LOG_DEBUG, "heard_list_update fd %d %s: inserting %.*s", c->fd, which, call_len, pb->data);
#ifndef _FOR_VALGRIND_
	h = cellmalloc(client_heard_cells);
	if (!h) {
	        hlog(LOG_ERR, "heard_list_update: cellmalloc failed");
	        return;
	}
#else	
	h = hmalloc(sizeof(*h));
#endif
	h->hash = hash;
	strncpy(h->callsign, pb->data, call_len);
	h->callsign[sizeof(h->callsign)-1] = 0;
	h->call_len = call_len;
	h->last_heard = pb->t;
	
	/* insert in beginning of linked list */
	h->next = list[i];
	h->prevp = &list[i];
	if (h->next)
		h->next->prevp = &h->next;
	list[i] = h;
	*entrycount = *entrycount + 1;
}
예제 #29
0
파일: hmalloc.cpp 프로젝트: mymy49/lss
void* operator new (unsigned int size)
{
	return hmalloc(size);
}
예제 #30
0
파일: ais.c 프로젝트: kbeckmann/gnuais.js
int main(int argc, char *argv[])
{
	int err;
	done = 0;
	FILE *sound_in_fd = NULL;
	FILE *sound_out_fd = NULL;
	int channels;
	short *buffer = NULL;
	int buffer_l;
	int buffer_read;
	struct serial_state_t *serial = NULL;
	struct ipc_state_t *ipc = NULL;
	struct receiver *rx_a = NULL;
	struct receiver *rx_b = NULL;
	
	/* open syslog, write an initial log message and read configuration */
	open_log(logname, 0);
	hlog(LOG_NOTICE, "Starting up...");
	if (read_config()) {
		hlog(LOG_CRIT, "Initial configuration failed.");
		exit(1);
	}
	
	/* initialize position cache for timed JSON AIS transmission */
	if (uplink_config) {
		hlog(LOG_DEBUG, "Initializing cache...");
		if (cache_init())
			exit(1);
		hlog(LOG_DEBUG, "Initializing jsonout...");
		if (jsonout_init())
			exit(1);
	}
	
	/* initialize the AIS decoders */
	if (sound_channels != SOUND_CHANNELS_MONO) {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 2, 0,ipc);
		hlog(LOG_DEBUG, "Initializing demodulator B");
		rx_b = init_receiver('B', 2, 1,ipc);
		channels = 2;
	} else {
		hlog(LOG_DEBUG, "Initializing demodulator A");
		rx_a = init_receiver('A', 1, 0,ipc);
		channels = 1;
	}


	printf("HEJ!");

		hlog(LOG_NOTICE, "Reading audio from blob.");
		buffer_l = 1024;
		int extra = buffer_l % 5;
		buffer_l -= extra;
		buffer = (short *) hmalloc(buffer_l * sizeof(short) * channels);
	
	hlog(LOG_NOTICE, "Started");
	
	int dataoffset = 0;

#define AAA 0

#if AAA
	sound_in_fd = fopen("xaa", "rb");
#endif

	while (!done) {
		printf(".");
#if AAA
		buffer_read = fread(buffer, channels * sizeof(short), buffer_l, sound_in_fd);
			if (buffer_read <= 0)
				done = 1;
#else
		memcpy(buffer, staticSoundData + dataoffset, buffer_l * channels * sizeof(short));
		dataoffset += buffer_l * channels;
		if (dataoffset >= sizeof(staticSoundData) / sizeof(short)) {
			done = 1;
		}
		buffer_read = buffer_l;

#endif

# if 0
		printf("buffer_read: %d\n", buffer_read);
		int xx;
		for (xx = 0; xx < buffer_l * channels; xx++)
			printf("%x ", buffer[xx]);
		
		done = 1;
#endif

		if (sound_channels == SOUND_CHANNELS_MONO) {
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_RIGHT) {
			/* ch a/0/right */
			receiver_run(rx_a, buffer, buffer_read);
		}
		if (sound_channels == SOUND_CHANNELS_BOTH
		    || sound_channels == SOUND_CHANNELS_LEFT) {	
			/* ch b/1/left */
			receiver_run(rx_b, buffer, buffer_read);
		}
	}
	
	hlog(LOG_NOTICE, "Closing down...");
	if (sound_in_fd) {
		fclose(sound_in_fd);
	}
	
	hfree(buffer);

	if (uplink_config)
		jsonout_deinit();
	
	if (cache_positions)
		cache_deinit();
	
	if (rx_a) {
		struct demod_state_t *d = rx_a->decoder;
		hlog(LOG_INFO,
			"A: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	if (rx_b) {
		struct demod_state_t *d = rx_b->decoder;
		hlog(LOG_INFO,
			"B: Received correctly: %d packets, wrong CRC: %d packets, wrong size: %d packets",
			d->receivedframes, d->lostframes,
			d->lostframes2);
	}
	
	free_receiver(rx_a);
	free_receiver(rx_b);
	
	free_config();
	close_log(0);
	
	return 0;
}