+/* Reads a file to a buffer. The allocated buffer is returned. Length of
+ the file read is returned to the return_len argument. */
+
+char *silc_file_readfile(const char *filename, uint32 *return_len)
+{
+ int fd;
+ char *buffer;
+ int filelen;
+
+ fd = silc_file_open(filename, O_RDONLY);
+ if (fd < 0) {
+ if (errno == ENOENT)
+ return NULL;
+ SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
+ return NULL;
+ }
+
+ filelen = lseek(fd, (off_t)0L, SEEK_END);
+ if (filelen < 0) {
+ close(fd);
+ return NULL;
+ }
+ if (lseek(fd, (off_t)0L, SEEK_SET) < 0) {
+ close(fd);
+ return NULL;
+ }
+
+ if (filelen < 0) {
+ SILC_LOG_ERROR(("Cannot open file %s: %s", filename, strerror(errno)));
+ close(fd);
+ return NULL;
+ }
+
+ buffer = silc_calloc(filelen + 1, sizeof(char));
+
+ if ((read(fd, buffer, filelen)) == -1) {
+ memset(buffer, 0, sizeof(buffer));
+ close(fd);
+ SILC_LOG_ERROR(("Cannot read from file %s: %s", filename,
+ strerror(errno)));
+ return NULL;
+ }
+
+ close(fd);
+ buffer[filelen] = EOF;
+
+ if (return_len)
+ *return_len = filelen;
+
+ return buffer;
+}
+