Exemple #1
0
void InitStdoutFilter() {
	stdout_cookie.real_file = stdout;
	stderr_cookie.real_file = stderr;
	stdout = fopencookie(&stdout_cookie, "w+", filteroutput_func);
	stderr = fopencookie(&stderr_cookie, "w+", filteroutput_func);
	setlinebuf(stdout);
	setlinebuf(stderr);
}
Exemple #2
0
FILE *fmemopen(void *s, size_t len, const char *modes)
{
	FILE *fp;
	register __fmo_cookie *cookie;
	size_t i;

	if ((cookie = malloc(sizeof(__fmo_cookie))) != NULL) {
		cookie->len = len;
		cookie->eof = cookie->pos = 0; /* pos and eof adjusted below. */
		cookie->dynbuf = 0;
		if (((cookie->buf = s) == NULL) && (len > 0)) {
			if ((cookie->buf = malloc(len)) == NULL) {
				goto EXIT_cookie;
			}
			cookie->dynbuf = 1;
			*cookie->buf = 0;	/* If we're appending, treat as empty file. */
		}

#ifndef __BCC__
		fp = fopencookie(cookie, modes, _fmo_io_funcs);
#else
		fp = fopencookie(cookie, modes, &_fmo_io_funcs);
#endif
		/* Note: We don't need to worry about locking fp in the thread case
		 * as the only possible access would be a close or flush with
		 * nothing currently in the FILE's write buffer. */

		if (fp != NULL) {
			cookie->fp = fp;
			if (fp->__modeflags & __FLAG_READONLY) {
				cookie->eof = len;
			}
			if ((fp->__modeflags & __FLAG_APPEND) && (len > 0)) {
				for (i = 0 ; i < len ; i++) {
					if (cookie->buf[i] == 0) {
						break;
					}
				}
				cookie->eof = cookie->pos = i; /* Adjust eof and pos. */
			}

			__STDIO_STREAM_VALIDATE(fp);

			return fp;
		}
	}

	if (!s) {
		free(cookie->buf);
	}
 EXIT_cookie:
	free(cookie);

	return NULL;
}
Exemple #3
0
static FILE *
open_logfile(size_t sz, const char *fmt, ...)
{
	static cookie_io_functions_t funcs = {
		NULL,
		size_limited_write,
		NULL,
		size_limited_close
	};
	va_list args;
	va_start(args, fmt);
	char *path;
	int r = vasprintf(&path, fmt, args);
	(void)r;
	va_end(args);
	FILE *f = fopen(path, "a");
	free(path);
	if (!f)
		return NULL;
	struct size_limited_file *slf = (struct size_limited_file *)malloc(sizeof(struct size_limited_file));
	slf->remaining_quota = sz;
	slf->f = f;
	FILE *res = fopencookie(slf, "a", funcs);
	if (!res) {
		fclose(f);
		free(slf);
		return NULL;
	}
	return res;
}
Exemple #4
0
static FILE *cookieopen(void *cookie, const char *mode,
	ssize_t (*cread)(void *, char *, size_t), 
	ssize_t (*cwrite)(void *, const char *, size_t), 
	int (*cclose)(void *))
{
  if (!cookie)
    return 0;
#ifdef HAVE_FUNOPEN
  return funopen(cookie, 
      (int (*)(void *, char *, int))(*mode == 'r' ? cread: NULL),/* readfn */
      (int (*)(void *, const char *, int))(*mode == 'w' ? cwrite : NULL), /* writefn */
      (fpos_t (*)(void *, fpos_t, int))NULL, /* seekfn */
      cclose
      );
#elif defined(HAVE_FOPENCOOKIE)
  cookie_io_functions_t cio;
  memset(&cio, 0, sizeof(cio));
  if (*mode == 'r')
    cio.read = cread;
  else if (*mode == 'w')
    cio.write = cwrite;
  cio.close = cclose;
  return  fopencookie(cookie, *mode == 'w' ? "w" : "r", cio);
#else
# error Need to implement custom I/O
#endif
}
Exemple #5
0
FILE* unpack_open(const char* filename, const char* mode){
	struct datapack_file_entry* entry = unpack_find(filename);
	if ( !entry ){
		errno = ENOENT;
		return NULL;
	}

	const int write = strchr(mode, 'w') || strchr(mode, 'a');
	const int read = !write;

	/* allow overriding with local path */
	if ( read && local ){
		char* local_path;
		asprintf(&local_path, "%s/%s", local, filename);
		FILE* fp = fopen(local_path, mode);
		free(local_path);
		if ( fp ){
			return fp;
		}
	}

	if ( write ) {
		/* ensure write is done in local mode */
		if ( !local ){
			errno = EPERM;
			return NULL;
		}

		/* ensure directory exists */
		rec_mkdir(local);

		/* give file pointer directly from fopen */
		char* local_path;
		asprintf(&local_path, "%s/%s", local, filename);
		FILE* fp = fopen(local_path, mode);
		free(local_path);

		return fp;
	}

	struct unpack_cookie_data* ctx = (struct unpack_cookie_data*)malloc(sizeof(struct unpack_cookie_data));
	ctx->src = entry;
	ctx->bufsize = 0;

	ctx->strm.avail_in = entry->in_bytes;
	ctx->strm.next_in = (unsigned char*)entry->data;
	ctx->strm.zalloc = Z_NULL;
	ctx->strm.zfree = Z_NULL;
	ctx->strm.opaque = Z_NULL;
	int ret = inflateInit(&ctx->strm);
	if (ret != Z_OK){
		errno = EBADFD;
		return NULL;
	}

	return fopencookie(ctx, mode, unpack_cookie_func);
}
Exemple #6
0
/* Create a new plotter whose output and error are Guile ports */
SCM
gupl_newpl (SCM type, SCM outp, SCM errp, SCM param)
{
  char *c_type;
  FILE *c_outp, *c_errp;
  plPlotter *ret;
  plPlotterParams *c_param;

  SCM_ASSERT (scm_is_string (type), type, SCM_ARG1, "newpl");
  SCM_ASSERT (scm_is_true (scm_output_port_p (outp)), outp, SCM_ARG2,
	      "newpl");
  SCM_ASSERT (scm_is_true (scm_output_port_p (errp)), errp, SCM_ARG3, "newpl");
  SCM_ASSERT (_scm_is_plparams (param), param, SCM_ARG4, "newpl");

  /* Convert the output port to a special stream */
  c_outp = fopencookie (SCM2PTR (outp), "wb", port_funcs);

  /* Don't buffer port here, since the underlying Guile port also has
     port buffering.  Double buffering causes problems.  */

  setvbuf (c_outp, NULL, _IONBF, 0);
  if (c_outp == NULL)
    scm_syserror ("newpl");

  /* Convert the err port to a special stream */
  c_errp = fopencookie (SCM2PTR (errp), "wb", port_funcs);
  if (c_errp == NULL)
    scm_out_of_range ("newpl", errp);
  setvbuf (c_errp, NULL, _IONBF, 0);

  c_type = scm_to_locale_string (type);
  c_param = _scm_to_plparams (param);

  ret = pl_newpl_r (c_type, NULL, c_outp, c_errp, c_param);

  free (c_type);

  if (ret == NULL)
    return SCM_BOOL_F;

  return _scm_from_plotter (ret);
}
Exemple #7
0
static FILE *_ssl_fopen(int sd, int client)
{
	int r;
	mssl_cookie_t *kuki;
	FILE *f;

	_dprintf("%s()\n", __FUNCTION__);

	if ((kuki = calloc(1, sizeof(*kuki))) == NULL) {
		errno = ENOMEM;
		return NULL;
	}
	kuki->sd = sd;

	if ((kuki->ssl = SSL_new(ctx)) == NULL) {
		_dprintf("%s: SSL_new failed\n", __FUNCTION__);
		goto ERROR;
	}

#ifdef USE_OPENSSL
	SSL_set_verify(kuki->ssl, SSL_VERIFY_NONE, NULL);
	SSL_set_mode(kuki->ssl, SSL_MODE_AUTO_RETRY);
#endif
	SSL_set_fd(kuki->ssl, kuki->sd);

	r = client ? SSL_connect(kuki->ssl) : SSL_accept(kuki->ssl);
	if (r <= 0) {
		_dprintf("%s: SSL handshake failed\n", __FUNCTION__);
		mssl_print_err(kuki->ssl);
		goto ERROR;
	}

#ifdef USE_OPENSSL
	_dprintf("SSL connection using %s cipher\n", SSL_get_cipher(kuki->ssl));
#endif

	if ((f = fopencookie(kuki, "r+", mssl)) == NULL) {
		_dprintf("%s: fopencookie failed\n", __FUNCTION__);
		goto ERROR;
	}

	_dprintf("%s() success\n", __FUNCTION__);
	return f;

ERROR:
	mssl_close(kuki);
	return NULL;
}
FILE *tmpfile_fopencookie(void) {
  static const cookie_io_functions_t memfile_func = {
    .read  = memfile_read,
    .write = memfile_write,
    .seek  = memfile_seek,
    .close = memfile_close
  };
  struct memfile_cookie *mycookie;
  mycookie = malloc(sizeof(struct memfile_cookie));
  if ( !mycookie ) return NULL;
  mycookie->buf = malloc(INIT_BUF_SIZE);
  mycookie->allocated = INIT_BUF_SIZE;
  mycookie->offset = 0;
  mycookie->endpos = 0;
  return fopencookie(&mycookie,"w+",memfile_func);
}
Exemple #9
0
char *
nameIRExpr(const IRExpr *a)
{
	cookie_io_functions_t functionTable;
	memset(&functionTable, 0, sizeof(functionTable));
	functionTable.write = __nameIRExpr_write;
	struct __nameIRExpr_context ctxt;
	ctxt.buffer_used = 0;
	ctxt.buffer = NULL;
	FILE *f = fopencookie(&ctxt, "w", functionTable);
	if (!f)
		err(1, "fopencookie() returned NULL?");
	ppIRExpr(a, f);
	fclose(f);
	return ctxt.buffer;
}
/**
 * @note must call fclose after use of returned FILE
 */
