Rename pmhandle_t to alpm_handle_t
[pacman-ng.git] / lib / libalpm / util.c
blob991898e11c67f1edd450f6832f6488ea8834cf41
1 /*
2 * util.c
4 * Copyright (c) 2006-2011 Pacman Development Team <pacman-dev@archlinux.org>
5 * Copyright (c) 2002-2006 by Judd Vinet <jvinet@zeroflux.org>
6 * Copyright (c) 2005 by Aurelien Foret <orelien@chez.com>
7 * Copyright (c) 2005 by Christian Hamar <krics@linuxforum.hu>
8 * Copyright (c) 2006 by David Kimpe <dnaku@frugalware.org>
9 * Copyright (c) 2005, 2006 by Miklos Vajna <vmiklos@frugalware.org>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include "config.h"
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <stdarg.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <time.h>
35 #include <syslog.h>
36 #include <errno.h>
37 #include <limits.h>
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <sys/wait.h>
41 #include <locale.h> /* setlocale */
43 /* libarchive */
44 #include <archive.h>
45 #include <archive_entry.h>
47 #ifdef HAVE_LIBSSL
48 #include <openssl/md5.h>
49 #else
50 #include "md5.h"
51 #endif
53 /* libalpm */
54 #include "util.h"
55 #include "log.h"
56 #include "alpm.h"
57 #include "alpm_list.h"
58 #include "handle.h"
59 #include "trans.h"
61 #ifndef HAVE_STRSEP
62 /* This is a replacement for strsep which is not portable (missing on Solaris).
63 * Copyright (c) 2001 by François Gouget <fgouget_at_codeweavers.com> */
64 char* strsep(char** str, const char* delims)
66 char* token;
68 if(*str==NULL) {
69 /* No more tokens */
70 return NULL;
73 token=*str;
74 while(**str!='\0') {
75 if(strchr(delims,**str)!=NULL) {
76 **str='\0';
77 (*str)++;
78 return token;
80 (*str)++;
82 /* There is no other token */
83 *str=NULL;
84 return token;
86 #endif
88 int _alpm_makepath(const char *path)
90 return _alpm_makepath_mode(path, 0755);
93 /* does the same thing as 'mkdir -p' */
94 int _alpm_makepath_mode(const char *path, mode_t mode)
96 /* A bit of pointer hell here. Descriptions:
97 * orig - a copy of path so we can safely butcher it with strsep
98 * str - the current position in the path string (after the delimiter)
99 * ptr - the original position of str after calling strsep
100 * incr - incrementally generated path for use in stat/mkdir call
102 char *orig, *str, *ptr, *incr;
103 mode_t oldmask = umask(0000);
104 int ret = 0;
106 orig = strdup(path);
107 incr = calloc(strlen(orig) + 1, sizeof(char));
108 str = orig;
109 while((ptr = strsep(&str, "/"))) {
110 if(strlen(ptr)) {
111 /* we have another path component- append the newest component to
112 * existing string and create one more level of dir structure */
113 strcat(incr, "/");
114 strcat(incr, ptr);
115 if(access(incr, F_OK)) {
116 if(mkdir(incr, mode)) {
117 ret = 1;
118 break;
123 free(orig);
124 free(incr);
125 umask(oldmask);
126 return ret;
129 #define CPBUFSIZE 8 * 1024
131 int _alpm_copyfile(const char *src, const char *dest)
133 FILE *in, *out;
134 size_t len;
135 char *buf;
136 int ret = 0;
138 in = fopen(src, "rb");
139 if(in == NULL) {
140 return 1;
142 out = fopen(dest, "wb");
143 if(out == NULL) {
144 fclose(in);
145 return 1;
148 CALLOC(buf, (size_t)CPBUFSIZE, (size_t)1, ret = 1; goto cleanup;);
150 /* do the actual file copy */
151 while((len = fread(buf, 1, CPBUFSIZE, in))) {
152 size_t nwritten = 0;
153 nwritten = fwrite(buf, 1, len, out);
154 if((nwritten != len) || ferror(out)) {
155 ret = -1;
156 goto cleanup;
160 /* chmod dest to permissions of src, as long as it is not a symlink */
161 struct stat statbuf;
162 if(!stat(src, &statbuf)) {
163 if(! S_ISLNK(statbuf.st_mode)) {
164 fchmod(fileno(out), statbuf.st_mode);
166 } else {
167 /* stat was unsuccessful */
168 ret = 1;
171 cleanup:
172 fclose(in);
173 fclose(out);
174 FREE(buf);
175 return ret;
178 /* Trim whitespace and newlines from a string
180 char *_alpm_strtrim(char *str)
182 char *pch = str;
184 if(*str == '\0') {
185 /* string is empty, so we're done. */
186 return str;
189 while(isspace((unsigned char)*pch)) {
190 pch++;
192 if(pch != str) {
193 memmove(str, pch, (strlen(pch) + 1));
196 /* check if there wasn't anything but whitespace in the string. */
197 if(*str == '\0') {
198 return str;
201 pch = (str + (strlen(str) - 1));
202 while(isspace((unsigned char)*pch)) {
203 pch--;
205 *++pch = '\0';
207 return str;
210 /* Compression functions */
213 * @brief Unpack a specific file in an archive.
215 * @param handle the context handle
216 * @param archive the archive to unpack
217 * @param prefix where to extract the files
218 * @param filename a file within the archive to unpack
219 * @return 0 on success, 1 on failure
221 int _alpm_unpack_single(alpm_handle_t *handle, const char *archive,
222 const char *prefix, const char *filename)
224 alpm_list_t *list = NULL;
225 int ret = 0;
226 if(filename == NULL) {
227 return 1;
229 list = alpm_list_add(list, (void *)filename);
230 ret = _alpm_unpack(handle, archive, prefix, list, 1);
231 alpm_list_free(list);
232 return ret;
236 * @brief Unpack a list of files in an archive.
238 * @param handle the context handle
239 * @param archive the archive to unpack
240 * @param prefix where to extract the files
241 * @param list a list of files within the archive to unpack or NULL for all
242 * @param breakfirst break after the first entry found
244 * @return 0 on success, 1 on failure
246 int _alpm_unpack(alpm_handle_t *handle, const char *archive, const char *prefix,
247 alpm_list_t *list, int breakfirst)
249 int ret = 0;
250 mode_t oldmask;
251 struct archive *_archive;
252 struct archive_entry *entry;
253 char cwd[PATH_MAX];
254 int restore_cwd = 0;
256 if((_archive = archive_read_new()) == NULL) {
257 RET_ERR(handle, PM_ERR_LIBARCHIVE, 1);
260 archive_read_support_compression_all(_archive);
261 archive_read_support_format_all(_archive);
263 if(archive_read_open_filename(_archive, archive,
264 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
265 _alpm_log(handle, PM_LOG_ERROR, _("could not open file %s: %s\n"), archive,
266 archive_error_string(_archive));
267 RET_ERR(handle, PM_ERR_PKG_OPEN, 1);
270 oldmask = umask(0022);
272 /* save the cwd so we can restore it later */
273 if(getcwd(cwd, PATH_MAX) == NULL) {
274 _alpm_log(handle, PM_LOG_ERROR, _("could not get current working directory\n"));
275 } else {
276 restore_cwd = 1;
279 /* just in case our cwd was removed in the upgrade operation */
280 if(chdir(prefix) != 0) {
281 _alpm_log(handle, PM_LOG_ERROR, _("could not change directory to %s (%s)\n"),
282 prefix, strerror(errno));
283 ret = 1;
284 goto cleanup;
287 while(archive_read_next_header(_archive, &entry) == ARCHIVE_OK) {
288 const struct stat *st;
289 const char *entryname; /* the name of the file in the archive */
291 st = archive_entry_stat(entry);
292 entryname = archive_entry_pathname(entry);
294 if(S_ISREG(st->st_mode)) {
295 archive_entry_set_perm(entry, 0644);
296 } else if(S_ISDIR(st->st_mode)) {
297 archive_entry_set_perm(entry, 0755);
300 /* If specific files were requested, skip entries that don't match. */
301 if(list) {
302 char *entry_prefix = strdup(entryname);
303 char *p = strstr(prefix,"/");
304 if(p) {
305 *(p+1) = '\0';
307 char *found = alpm_list_find_str(list, entry_prefix);
308 free(entry_prefix);
309 if(!found) {
310 if(archive_read_data_skip(_archive) != ARCHIVE_OK) {
311 ret = 1;
312 goto cleanup;
314 continue;
315 } else {
316 _alpm_log(handle, PM_LOG_DEBUG, "extracting: %s\n", entryname);
320 /* Extract the archive entry. */
321 int readret = archive_read_extract(_archive, entry, 0);
322 if(readret == ARCHIVE_WARN) {
323 /* operation succeeded but a non-critical error was encountered */
324 _alpm_log(handle, PM_LOG_WARNING, _("warning given when extracting %s (%s)\n"),
325 entryname, archive_error_string(_archive));
326 } else if(readret != ARCHIVE_OK) {
327 _alpm_log(handle, PM_LOG_ERROR, _("could not extract %s (%s)\n"),
328 entryname, archive_error_string(_archive));
329 ret = 1;
330 goto cleanup;
333 if(breakfirst) {
334 break;
338 cleanup:
339 umask(oldmask);
340 archive_read_finish(_archive);
341 if(restore_cwd && chdir(cwd) != 0) {
342 _alpm_log(handle, PM_LOG_ERROR, _("could not change directory to %s (%s)\n"),
343 cwd, strerror(errno));
345 return ret;
348 /* does the same thing as 'rm -rf' */
349 int _alpm_rmrf(const char *path)
351 int errflag = 0;
352 struct dirent *dp;
353 DIR *dirp;
354 char name[PATH_MAX];
355 struct stat st;
357 if(_alpm_lstat(path, &st) == 0) {
358 if(!S_ISDIR(st.st_mode)) {
359 if(!unlink(path)) {
360 return 0;
361 } else {
362 if(errno == ENOENT) {
363 return 0;
364 } else {
365 return 1;
368 } else {
369 dirp = opendir(path);
370 if(!dirp) {
371 return 1;
373 for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
374 if(dp->d_ino) {
375 sprintf(name, "%s/%s", path, dp->d_name);
376 if(strcmp(dp->d_name, "..") != 0 && strcmp(dp->d_name, ".") != 0) {
377 errflag += _alpm_rmrf(name);
381 closedir(dirp);
382 if(rmdir(path)) {
383 errflag++;
386 return errflag;
388 return 0;
391 int _alpm_logaction(alpm_handle_t *handle, const char *fmt, va_list args)
393 int ret = 0;
395 if(handle->usesyslog) {
396 /* we can't use a va_list more than once, so we need to copy it
397 * so we can use the original when calling vfprintf below. */
398 va_list args_syslog;
399 va_copy(args_syslog, args);
400 vsyslog(LOG_WARNING, fmt, args_syslog);
401 va_end(args_syslog);
404 if(handle->logstream) {
405 time_t t;
406 struct tm *tm;
408 t = time(NULL);
409 tm = localtime(&t);
411 /* Use ISO-8601 date format */
412 fprintf(handle->logstream, "[%04d-%02d-%02d %02d:%02d] ",
413 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
414 tm->tm_hour, tm->tm_min);
415 ret = vfprintf(handle->logstream, fmt, args);
416 fflush(handle->logstream);
419 return ret;
422 int _alpm_run_chroot(alpm_handle_t *handle, const char *path, char *const argv[])
424 char cwd[PATH_MAX];
425 pid_t pid;
426 int pipefd[2];
427 int restore_cwd = 0;
428 int retval = 0;
430 /* save the cwd so we can restore it later */
431 if(getcwd(cwd, PATH_MAX) == NULL) {
432 _alpm_log(handle, PM_LOG_ERROR, _("could not get current working directory\n"));
433 } else {
434 restore_cwd = 1;
437 /* just in case our cwd was removed in the upgrade operation */
438 if(chdir(handle->root) != 0) {
439 _alpm_log(handle, PM_LOG_ERROR, _("could not change directory to %s (%s)\n"),
440 handle->root, strerror(errno));
441 goto cleanup;
444 _alpm_log(handle, PM_LOG_DEBUG, "executing \"%s\" under chroot \"%s\"\n",
445 path, handle->root);
447 /* Flush open fds before fork() to avoid cloning buffers */
448 fflush(NULL);
450 if(pipe(pipefd) == -1) {
451 _alpm_log(handle, PM_LOG_ERROR, _("could not create pipe (%s)\n"), strerror(errno));
452 retval = 1;
453 goto cleanup;
456 /* fork- parent and child each have seperate code blocks below */
457 pid = fork();
458 if(pid == -1) {
459 _alpm_log(handle, PM_LOG_ERROR, _("could not fork a new process (%s)\n"), strerror(errno));
460 retval = 1;
461 goto cleanup;
464 if(pid == 0) {
465 /* this code runs for the child only (the actual chroot/exec) */
466 close(1);
467 close(2);
468 while(dup2(pipefd[1], 1) == -1 && errno == EINTR);
469 while(dup2(pipefd[1], 2) == -1 && errno == EINTR);
470 close(pipefd[0]);
471 close(pipefd[1]);
473 /* use fprintf instead of _alpm_log to send output through the parent */
474 if(chroot(handle->root) != 0) {
475 fprintf(stderr, _("could not change the root directory (%s)\n"), strerror(errno));
476 exit(1);
478 if(chdir("/") != 0) {
479 fprintf(stderr, _("could not change directory to %s (%s)\n"),
480 "/", strerror(errno));
481 exit(1);
483 umask(0022);
484 execv(path, argv);
485 fprintf(stderr, _("call to execv failed (%s)\n"), strerror(errno));
486 exit(1);
487 } else {
488 /* this code runs for the parent only (wait on the child) */
489 int status;
490 FILE *pipe_file;
492 close(pipefd[1]);
493 pipe_file = fdopen(pipefd[0], "r");
494 if(pipe_file == NULL) {
495 close(pipefd[0]);
496 retval = 1;
497 } else {
498 while(!feof(pipe_file)) {
499 char line[PATH_MAX];
500 if(fgets(line, PATH_MAX, pipe_file) == NULL)
501 break;
502 alpm_logaction(handle, "%s", line);
503 EVENT(handle->trans, PM_TRANS_EVT_SCRIPTLET_INFO, line, NULL);
505 fclose(pipe_file);
508 while(waitpid(pid, &status, 0) == -1) {
509 if(errno != EINTR) {
510 _alpm_log(handle, PM_LOG_ERROR, _("call to waitpid failed (%s)\n"), strerror(errno));
511 retval = 1;
512 goto cleanup;
516 /* report error from above after the child has exited */
517 if(retval != 0) {
518 _alpm_log(handle, PM_LOG_ERROR, _("could not open pipe (%s)\n"), strerror(errno));
519 goto cleanup;
521 /* check the return status, make sure it is 0 (success) */
522 if(WIFEXITED(status)) {
523 _alpm_log(handle, PM_LOG_DEBUG, "call to waitpid succeeded\n");
524 if(WEXITSTATUS(status) != 0) {
525 _alpm_log(handle, PM_LOG_ERROR, _("command failed to execute correctly\n"));
526 retval = 1;
531 cleanup:
532 if(restore_cwd && chdir(cwd) != 0) {
533 _alpm_log(handle, PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
536 return retval;
539 int _alpm_ldconfig(alpm_handle_t *handle)
541 char line[PATH_MAX];
543 _alpm_log(handle, PM_LOG_DEBUG, "running ldconfig\n");
545 snprintf(line, PATH_MAX, "%setc/ld.so.conf", handle->root);
546 if(access(line, F_OK) == 0) {
547 snprintf(line, PATH_MAX, "%ssbin/ldconfig", handle->root);
548 if(access(line, X_OK) == 0) {
549 char *argv[] = { "ldconfig", NULL };
550 _alpm_run_chroot(handle, "/sbin/ldconfig", argv);
554 return 0;
557 /* Helper function for comparing strings using the
558 * alpm "compare func" signature */
559 int _alpm_str_cmp(const void *s1, const void *s2)
561 return strcmp(s1, s2);
564 /** Find a filename in a registered alpm cachedir.
565 * @param handle the context handle
566 * @param filename name of file to find
567 * @return malloced path of file, NULL if not found
569 char *_alpm_filecache_find(alpm_handle_t *handle, const char *filename)
571 char path[PATH_MAX];
572 char *retpath;
573 alpm_list_t *i;
574 struct stat buf;
576 /* Loop through the cache dirs until we find a matching file */
577 for(i = alpm_option_get_cachedirs(handle); i; i = alpm_list_next(i)) {
578 snprintf(path, PATH_MAX, "%s%s", (char *)alpm_list_getdata(i),
579 filename);
580 if(stat(path, &buf) == 0 && S_ISREG(buf.st_mode)) {
581 retpath = strdup(path);
582 _alpm_log(handle, PM_LOG_DEBUG, "found cached pkg: %s\n", retpath);
583 return retpath;
586 /* package wasn't found in any cachedir */
587 return NULL;
590 /** Check the alpm cachedirs for existance and find a writable one.
591 * If no valid cache directory can be found, use /tmp.
592 * @param handle the context handle
593 * @return pointer to a writable cache directory.
595 const char *_alpm_filecache_setup(alpm_handle_t *handle)
597 struct stat buf;
598 alpm_list_t *i, *tmp;
599 char *cachedir;
601 /* Loop through the cache dirs until we find a writeable dir */
602 for(i = alpm_option_get_cachedirs(handle); i; i = alpm_list_next(i)) {
603 cachedir = alpm_list_getdata(i);
604 if(stat(cachedir, &buf) != 0) {
605 /* cache directory does not exist.... try creating it */
606 _alpm_log(handle, PM_LOG_WARNING, _("no %s cache exists, creating...\n"),
607 cachedir);
608 if(_alpm_makepath(cachedir) == 0) {
609 _alpm_log(handle, PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
610 return cachedir;
612 } else if(S_ISDIR(buf.st_mode) && (buf.st_mode & S_IWUSR)) {
613 _alpm_log(handle, PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
614 return cachedir;
615 } else {
616 _alpm_log(handle, PM_LOG_DEBUG, "skipping cachedir: %s\n", cachedir);
620 /* we didn't find a valid cache directory. use /tmp. */
621 tmp = alpm_list_add(NULL, "/tmp/");
622 alpm_option_set_cachedirs(handle, tmp);
623 alpm_list_free(tmp);
624 _alpm_log(handle, PM_LOG_DEBUG, "using cachedir: %s\n", "/tmp/");
625 _alpm_log(handle, PM_LOG_WARNING, _("couldn't create package cache, using /tmp instead\n"));
626 return "/tmp/";
629 /** lstat wrapper that treats /path/dirsymlink/ the same as /path/dirsymlink.
630 * Linux lstat follows POSIX semantics and still performs a dereference on
631 * the first, and for uses of lstat in libalpm this is not what we want.
632 * @param path path to file to lstat
633 * @param buf structure to fill with stat information
634 * @return the return code from lstat
636 int _alpm_lstat(const char *path, struct stat *buf)
638 int ret;
639 size_t len = strlen(path);
641 /* strip the trailing slash if one exists */
642 if(len != 0 && path[len - 1] == '/') {
643 char *newpath = strdup(path);
644 newpath[len - 1] = '\0';
645 ret = lstat(newpath, buf);
646 free(newpath);
647 } else {
648 ret = lstat(path, buf);
651 return ret;
654 #ifdef HAVE_LIBSSL
655 static int md5_file(const char *path, unsigned char output[16])
657 FILE *f;
658 size_t n;
659 MD5_CTX ctx;
660 unsigned char *buf;
662 CALLOC(buf, 8192, sizeof(unsigned char), return 1);
664 if((f = fopen(path, "rb")) == NULL) {
665 free(buf);
666 return 1;
669 MD5_Init(&ctx);
671 while((n = fread(buf, 1, sizeof(buf), f)) > 0) {
672 MD5_Update(&ctx, buf, n);
675 MD5_Final(output, &ctx);
677 memset(&ctx, 0, sizeof(MD5_CTX));
678 free(buf);
680 if(ferror(f) != 0) {
681 fclose(f);
682 return 2;
685 fclose(f);
686 return 0;
688 #endif
690 /** Get the md5 sum of file.
691 * @param filename name of the file
692 * @return the checksum on success, NULL on error
693 * @addtogroup alpm_misc
695 char SYMEXPORT *alpm_compute_md5sum(const char *filename)
697 unsigned char output[16];
698 char *md5sum;
699 int ret, i;
701 ASSERT(filename != NULL, return NULL);
703 /* allocate 32 chars plus 1 for null */
704 CALLOC(md5sum, 33, sizeof(char), return NULL);
705 /* defined above for OpenSSL, otherwise defined in md5.h */
706 ret = md5_file(filename, output);
708 if(ret > 0) {
709 return NULL;
712 /* Convert the result to something readable */
713 for (i = 0; i < 16; i++) {
714 /* sprintf is acceptable here because we know our output */
715 sprintf(md5sum +(i * 2), "%02x", output[i]);
718 return md5sum;
721 int _alpm_test_md5sum(const char *filepath, const char *md5sum)
723 char *md5sum2;
724 int ret;
726 md5sum2 = alpm_compute_md5sum(filepath);
728 if(md5sum == NULL || md5sum2 == NULL) {
729 ret = -1;
730 } else if(strcmp(md5sum, md5sum2) != 0) {
731 ret = 1;
732 } else {
733 ret = 0;
736 FREE(md5sum2);
737 return ret;
740 /* Note: does NOT handle sparse files on purpose for speed. */
741 int _alpm_archive_fgets(struct archive *a, struct archive_read_buffer *b)
743 char *i = NULL;
744 int64_t offset;
745 int done = 0;
747 /* ensure we start populating our line buffer at the beginning */
748 b->line_offset = b->line;
750 while(1) {
751 /* have we processed this entire block? */
752 if(b->block + b->block_size == b->block_offset) {
753 if(b->ret == ARCHIVE_EOF) {
754 /* reached end of archive on the last read, now we are out of data */
755 goto cleanup;
758 /* zero-copy - this is the entire next block of data. */
759 b->ret = archive_read_data_block(a, (void *)&b->block,
760 &b->block_size, &offset);
761 b->block_offset = b->block;
763 /* error, cleanup */
764 if(b->ret < ARCHIVE_OK) {
765 goto cleanup;
769 /* loop through the block looking for EOL characters */
770 for(i = b->block_offset; i < (b->block + b->block_size); i++) {
771 /* check if read value was null or newline */
772 if(*i == '\0' || *i == '\n') {
773 done = 1;
774 break;
778 /* allocate our buffer, or ensure our existing one is big enough */
779 if(!b->line) {
780 /* set the initial buffer to the read block_size */
781 CALLOC(b->line, b->block_size + 1, sizeof(char), b->ret = -ENOMEM; goto cleanup);
782 b->line_size = b->block_size + 1;
783 b->line_offset = b->line;
784 } else {
785 size_t needed = (size_t)((b->line_offset - b->line)
786 + (i - b->block_offset) + 1);
787 if(needed > b->max_line_size) {
788 b->ret = -ERANGE;
789 goto cleanup;
791 if(needed > b->line_size) {
792 /* need to realloc + copy data to fit total length */
793 char *new;
794 CALLOC(new, needed, sizeof(char), b->ret = -ENOMEM; goto cleanup);
795 memcpy(new, b->line, b->line_size);
796 b->line_size = needed;
797 b->line_offset = new + (b->line_offset - b->line);
798 free(b->line);
799 b->line = new;
803 if(done) {
804 size_t len = (size_t)(i - b->block_offset);
805 memcpy(b->line_offset, b->block_offset, len);
806 b->line_offset[len] = '\0';
807 b->block_offset = ++i;
808 /* this is the main return point; from here you can read b->line */
809 return ARCHIVE_OK;
810 } else {
811 /* we've looked through the whole block but no newline, copy it */
812 size_t len = (size_t)(b->block + b->block_size - b->block_offset);
813 memcpy(b->line_offset, b->block_offset, len);
814 b->line_offset += len;
815 b->block_offset = i;
816 /* there was no new data, return what is left; saved ARCHIVE_EOF will be
817 * returned on next call */
818 if(len == 0) {
819 b->line_offset[0] = '\0';
820 return ARCHIVE_OK;
825 cleanup:
827 int ret = b->ret;
828 FREE(b->line);
829 memset(b, 0, sizeof(b));
830 return ret;
834 int _alpm_splitname(const char *target, char **name, char **version,
835 unsigned long *name_hash)
837 /* the format of a db entry is as follows:
838 * package-version-rel/
839 * package-version-rel/desc (we ignore the filename portion)
840 * package name can contain hyphens, so parse from the back- go back
841 * two hyphens and we have split the version from the name.
843 const char *pkgver, *end;
845 if(target == NULL) {
846 return -1;
849 /* remove anything trailing a '/' */
850 end = strchr(target, '/');
851 if(!end) {
852 end = target + strlen(target);
855 /* do the magic parsing- find the beginning of the version string
856 * by doing two iterations of same loop to lop off two hyphens */
857 for(pkgver = end - 1; *pkgver && *pkgver != '-'; pkgver--);
858 for(pkgver = pkgver - 1; *pkgver && *pkgver != '-'; pkgver--);
859 if(*pkgver != '-' || pkgver == target) {
860 return -1;
863 /* copy into fields and return */
864 if(version) {
865 if(*version) {
866 FREE(*version);
868 /* version actually points to the dash, so need to increment 1 and account
869 * for potential end character */
870 STRNDUP(*version, pkgver + 1, end - pkgver - 1, return -1);
873 if(name) {
874 if(*name) {
875 FREE(*name);
877 STRNDUP(*name, target, pkgver - target, return -1);
878 if(name_hash) {
879 *name_hash = _alpm_hash_sdbm(*name);
883 return 0;
887 * Hash the given string to an unsigned long value.
888 * This is the standard sdbm hashing algorithm.
889 * @param str string to hash
890 * @return the hash value of the given string
892 unsigned long _alpm_hash_sdbm(const char *str)
894 unsigned long hash = 0;
895 int c;
897 if(!str) {
898 return hash;
900 while((c = *str++)) {
901 hash = c + (hash << 6) + (hash << 16) - hash;
904 return hash;
907 long _alpm_parsedate(const char *line)
909 if(isalpha((unsigned char)line[0])) {
910 /* initialize to null in case of failure */
911 struct tm tmp_tm = { 0 };
912 setlocale(LC_TIME, "C");
913 strptime(line, "%a %b %e %H:%M:%S %Y", &tmp_tm);
914 setlocale(LC_TIME, "");
915 return mktime(&tmp_tm);
917 return atol(line);
920 #ifndef HAVE_STRNDUP
921 /* A quick and dirty implementation derived from glibc */
922 static size_t strnlen(const char *s, size_t max)
924 register const char *p;
925 for(p = s; *p && max--; ++p);
926 return (p - s);
929 char *strndup(const char *s, size_t n)
931 size_t len = strnlen(s, n);
932 char *new = (char *) malloc(len + 1);
934 if(new == NULL)
935 return NULL;
937 new[len] = '\0';
938 return (char *)memcpy(new, s, len);
940 #endif
942 /* vim: set ts=2 sw=2 noet: */