FILE* IOutputStream::forOutputFILE()
{
	cookie_io_functions_t func = {
		NULL,
		OutputStream_write,
		NULL,
		NULL
	};
	assert(this);
	void* cookie = this;
	FILE* fp = fopencookie(cookie,"w", func);
	if (fp == NULL) {
		perror("fopencookie@IOutputStream::forOutputFILE");
		return NULL;
	}
	return fp;
}
/**
 * @note must call fclose after use of returned FILE
 */
FILE* IInputStream::forInputFILE()
{
	cookie_io_functions_t func = {
		InputStream_read,
		NULL,
		NULL,
		NULL
	};
	assert(this);
	void* cookie = this;
	FILE* fp = fopencookie(cookie,"r", func);
	if (fp == NULL) {
		perror("fopencookie@IInputStream::forInputFILE");
		return NULL;
	}
	return fp;
}
Exemple #12
0
FILE *ssl_server_fopen(int fd)
{
	FILE *fp;
	http_ssl_cookie_t *hsc;

	hsc = (http_ssl_cookie_t *)malloc(sizeof(http_ssl_cookie_t));
	if (!hsc)
		return NULL;

	hsc->fd = fd;
	hsc->ssl = SSL_new(ssl_ctx);
	if (!hsc->ssl)
		goto ERROR;

	SSL_set_mode(hsc->ssl, SSL_MODE_AUTO_RETRY);

	if (SSL_set_fd(hsc->ssl, fd) != 1)
		goto ERROR;

	for (;;) {
		int ret = SSL_accept(hsc->ssl);
		if (ret <= 0) {
			int err = SSL_get_error(hsc->ssl, ret);
			if (ret < 0 && (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE))
				continue;
			goto ERROR;
		}
		break;
	}

	fp = fopencookie((void*)hsc, "r+", http_ssl_io);
	if (!fp)
		goto ERROR;

	return fp;

ERROR:

	if (hsc->ssl)
		SSL_free(hsc->ssl);

	free(hsc);

	return NULL;
}
Exemple #13
0
static FILE *mygzfopen(gzFile* gzf)
{
#ifdef HAVE_FUNOPEN
  return funopen(
      gzf, (int (*)(void *, char *, int))cookie_gzread,
      (int (*)(void *, const char *, int))NULL, /* writefn */
      (fpos_t (*)(void *, fpos_t, int))NULL, /* seekfn */
      cookie_gzclose
      );
#elif defined(HAVE_FOPENCOOKIE)
  cookie_io_functions_t cio;
  memset(&cio, 0, sizeof(cio));
  cio.read = cookie_gzread;
  cio.close = cookie_gzclose;
  return  fopencookie(gzf, "r", cio);
#else
# error Need to implement custom I/O
#endif
}
Exemple #14
0
static sexp sexp_make_custom_port (sexp ctx, sexp self, char *mode,
                                   sexp read, sexp write,
                                   sexp seek, sexp close) {
  FILE *in;
  sexp res;
  sexp_gc_var1(vec);
  if (sexp_truep(read) && ! sexp_procedurep(read))
    return sexp_type_exception(ctx, self, SEXP_PROCEDURE, read);
  if (sexp_truep(write) && ! sexp_procedurep(write))
    return sexp_type_exception(ctx, self, SEXP_PROCEDURE, write);
  if (sexp_truep(seek) && ! sexp_procedurep(seek))
    return sexp_type_exception(ctx, self, SEXP_PROCEDURE, seek);
  if (sexp_truep(close) && ! sexp_procedurep(close))
    return sexp_type_exception(ctx, self, SEXP_PROCEDURE, close);
  sexp_gc_preserve1(ctx, vec);
  vec = sexp_make_vector(ctx, SEXP_SIX, SEXP_VOID);
  sexp_cookie_ctx_set(vec, ctx);
  sexp_cookie_buffer_set(vec, sexp_make_string(ctx, sexp_make_fixnum(SEXP_PORT_BUFFER_SIZE), SEXP_VOID));
  sexp_cookie_read_set(vec, read);
  sexp_cookie_write_set(vec, write);
  sexp_cookie_seek_set(vec, seek);
  sexp_cookie_close_set(vec, close);
#if SEXP_BSD
  in = funopen(vec,
               (sexp_procedurep(read) ? sexp_cookie_reader : NULL),
               (sexp_procedurep(write) ? sexp_cookie_writer : NULL),
               NULL, /* (sexp_procedurep(seek) ? sexp_cookie_reader : NULL), */
               (sexp_procedurep(close) ? sexp_cookie_cleaner : NULL));
#else
  in = fopencookie(vec, mode, (sexp_truep(seek) ? sexp_cookie : sexp_cookie_no_seek));
#endif
  if (! in) {
    res = sexp_user_exception(ctx, self, "couldn't make custom port", read);
  } else {
    res = sexp_make_input_port(ctx, in, SEXP_FALSE);
    sexp_port_cookie(res) = vec;  /* for gc preserving */
  }
  if (mode && mode[0] == 'w')
    sexp_pointer_tag(res) = SEXP_OPORT;
  sexp_gc_release1(ctx);
  return res;
}
static FILE *usart_setup(uint32_t dev)
{
	/* Setup USART2 parameters. */
	usart_set_baudrate(dev, 38400);
	usart_set_databits(dev, 8);
	usart_set_parity(dev, USART_PARITY_NONE);
	usart_set_stopbits(dev, USART_CR2_STOP_1_0BIT);
	usart_set_mode(dev, USART_MODE_TX_RX);
	usart_set_flow_control(dev, USART_FLOWCONTROL_NONE);

	/* Finally enable the USART. */
	usart_enable(dev);

	cookie_io_functions_t stub = { _iord, _iowr, NULL, NULL };
	FILE *fp = fopencookie((void *)dev, "rw+", stub);
	/* Do not buffer the serial line */
	setvbuf(fp, NULL, _IONBF, 0);
	return fp;

}
Exemple #16
0
FILE *
__fopenport (mach_port_t port, const char *mode)
{
  int pflags;
  int needflags;
  error_t err;

  const char *m = mode;

  switch (*m++)
    {
    case 'r':
      needflags = O_READ;
      break;
    case 'w':
      needflags = O_WRITE;
      break;
    case 'a':
      needflags = O_WRITE|O_APPEND;
      break;
    default:
      return NULL;
  }
  if (m[0] == '+' || (m[0] == 'b' && m[1] == '+'))
    needflags |= O_RDWR;

  /* Verify the PORT is valid allows the access MODE specifies.  */

  if (err = __io_get_openmodes (port, &pflags))
    return __hurd_fail (err), NULL;

  /* Check the access mode.  */
  if ((pflags & needflags) != needflags)
    {
      errno = EBADF;
      return NULL;
    }

  return fopencookie ((void *) port, mode, funcsio);
}
Exemple #17
0
FILE *
funopen(const void *cookie,
        int (*readfn)(void *cookie, char *buf, int size),
        int (*writefn)(void *cookie, const char *buf, int size),
        off_t (*seekfn)(void *cookie, off_t offset, int whence),
        int (*closefn)(void *cookie))
{
	struct funopen_cookie *cookiewrap;
	cookie_io_functions_t funcswrap = {
		.read = funopen_read,
		.write = funopen_write,
		.seek = funopen_seek,
		.close = funopen_close,
	};
	const char *mode;

	if (readfn) {
		if (writefn == NULL)
			mode = "r";
		else
			mode = "r+";
	} else if (writefn) {
		mode = "w";
	} else {
		errno = EINVAL;
		return NULL;
	}

	cookiewrap = malloc(sizeof(*cookiewrap));
	if (cookiewrap == NULL)
		return NULL;

	cookiewrap->orig_cookie = (void *)cookie;
	cookiewrap->readfn = readfn;
	cookiewrap->writefn = writefn;
	cookiewrap->seekfn = seekfn;
	cookiewrap->closefn = closefn;

	return fopencookie(cookiewrap, mode, funcswrap);
}
Exemple #18
0
/*!
 * \internal
 * \brief Open a custom FILE stream for tcptls.
 *
 * \param stream Stream cookie control data.
 * \param ssl SSL state if not NULL.
 * \param fd Socket file descriptor.
 * \param timeout ms to wait for an event on fd. -1 if timeout disabled.
 *
 * \retval fp on success.
 * \retval NULL on error.
 */
static FILE *tcptls_stream_fopen(struct ast_tcptls_stream *stream, SSL *ssl, int fd, int timeout)
{
	FILE *fp;

#if defined(HAVE_FOPENCOOKIE)	/* the glibc/linux interface */
	static const cookie_io_functions_t cookie_funcs = {
		tcptls_stream_read,
		tcptls_stream_write,
		NULL,
		tcptls_stream_close
	};
#endif	/* defined(HAVE_FOPENCOOKIE) */

	if (fd == -1) {
		/* Socket not open. */
		return NULL;
	}

	stream->ssl = ssl;
	stream->fd = fd;
	stream->timeout = timeout;
	ao2_t_ref(stream, +1, "Opening tcptls stream cookie");

#if defined(HAVE_FUNOPEN)	/* the BSD interface */
	fp = funopen(stream, tcptls_stream_read, tcptls_stream_write, NULL,
		tcptls_stream_close);
#elif defined(HAVE_FOPENCOOKIE)	/* the glibc/linux interface */
	fp = fopencookie(stream, "w+", cookie_funcs);
#else
	/* could add other methods here */
	ast_debug(2, "No stream FILE methods attempted!\n");
	fp = NULL;
#endif

	if (!fp) {
		stream->fd = -1;
		ao2_t_ref(stream, -1, "Failed to open tcptls stream cookie");
	}
	return fp;
}
Exemple #19
0
static FILE * uopen (const char *buf, int size)
{
    static FILE *fp;

    if (fp) fclose (fp);

#ifdef	__AVR__
    fp = fdevopen (0, ugetc);
#else
    {
        cookie_io_functions_t iofuns;
	memset (& iofuns, 0, sizeof(iofuns));
        iofuns.read = uread;
	iofuns.close = uclose;
        fp = fopencookie (NULL, "rb", iofuns);
    }
#endif
    ASSERT (fp);

    getpnt = buf;
    getend = buf + size;
    return fp;
}
Exemple #20
0
FILE *  roar_vio_to_stdio      (struct roar_vio_calls * calls, int flags) {
#ifdef ROAR_HAVE_FOPENCOOKIE
 cookie_io_functions_t foc_funcs;
#endif

 if ( calls == NULL )
  return NULL;

#if defined(ROAR_HAVE_FOPENCOOKIE)
 memset(&foc_funcs, 0, sizeof(cookie_io_functions_t));

 foc_funcs.close = roar_vio_to_stdio_close;
 foc_funcs.read  = roar_vio_to_stdio_read;
 foc_funcs.write = roar_vio_to_stdio_write;

 return fopencookie((void*) calls, "rw", foc_funcs);
#elif defined(ROAR_HAVE_FUNOPEN)
 return funopen((void*) calls, roar_vio_to_stdio_read,  roar_vio_to_stdio_write,
                               roar_vio_to_stdio_lseek, roar_vio_to_stdio_close);
#else
 return NULL;
#endif
}
/*! \brief
* creates a FILE * from the fd passed by the accept thread.
* This operation is potentially expensive (certificate verification),
* so we do it in the child thread context.
*
* \note must decrement ref count before returning NULL on error
*/
static void *handle_tcptls_connection(void *data)
{
	struct ast_tcptls_session_instance *tcptls_session = data;
#ifdef DO_SSL
	int (*ssl_setup)(SSL *) = (tcptls_session->client) ? SSL_connect : SSL_accept;
	int ret;
	char err[256];
#endif

	/* TCP/TLS connections are associated with external protocols, and
	 * should not be allowed to execute 'dangerous' functions. This may
	 * need to be pushed down into the individual protocol handlers, but
	 * this seems like a good general policy.
	 */
	if (ast_thread_inhibit_escalations()) {
		ast_log(LOG_ERROR, "Failed to inhibit privilege escalations; killing connection\n");
		return NULL;
	}

	/*
	* open a FILE * as appropriate.
	*/
	if (!tcptls_session->parent->tls_cfg) {
		if ((tcptls_session->f = fdopen(tcptls_session->fd, "w+"))) {
			if(setvbuf(tcptls_session->f, NULL, _IONBF, 0)) {
				ast_tcptls_close_session_file(tcptls_session);
			}
		}
	}
#ifdef DO_SSL
	else if ( (tcptls_session->ssl = SSL_new(tcptls_session->parent->tls_cfg->ssl_ctx)) ) {
		SSL_set_fd(tcptls_session->ssl, tcptls_session->fd);
		if ((ret = ssl_setup(tcptls_session->ssl)) <= 0) {
			ast_verb(2, "Problem setting up ssl connection: %s\n", ERR_error_string(ERR_get_error(), err));
		} else {
#if defined(HAVE_FUNOPEN)	/* the BSD interface */
			tcptls_session->f = funopen(tcptls_session->ssl, ssl_read, ssl_write, NULL, ssl_close);

#elif defined(HAVE_FOPENCOOKIE)	/* the glibc/linux interface */
			static const cookie_io_functions_t cookie_funcs = {
				ssl_read, ssl_write, NULL, ssl_close
			};
			tcptls_session->f = fopencookie(tcptls_session->ssl, "w+", cookie_funcs);
#else
			/* could add other methods here */
			ast_debug(2, "no tcptls_session->f methods attempted!\n");
#endif
			if ((tcptls_session->client && !ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_DONT_VERIFY_SERVER))
				|| (!tcptls_session->client && ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_VERIFY_CLIENT))) {
				X509 *peer;
				long res;
				peer = SSL_get_peer_certificate(tcptls_session->ssl);
				if (!peer)
					ast_log(LOG_WARNING, "No peer SSL certificate\n");
				res = SSL_get_verify_result(tcptls_session->ssl);
				if (res != X509_V_OK)
					ast_log(LOG_ERROR, "Certificate did not verify: %s\n", X509_verify_cert_error_string(res));
				if (!ast_test_flag(&tcptls_session->parent->tls_cfg->flags, AST_SSL_IGNORE_COMMON_NAME)) {
					ASN1_STRING *str;
					unsigned char *str2;
					X509_NAME *name = X509_get_subject_name(peer);
					int pos = -1;
					int found = 0;

					for (;;) {
						/* Walk the certificate to check all available "Common Name" */
						/* XXX Probably should do a gethostbyname on the hostname and compare that as well */
						pos = X509_NAME_get_index_by_NID(name, NID_commonName, pos);
						if (pos < 0)
							break;
						str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, pos));
						ASN1_STRING_to_UTF8(&str2, str);
						if (str2) {
							if (!strcasecmp(tcptls_session->parent->hostname, (char *) str2))
								found = 1;
							ast_debug(3, "SSL Common Name compare s1='%s' s2='%s'\n", tcptls_session->parent->hostname, str2);
							OPENSSL_free(str2);
						}
						if (found)
							break;
					}
					if (!found) {
						ast_log(LOG_ERROR, "Certificate common name did not match (%s)\n", tcptls_session->parent->hostname);
						if (peer) {
							X509_free(peer);
						}
						ast_tcptls_close_session_file(tcptls_session);
						ao2_ref(tcptls_session, -1);
						return NULL;
					}
				}
				if (peer)
					X509_free(peer);
			}
		}
		if (!tcptls_session->f)	/* no success opening descriptor stacking */
			SSL_free(tcptls_session->ssl);
   }
#endif /* DO_SSL */

	if (!tcptls_session->f) {
		ast_tcptls_close_session_file(tcptls_session);
		ast_log(LOG_WARNING, "FILE * open failed!\n");
#ifndef DO_SSL
		if (tcptls_session->parent->tls_cfg) {
			ast_log(LOG_WARNING, "Attempted a TLS connection without OpenSSL support.  This will not work!\n");
		}
#endif
		ao2_ref(tcptls_session, -1);
		return NULL;
	}

	if (tcptls_session->parent->worker_fn) {
		return tcptls_session->parent->worker_fn(tcptls_session);
	} else {
		return tcptls_session;
	}
}
Exemple #22
0
/* {{{ php_stream_cast */
PHPAPI int _php_stream_cast(php_stream *stream, int castas, void **ret, int show_err)
{
	int flags = castas & PHP_STREAM_CAST_MASK;
	castas &= ~PHP_STREAM_CAST_MASK;

	/* synchronize our buffer (if possible) */
	if (ret && castas != PHP_STREAM_AS_FD_FOR_SELECT) {
		php_stream_flush(stream);
		if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
			zend_off_t dummy;

			stream->ops->seek(stream, stream->position, SEEK_SET, &dummy);
			stream->readpos = stream->writepos = 0;
		}
	}

	/* filtered streams can only be cast as stdio, and only when fopencookie is present */

	if (castas == PHP_STREAM_AS_STDIO) {
		if (stream->stdiocast) {
			if (ret) {
				*(FILE**)ret = stream->stdiocast;
			}
			goto exit_success;
		}

		/* if the stream is a stdio stream let's give it a chance to respond
		 * first, to avoid doubling up the layers of stdio with an fopencookie */
		if (php_stream_is(stream, PHP_STREAM_IS_STDIO) &&
			stream->ops->cast &&
			!php_stream_is_filtered(stream) &&
			stream->ops->cast(stream, castas, ret) == SUCCESS
		) {
			goto exit_success;
		}

#if HAVE_FOPENCOOKIE
		/* if just checking, say yes we can be a FILE*, but don't actually create it yet */
		if (ret == NULL) {
			goto exit_success;
		}

		{
			char fixed_mode[5];
			php_stream_mode_sanitize_fdopen_fopencookie(stream, fixed_mode);
			*(FILE**)ret = fopencookie(stream, fixed_mode, PHP_STREAM_COOKIE_FUNCTIONS);
		}

		if (*ret != NULL) {
			zend_off_t pos;

			stream->fclose_stdiocast = PHP_STREAM_FCLOSE_FOPENCOOKIE;

			/* If the stream position is not at the start, we need to force
			 * the stdio layer to believe it's real location. */
			pos = php_stream_tell(stream);
			if (pos > 0) {
				zend_fseek(*ret, pos, SEEK_SET);
			}

			goto exit_success;
		}

		/* must be either:
			a) programmer error
			b) no memory
			-> lets bail
		*/
		php_error_docref(NULL, E_ERROR, "fopencookie failed");
		return FAILURE;
#endif

		if (!php_stream_is_filtered(stream) && stream->ops->cast && stream->ops->cast(stream, castas, NULL) == SUCCESS) {
			if (FAILURE == stream->ops->cast(stream, castas, ret)) {
				return FAILURE;
			}
			goto exit_success;
		} else if (flags & PHP_STREAM_CAST_TRY_HARD) {
			php_stream *newstream;

			newstream = php_stream_fopen_tmpfile();
			if (newstream) {
				int retcopy = php_stream_copy_to_stream_ex(stream, newstream, PHP_STREAM_COPY_ALL, NULL);

				if (retcopy != SUCCESS) {
					php_stream_close(newstream);
				} else {
					int retcast = php_stream_cast(newstream, castas | flags, (void **)ret, show_err);

					if (retcast == SUCCESS) {
						rewind(*(FILE**)ret);
					}

					/* do some specialized cleanup */
					if ((flags & PHP_STREAM_CAST_RELEASE)) {
						php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
					}

					/* TODO: we probably should be setting .stdiocast and .fclose_stdiocast or
					 * we may be leaking the FILE*. Needs investigation, though. */
					return retcast;
				}
			}
		}
	}

	if (php_stream_is_filtered(stream)) {
		php_error_docref(NULL, E_WARNING, "cannot cast a filtered stream on this system");
		return FAILURE;
	} else if (stream->ops->cast && stream->ops->cast(stream, castas, ret) == SUCCESS) {
		goto exit_success;
	}

	if (show_err) {
		/* these names depend on the values of the PHP_STREAM_AS_XXX defines in php_streams.h */
		static const char *cast_names[4] = {
			"STDIO FILE*",
			"File Descriptor",
			"Socket Descriptor",
			"select()able descriptor"
		};

		php_error_docref(NULL, E_WARNING, "cannot represent a stream of type %s as a %s", stream->ops->label, cast_names[castas]);
	}

	return FAILURE;

exit_success:

	if ((stream->writepos - stream->readpos) > 0 &&
		stream->fclose_stdiocast != PHP_STREAM_FCLOSE_FOPENCOOKIE &&
		(flags & PHP_STREAM_CAST_INTERNAL) == 0
	) {
		/* the data we have buffered will be lost to the third party library that
		 * will be accessing the stream.  Emit a warning so that the end-user will
		 * know that they should try something else */

		php_error_docref(NULL, E_WARNING, ZEND_LONG_FMT " bytes of buffered data lost during stream conversion!", (zend_long)(stream->writepos - stream->readpos));
	}

	if (castas == PHP_STREAM_AS_STDIO && ret) {
		stream->stdiocast = *(FILE**)ret;
	}

	if (flags & PHP_STREAM_CAST_RELEASE) {
		php_stream_free(stream, PHP_STREAM_FREE_CLOSE_CASTED);
	}

	return SUCCESS;

}
Exemple #23
0
    FILE *stream;
    cookie_io_functions_t toxstream_func = {
        .read	= NULL,
        .write	= toxstream_write,
        .seek	= NULL,
        .close	= NULL
    };

    struct toxstream_cookie mycookie = {
        .tox		= tox,
                .friend_number	= friend_number,
                .type		= TOX_MESSAGE_TYPE_NORMAL,
    };

    stream = fopencookie(&mycookie, "w", toxstream_func);
    if (stream == NULL) {
        perror("fopencookie");
        return;
    };

    static bool xdcc = false;
    if (xdcc) {
        execute(tox, (char *)message, friend_number);
    }

    ydebug("Recv: %s", message);

    struct suit_info *si = user_data;
    struct list_head *friends_info = &si->friends_info;
    struct friend_info *f = friend_info_by_friend_number(friends_info, friend_number);
Exemple #24
0
FILE *
fa_fopen(fa_handle_t *fh, int doclose)
{
  return fopencookie(fh, "rb", doclose ? fn_full : fn_noclose);
}
Exemple #25
0
FILE *
ccstreams_fmemopen(char **ptr, size_t *size, const char *mode)
{
  assert(ptr != NULL);
  assert(size != NULL);

  int status = 0;
  FILE *stream = NULL;
  struct mem_cookie *cookie = NULL;
  cookie_io_functions_t mem_io_funcs = {
    .read  = mem_read,
    .write = mem_write,
    .seek  = mem_seek,
    .close = mem_close,
  };
  size_t mode_length = strlen(mode);
  int extra = 0;
  int create = 0;
  int created = 0;
  int append = 0;
  int truncate = 0;
  int end = 0;

  if (mode_length > 1) {
    if (mode[1] == 'b') {
      if (mode_length > 2 && mode[2] == '+') {
        extra = 2;
      }
    }
    else if (mode[1] == '+') {
      extra = 1;
    }
  }

  switch (mode[0]) {
    case 'w':
      if (extra) {
        create = 1;
      }
      truncate = 1;
      break;
    case 'a':
      if (!extra) {
        end = 1;
      }
      create = 1;
      append = 1;
      break;
  }

  if (create && *ptr == NULL) {
    *ptr = malloc(0);
    if (*ptr == NULL) {
      status = -1;
      goto cleanup;
    }

    created = 1;
    *size = 0;
  }

  if (*ptr == NULL) {
    status = -1;
    errno = ENOENT;
    goto cleanup;
  }

  if (truncate & !created) {
    free(*ptr);
    *ptr = malloc(0);
    if (*ptr == NULL) {
      status = -1;
      goto cleanup;
    }

    *size = 0;
  }

  cookie = malloc(sizeof(*cookie));
  if (cookie == NULL) {
    status = -1;
    goto cleanup;
  }

  status = mem_cookie_init(cookie, ptr, size, append);
  if (status != 0) {
    status = -1;
    goto cleanup;
  }

  stream = fopencookie(cookie, mode, mem_io_funcs);
  if (stream == NULL) {
    status = -1;
    goto cleanup;
  }

  if (end) {
    status = fseek(stream, 0, SEEK_END);
    if (status != 0) {
      status = -1;
      goto cleanup;
    }
  }

cleanup:
  if (status != 0) {
    mem_cookie_fini(cookie);
    free(cookie);

    if (created) {
      free(*ptr);
      *ptr = NULL;
    }
  }

  return stream;
}
Exemple #26
0
/*=export_func ag_fmemopen
 *
 *  what:  Open a stream to a string
 *
 *  arg: + void*   + buf  + buffer to use for i/o +
 *  arg: + ssize_t + len  + size of the buffer +
 *  arg: + char*   + mode + mode string, a la fopen(3C) +
 *
 *  ret-type:  FILE*
 *  ret-desc:  a stdio FILE* pointer
 *
 *  err:  NULL is returned and errno is set to @code{EINVAL} or @code{ENOSPC}.
 *
 *  doc:
 *
 *  This function requires underlying @var{libc} functionality:
 *  either @code{fopencookie(3GNU)} or @code{funopen(3BSD)}.
 *
 *  If @var{buf} is @code{NULL}, then a buffer is allocated.  The initial
 *  allocation is @var{len} bytes.  If @var{len} is less than zero, then the
 *  buffer will be reallocated as more space is needed.  Any allocated
 *  memory is @code{free()}-ed when @code{fclose(3C)} is called.
 *
 *  If @code{buf} is not @code{NULL}, then @code{len} must not be zero.
 *  It may still be less than zero to indicate that the buffer may
 *  be reallocated.
 *
 *  The mode string is interpreted as follows.  If the first character of
 *  the mode is:
 *
 *  @table @code
 *  @item a
 *  Then the string is opened in "append" mode.  In binary mode, "appending"
 *  will begin from the end of the initial buffer.  Otherwise, appending will
 *  start at the first NUL character in the initial buffer (or the end of the
 *  buffer if there is no NUL character).  Do not use fixed size buffers
 *  (negative @var{len} lengths) in append mode.
 *
 *  @item w
 *  Then the string is opened in "write" mode.  Any initial buffer is presumed
 *  to be empty.
 *
 *  @item r
 *  Then the string is opened in "read" mode.
 *  @end table
 *
 *  @noindent
 *  If it is not one of these three, the open fails and @code{errno} is
 *  set to @code{EINVAL}.  These initial characters may be followed by:
 *
 *  @table @code
 *  @item +
 *  The buffer is marked as updatable and both reading and writing is enabled.
 *
 *  @item b
 *  The I/O is marked as "binary" and a trailing NUL will not be inserted
 *  into the buffer.  Without this mode flag, one will be inserted after the
 *  @code{EOF}, if it fits.  It will fit if the buffer is extensible (the
 *  provided @var{len} was negative).  This mode flag has no effect if
 *  the buffer is opened in read-only mode.
 *
 *  @item x
 *  This is ignored.
 *  @end table
 *
 *  @noindent
 *  Any other letters following the inital 'a', 'w' or 'r' will cause an error.
=*/
FILE *
ag_fmemopen(void * buf, ssize_t len, char const * mode)
{
    fmem_cookie_t *pFMC;

    {
        mode_bits_t bits;

        if (fmem_getmode(mode, &bits) != 0) {
            return NULL;
        }

        pFMC = malloc(sizeof(fmem_cookie_t));
        if (pFMC == NULL) {
            errno = ENOMEM;
            return NULL;
        }

        pFMC->mode = bits;
    }

    /*
     *  Two more mode bits that do not come from the mode string:
     *  a negative size implies fixed size buffer and a NULL
     *  buffer pointer means we must allocate (and free) it.
     */
    if (len <= 0) {
        /*
         *  We only need page size if we might extend an allocation.
         */
        len = -len;
        pFMC->pg_size = getpagesize();
    }

    else {
        pFMC->mode |= FLAG_BIT(fixed_size);
    }

    if (buf != NULL) {
        if (! fmem_config_user_buf(pFMC, buf, len))
            return NULL;

    } else if ((pFMC->mode & (FLAG_BIT(append) | FLAG_BIT(truncate))) == 0) {
        /*
         *  Not appending and not truncating.  We must be reading.
         *  We also have no user supplied buffer.  Nonsense.
         */
        errno = EINVAL;
        free(pFMC);
        return NULL;
    }

    else if (! fmem_alloc_buf(pFMC, len))
        return NULL;

#ifdef TEST_FMEMOPEN
    saved_cookie = pFMC;
#endif

    {
        FILE * res;

        cookie_read_function_t* pRd = (pFMC->mode & FLAG_BIT(read))
            ?  (cookie_read_function_t*)fmem_read  : NULL;
        cookie_write_function_t* pWr = (pFMC->mode & FLAG_BIT(write))
            ? (cookie_write_function_t*)fmem_write : NULL;

#ifdef HAVE_FOPENCOOKIE
        cookie_io_functions_t iof;
        iof.read  = pRd;
        iof.write = pWr;
        iof.seek  = fmem_seek;
        iof.close = fmem_close;

        res = fopencookie(pFMC, mode, iof);
#else
        res = funopen(pFMC, pRd, pWr, fmem_seek, fmem_close);
#endif
        if (res == NULL)
            return res;

        if (++map_ct >= map_alloc_ct) {
            void * p = (map_alloc_ct > 0)
                ? realloc((void *)map, (map_alloc_ct += 4) * sizeof(*map))
                : malloc((map_alloc_ct = 4) * sizeof(*map));

            if (p == NULL) {
                fclose(res);
                errno = ENOMEM; /* "fclose" set it to "EINVAL". */
                return NULL;
            }

            map = p;
        }

        {
            cookie_fp_map_t * p = (void *)(map + map_ct - 1);
            p->fp = res;
            p->cookie = pFMC;
        }

        return res;
    }
}
Exemple #27
0
int perform_test(struct np_test* tests, struct np_test_capab* global_capabs, struct np_test_var* global_vars, const struct nc_cpblts* capabs, FILE* output) {
	int test_no, cmd_filefd, i, test_fail, fd, size;
	char* cmd_file_content, *cmd_file = NULL, *msg, *cmd, *cmd_output_file = NULL, *result_file;
	FILE* file_cookie;
	struct np_test_cmd* cmd_struct;
	cookie_io_functions_t file_cookie_funcs = {.read = NULL, .write = NULL, .seek = NULL, .close = NULL};

	if (test_capab_check(capabs, global_capabs, &msg) != EXIT_SUCCESS) {
		fprintf(output, "FAIL: Test global capabilities (%s)\n", msg);
		free(msg);
		return EXIT_FAILURE;
	}
	fprintf(output, " OK : Test global capabilities\n");

	nc_callback_error_reply(clb_test_error);
	file_cookie = fopencookie(NULL, "r+", file_cookie_funcs);

	for (; tests != NULL; tests = tests->next) {
		/*
		 * test
		 */

		if (test_capab_check(capabs, tests->required_capabs, &msg) != EXIT_SUCCESS) {
			fprintf(output, "FAIL: Test \"%s\" capabs (%s)\n", tests->name, msg);
			free(msg);
			continue;
		}

		test_fail = 0;

		for (test_no = 0; test_no < tests->count && !test_fail; ++test_no) {
			/*
			 * one test execution
			 */

			for (cmd_struct = tests->cmds; cmd_struct != NULL; cmd_struct = cmd_struct->next) {
				/*
				 * test execution single command
				 */

				if (cmd_struct->file != NULL) {
					/*
					 * command with file
					 */

					cmd_file_content = strdup(cmd_struct->file);

					/* file test var substitution */
					test_file_var_subst(&cmd_file_content, tests->vars, test_no);

					/* file global var substitution */
					test_file_var_subst(&cmd_file_content, global_vars, test_no);

					asprintf(&cmd_file, "/tmp/tmpXXXXXX.xml");
					cmd_filefd = mkstemps(cmd_file, 4);
					if (cmd_filefd == -1) {
						fprintf(output, "INTERNAL ERROR: Test \"%s\" #%d cmd \"%s\": mkstemps: %s\n", tests->name, test_no+1, cmd_struct->cmd, strerror(errno));
						free(cmd_file_content);
						free(cmd_file);
						cmd_file = NULL;
						test_fail = 1;
						break;
					}
					if (write(cmd_filefd, cmd_file_content, strlen(cmd_file_content)) < strlen(cmd_file_content)) {
						fprintf(output, "INTERNAL ERROR: Test \"%s\" #%d cmd \"%s\": write: %s\n", tests->name, test_no+1, cmd_struct->cmd, strerror(errno));
						free(cmd_file_content);
						free(cmd_file);
						cmd_file = NULL;
						test_fail = 1;
						break;
					}
					close(cmd_filefd);
					free(cmd_file_content);
				}

				cmd = strdup(cmd_struct->cmd);
				test_cmd_subst_file(&cmd, cmd_file);
				free(cmd_file);
				cmd_file = NULL;

				/* find the command */
				for (i = 0; commands[i].name != NULL; ++i) {
					if (strncmp(cmd, commands[i].name, strlen(commands[i].name)) == 0 && cmd[strlen(commands[i].name)] == ' ') {
						break;
					}
				}
				if (commands[i].name == NULL) {
					fprintf(output, "FAIL: Test \"%s\" ", tests->name);
					if (tests->count > 1) {
						fprintf(output, "#%d ", test_no+1);
					}
					fprintf(output, "cmd \"%s\": command not found\n", cmd_struct->cmd);
					free(cmd);
					test_fail = 1;
					break;
				}

				/* make the command output into a file */
				if (cmd_struct->result_file != NULL) {
					asprintf(&cmd_output_file, "/tmp/tmpXXXXXX.xml");
					close(mkstemps(cmd_output_file, 4));

					cmd = realloc(cmd, strlen(cmd)+strlen(" --out ")+strlen(cmd_output_file)+1);
					strcat(cmd, " --out ");
					strcat(cmd, cmd_output_file);
				}

				/* finally execute the command */
				if (commands[i].func(cmd, NULL, file_cookie, file_cookie) != EXIT_SUCCESS) {
					fprintf(output, "COMMAND FAIL: Test \"%s\" ", tests->name);
					if (tests->count > 1) {
						fprintf(output, "#%d ", test_no+1);
					}
					fprintf(output, "cmd \"%s\"\n", cmd_struct->cmd);
					free(cmd);
					free(cmd_output_file);
					cmd_output_file = NULL;
					test_fail = 1;
					break;
				}

				/* check result */
				if (cmd_struct->result_err_tag != NULL) {
					/* error result */
					if (error_tag == NULL) {
						fprintf(output, "FAIL: Test \"%s\" ", tests->name);
						if (tests->count > 1) {
							fprintf(output, "#%d ", test_no+1);
						}
						fprintf(output, "cmd \"%s\": no error\n", cmd_struct->cmd);
						free(cmd);
						test_fail = 1;
						break;
					} else if (strcmp(cmd_struct->result_err_tag, "any") == 0) {
						fprintf(output, "INFO: Test \"%s\" ", tests->name);
						if (tests->count > 1) {
							fprintf(output, "#%d ", test_no+1);
						}
						fprintf(output, "cmd \"%s\": error %s", cmd_struct->cmd, error_tag);
						if (error_info != NULL) {
							fprintf(output, " - %s\n", error_info);
						}
						fprintf(output, " (%s)\n", error_message);
					} else if (strcmp(cmd_struct->result_err_tag, error_tag) != 0) {
						fprintf(output, "FAIL: Test \"%s\" ", tests->name);
						if (tests->count > 1) {
							fprintf(output, "#%d ", test_no+1);
						}
						fprintf(output, "cmd \"%s\": wrong error (%s instead %s)\n", cmd_struct->cmd, error_tag, cmd_struct->result_err_tag);
						free(error_tag);
						error_tag = NULL;
						free(error_message);
						error_message = NULL;
						free(error_info);
						error_info = NULL;
						free(cmd);
						test_fail = 1;
						break;
					}

					if (cmd_struct->result_err_msg != NULL && strcmp(cmd_struct->result_err_msg, error_message) != 0) {
						fprintf(output, "FAIL: Test \"%s\" ", tests->name);
						if (tests->count > 1) {
							fprintf(output, "#%d ", test_no+1);
						}
						fprintf(output, "cmd \"%s\": wrong error message (%s instead %s)\n", cmd_struct->cmd, error_message, cmd_struct->result_err_msg);
						free(error_tag);
						error_tag = NULL;
						free(error_message);
						error_message = NULL;
						free(error_info);
						error_info = NULL;
						free(cmd);
						test_fail = 1;
						break;
					}

					free(error_tag);
					error_tag = NULL;
					free(error_message);
					error_message = NULL;
					free(error_info);
					error_info = NULL;
				} else {
					/* success result */
					if (error_tag != NULL) {
						fprintf(output, "FAIL: Test \"%s\" ", tests->name);
						if (tests->count > 1) {
							fprintf(output, "#%d ", test_no+1);
						}
						fprintf(output, "cmd \"%s\": error %s (%s)\n", cmd_struct->cmd, error_tag, error_message);
						free(error_tag);
						error_tag = NULL;
						free(error_message);
						error_message = NULL;
						free(error_info);
						error_info = NULL;
						free(cmd);
						test_fail = 1;
						break;
					}

					if (cmd_struct->result_file != NULL) {
						/* file result */
						if (cmd_output_file == NULL) {
							fprintf(output, "INTERNAL ERROR: Test \"%s\" #%d cmd \"%s\": cmd_output_file is NULL\n", tests->name, test_no+1, cmd_struct->cmd);
							free(cmd);
							test_fail = 1;
							break;
						}

						if ((fd = open(cmd_output_file, O_RDONLY)) == -1 || (size = lseek(fd, 0, SEEK_END)) == -1) {
							fprintf(output, "INTERNAL ERROR: Test \"%s\" #%d cmd \"%s\": cmd output file error (%s)\n", tests->name, test_no+1, cmd_struct->cmd, strerror(errno));
							free(cmd);
							free(cmd_output_file);
							cmd_output_file = NULL;
							test_fail = 1;
							break;
						}
						unlink(cmd_output_file);
						free(cmd_output_file);
						cmd_output_file = NULL;
						lseek(fd, 0, SEEK_SET);
						result_file = malloc(size+1);
						result_file[size] = '\0';

						if (read(fd, result_file, size) < size) {
							fprintf(output, "INTERNAL ERROR: Test \"%s\" #%d cmd \"%s\": cmd output file read error\n", tests->name, test_no+1, cmd_struct->cmd);
							free(cmd);
							free(result_file);
							test_fail = 1;
							break;
						}
						close(fd);

						if (test_xmlfile_cmp(result_file, cmd_struct->result_file, &msg) != EXIT_SUCCESS) {
							fprintf(output, "FAIL: Test \"%s\" ", tests->name);
							if (tests->count > 1) {
								fprintf(output, "#%d ", test_no+1);
							}
							fprintf(output, "cmd \"%s\": output file differs from the expected result (%s)\n", cmd_struct->cmd, msg);
							free(msg);
							free(result_file);
							free(cmd);
							test_fail = 1;
							break;
						}

						free(result_file);
					}
				}

				free(cmd);
			}
		}

		if (!test_fail) {
			if (tests->count == 1) {
				fprintf(output, " OK : Test \"%s\"\n", tests->name);
			} else {
				fprintf(output, " OK : Test \"%s\" #1-%d\n", tests->name, tests->count);
			}
		}
	}

	fclose(file_cookie);
	nc_callback_error_reply(clb_error_print);
	return EXIT_SUCCESS;
}
Exemple #28
0
int main(int argc, char** argv) {
	printf("sizeof(__int16_t)=%d\n", sizeof(__int16_t));
	printf("sizeof(__int32_t)=%d\n", sizeof(__int32_t));
	printf("sizeof(__int64_t)=%d\n", sizeof(__int64_t));
	//printf("sizeof(cell_t)=%d\n", sizeof(cell_t));
	printf("sizeof(char)=%d\n", sizeof(char));
	printf("sizeof(char_p)=%d\n", sizeof(char*));
	printf("sizeof(dev_t)=%d\n", sizeof(dev_t));
	printf("sizeof(double)=%d\n", sizeof(double));
	printf("sizeof(float)=%d\n", sizeof(float));
	printf("sizeof(fpos_t)=%d\n", sizeof(fpos_t));
	printf("sizeof(int16_t)=%d\n", sizeof(int16_t));
	printf("sizeof(int32_t)=%d\n", sizeof(int32_t));
	printf("sizeof(int64_t)=%d\n", sizeof(int64_t));
	printf("sizeof(int8_t)=%d\n", sizeof(int8_t));
	printf("sizeof(int)=%d\n", sizeof(int));
	printf("sizeof(intmax_t)=%d\n", sizeof(intmax_t));
	printf("sizeof(intptr_t)=%d\n", sizeof(intptr_t));
	printf("sizeof(long)=%d\n", sizeof(long));
	printf("sizeof(long double)=%d\n", sizeof(long double));
	printf("sizeof(long long)=%d\n", sizeof(long long));
	printf("sizeof(long long int)=%d\n", sizeof(long long int));
	printf("sizeof(mode_t)=%d\n", sizeof(mode_t));
#ifdef INCLUDE_LFS_ONLY_TYPES
	printf("sizeof(off64_t)=%d\n", sizeof(off64_t));
#endif
	printf("sizeof(off_t)=%d\n", sizeof(off_t));
	printf("sizeof(pid_t)=%d\n", sizeof(pid_t));
	printf("sizeof(ptrdiff_t)=%d\n", sizeof(ptrdiff_t));
	printf("sizeof(short)=%d\n", sizeof(short));
	printf("sizeof(signed char)=%d\n", sizeof(signed char));
	printf("sizeof(size_t)=%d\n", sizeof(size_t));
	printf("sizeof(socklen_t)=%d\n", sizeof(socklen_t));
	printf("sizeof(ssize_t)=%d\n", sizeof(ssize_t));

	{
	    struct stat x;
	    FILE *fp;

	    fp = fopen("/dev/null", "w");
	    if (fp != NULL) {
		printf("sizeof(stat_st_size)=%d\n", sizeof(x.st_size));
		fclose(fp);
	    }
	}
	//printf("sizeof(struct_iovec)=%d\n", sizeof(struct_iovec));
	printf("sizeof(time_t)=%d\n", sizeof(time_t));
	printf("sizeof(uint16_t)=%d\n", sizeof(uint16_t));
	printf("sizeof(uint32_t)=%d\n", sizeof(uint32_t));
	printf("sizeof(uint64_t)=%d\n", sizeof(uint64_t));
	printf("sizeof(uint8_t)=%d\n", sizeof(uint8_t));
	printf("sizeof(uintmax_t)=%d\n", sizeof(uintmax_t));
	printf("sizeof(uintptr_t)=%d\n", sizeof(uintptr_t));
	printf("sizeof(unsigned char)=%d\n", sizeof(unsigned char));
	printf("sizeof(unsigned int)=%d\n", sizeof(unsigned int));
	printf("sizeof(unsigned long)=%d\n", sizeof(unsigned long));
	printf("sizeof(unsigned short)=%d\n", sizeof(unsigned short));
	printf("sizeof(void_p)=%d\n", sizeof(void*));
	printf("sizeof(voidp)=%d\n", sizeof(void*));
	printf("sizeof(mbstate_t)=%d\n", sizeof(mbstate_t));
	printf("sizeof(__off64_t)=%d\n", sizeof(__off64_t));

#ifdef __cplusplus
	{
	    printf("cv_type_of_bool=");
    	    bool x = true;
	    if ((bool)(-x) >= 0)
		printf("unsigned ");
	    if (sizeof(x) == sizeof(int))
		printf("int\n");
	    else if (sizeof(x) == sizeof(char))
		printf("char\n");
	    else if (sizeof(x) == sizeof(short))
		printf("short\n");
	    else if (sizeof(x) == sizeof(long))
		printf("long\n");
	}
#endif

	{
	    struct pollfd myfds;
	    int code;
	    myfds.fd = 0;
	    myfds.events = POLLIN;
	    code = poll(&myfds, 1, 100);
	    printf("cf_cv_working_poll=%s\n", (code>=0) ? "yes" : "no");
	}

	{
	    struct timespec ts1, ts2;
	    int code;
	    ts1.tv_sec  = 0;
	    ts1.tv_nsec = 750000000;
	    ts2.tv_sec  = 0;
	    ts2.tv_nsec = 0;
	    errno = 0;
	    code = nanosleep(&ts1, &ts2); /* on failure errno is ENOSYS. */
	    printf("cf_cv_func_nanosleep=%s\n", (code==0) ? "yes" : "no");
	}

	{
	    int n = write(1, TEXT, sizeof(TEXT)-1);
	    printf("\nac_cv_write_stdout=%s\n", (n == sizeof(TEXT)-1) ? "yes" : "no");
	}

#ifdef __cplusplus
	{
	    cookie_io_functions_t funcs = {reader, writer, seeker, closer};
	    struct cookiedata g = { 0 };
	    FILE *fp = fopencookie(&g, "r", funcs);
	    printf("cookie_io_functions_use_off64_t=%s\n", (fp && fseek(fp, 8192, SEEK_SET) == 0 && g.pos == 8192) ? "yes" : "no");
	}
#endif

	{
	    struct stat s, t;
	    int code =
#if 1
	    0;
#else
	    // doesn't compile so no
	    (
		stat ("conftestdata", &s) == 0
		&& utime("conftestdata", (long *)0) == 0
		&& stat("conftestdata", &t) == 0
		&& t.st_mtime >= s.st_mtime
		&& t.st_mtime - s.st_mtime < 120
	    );
#endif
	    printf("ac_cv_func_utime_null=%s\n", code ? "yes" : "no");
	}

	printf("ac_cv_c_stack_direction=%d\n", find_stack_direction());

	{
	    DIR *dir;
	    char entry[sizeof(struct dirent)+PATH_MAX];
	    struct dirent *pentry = (struct dirent *) &entry;
	    int code;

	    dir = opendir("/");
	    code = dir && (readdir_r(dir, (struct dirent *) entry, &pentry) == 0);
	    printf("ac_cv_what_readdir_r=%s\n", code ? "POSIX" : "none");
	}

#if 0
	{
	    char c0 = 0x40, c1 = 0x80, c2 = 0x81;
	    int code = memcmp(&c0, &c2, 1) < 0 && memcmp(&c1, &c2, 1) < 0;
	    printf("ac_cv_func_memcmp_clean=%s\n", code ? "yes" : "no");
	}
#endif

#if 0
	// doesn't compile so no
	int foo = res_ninit(NULL);
#endif

	{
	    int code = getgroups(0, 0) != -1;
	    printf("ac_cv_func_getgroups_works=%s\n", code ? "yes" : "no");
	}

	{
	    struct stat sbuf;
	    int code = (stat("", &sbuf) == 0);
	    printf("ac_cv_func_stat_empty_string_bug=%s\n", code ? "yes" : "no");
	}

	{
	    struct stat sbuf;
	    int code = (lstat("", &sbuf) == 0);
	    printf("ac_cv_func_lstat_empty_string_bug=%s\n", code ? "yes" : "no");
	}

	{
	    struct stat sbuf;
	    int code = (lstat("conftest.sym/", &sbuf) == 0);
	    printf("ac_cv_func_lstat_dereferences_slashed_symlink=%s (you should do 'echo > conftest.file && ln -s conftest.file conftest.sym' before running this test)\n", code ? "yes" : "no");
	}

	{
	    char buffer[10000];
	    struct passwd pwd;
	    struct passwd* pwdp = &pwd;
	    int error = getpwuid_r(0, &pwd, (char*)&buffer, sizeof(buffer), &pwdp);
	    int code = (errno != ENOSYS);
	    printf("ac_cv_func_getpwuid_r=%s\n", code ? "yes" : "no");
	}

	{
	    int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
	    int code = (sfd >= 0);
	    if (code)
		close(sfd);
	    printf("wi_cv_unix_domain_sockets=%s\n", code ? "yes" : "no");
	}

	{
	    struct hostent *hp1, *hp2;
	    int code = 0;
	    hp1 = gethostbyname("ftp.ncftp.com");
	    if (hp1 == (struct hostent *)0) {
		hp2 = gethostbyname("www.ibm.com");
		if (hp2 == (struct hostent *)0)
		    code = 1;
	    }
	    printf("wi_cv_look_for_resolv=%s\n", code ? "yes" : "no");
	}

	{
	    char s[16];
	    int i, result, code;

	    for (i=0; i<(int)(sizeof(s)/sizeof(char)); i++)
		s[i] = 'x';
	    result = (int)snprintf(s + 1, 10, "%s %s!", "hello", "world");
	    if (s[10] != '\0')
		code = 1; /* did not force termination! */
	    else if (s[11] != 'x')
		code = 2; /* overflow! */
	    else if (s[0] != 'x')
		code = 3; /* underflow! */
	    else
		code = 0;

	    printf("wi_cv_snprintf_terminates=%s\n", (code==0) ? "yes" : "no");
	}

	{
	    char s[8];
	    int result = (int)snprintf(s, sizeof(s) - 1, "%d", 22);
	    printf("wi_cv_snprintf_returns_ptr=%s\n", (result == 2) ? "no" : "yes");
	}

#if 0
	{
	    //doesn't compile -> no
	    int test_SYS = SYS_ioprio_set;
	    int test_NR = _NR_ioprio_set;
	}
#endif

	{
	    /* The string "%2$d %1$d", with dollar characters protected from the shell's
	    dollar expansion (possibly an autoconf bug). */
	    static char format[] = { '%', '2', '$', 'd', ' ', '%', '1', '$', 'd', '\0' };
	    static char buf[100];
	    int code;

	    sprintf(buf, format, 33, 55);
	    code = (strcmp (buf, "55 33") == 0);
	    printf("gt_cv_func_printf_posix=%s\n", code ? "yes" : "no");
	}

	{
	    int code = ac_cv_c_c99_format();
	    printf("ac_cv_c_c99_format=%s\n", code==0 ? "yes" : "no");
	}

	{
	    int code = ac_cv_fread_reads_directories();
	    printf("ac_cv_fread_reads_directories=%s\n", code ? "yes" : "no");
	}

	{
	    int code = ac_cv_snprintf_returns_bogus();
	    printf("ac_cv_snprintf_returns_bogus=%s\n", code ? "yes" : "no");
	}

	{
		uint64_t i0;
		uint64_t i1;
		uint8_t c[8];
		double d;

		d = 8.642135e130;
		memcpy ((void *) &i0, (void *) &d, 8);

		i1 = i0;
		memcpy ((void *) c, (void *) &i1, 8);

		int code = (
			(c[0] == 0x2f) && (c[1] == 0x25)
			&& (c[2] == 0xc0) && (c[3] == 0xc7)
			&& (c[4] == 0x43) && (c[5] == 0x2b)
			&& (c[6] == 0x1f) && (c[7] == 0x5b)
		);

		printf("c_cv_fp_layout_need_nothing=%s\n", code ? "yes" : "no");
	}

}
Exemple #29
0
    cookie = cookie;            // -Wunused-parameter
    for (size_t i = 0; i < size; i++) {
        char c = buf[i];
        if (c == '\n')
            console_putc('\r');
        console_putc(c);
    }
    return size;
}

void setup_console_stdio(void)
{
    cookie_io_functions_t console_input_fns = {
        .read  = NULL,
        .write = NULL,
        .seek  = NULL,
        .close = NULL
    };
    cookie_io_functions_t console_output_fns = {
        .read  = NULL,
        .write = console_write,
        .seek  = NULL,
        .close = NULL
    };
    stdin  = fopencookie(NULL, "r", console_input_fns);
    stdout = fopencookie(NULL, "w", console_output_fns);
    stderr = fopencookie(NULL, "w", console_output_fns);
    setlinebuf(stdout);
    setbuf(stderr, NULL);
}
Exemple #30
-1
int
main (int argc, char** argv)
{
  cookie_io_functions_t fcts;
  char buf[1];
  FILE *f;

  fcts.read = cookieread;
  fcts.seek = cookieseek;
  fcts.close = cookieclose;
  fcts.write = cookiewrite;

  f = fopencookie (THE_COOKIE, "r+", fcts);

  fread (buf, 1, 1, f);
  fwrite (buf, 1, 1, f);
  fseek (f, 0, SEEK_CUR);
  fclose (f);

  if (cookieread_called == 0
      || cookiewrite_called == 0
      || cookieseek_called == 0
      || cookieclose_called == 0)
    ++errors;

  return errors != 0;
}