Require handle for alpm_pkg_load()
[pacman-ng.git] / lib / libalpm / util.c
blob6b11c3a9e520061a64edf4b7e06afe41401cc6a7
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 pm_errno = PM_ERR_WRITE;
156 _alpm_log(PM_LOG_ERROR, _("error writing to file '%s': %s\n"),
157 dest, strerror(errno));
158 ret = -1;
159 goto cleanup;
163 /* chmod dest to permissions of src, as long as it is not a symlink */
164 struct stat statbuf;
165 if(!stat(src, &statbuf)) {
166 if(! S_ISLNK(statbuf.st_mode)) {
167 fchmod(fileno(out), statbuf.st_mode);
169 } else {
170 /* stat was unsuccessful */
171 ret = 1;
174 cleanup:
175 fclose(in);
176 fclose(out);
177 FREE(buf);
178 return ret;
181 /* Trim whitespace and newlines from a string
183 char *_alpm_strtrim(char *str)
185 char *pch = str;
187 if(*str == '\0') {
188 /* string is empty, so we're done. */
189 return str;
192 while(isspace((unsigned char)*pch)) {
193 pch++;
195 if(pch != str) {
196 memmove(str, pch, (strlen(pch) + 1));
199 /* check if there wasn't anything but whitespace in the string. */
200 if(*str == '\0') {
201 return str;
204 pch = (str + (strlen(str) - 1));
205 while(isspace((unsigned char)*pch)) {
206 pch--;
208 *++pch = '\0';
210 return str;
213 /* Compression functions */
216 * @brief Unpack a specific file in an archive.
218 * @param archive the archive to unpack
219 * @param prefix where to extract the files
220 * @param fn a file within the archive to unpack
221 * @return 0 on success, 1 on failure
223 int _alpm_unpack_single(const char *archive, const char *prefix, const char *fn)
225 alpm_list_t *list = NULL;
226 int ret = 0;
227 if(fn == NULL) {
228 return 1;
230 list = alpm_list_add(list, (void *)fn);
231 ret = _alpm_unpack(archive, prefix, list, 1);
232 alpm_list_free(list);
233 return ret;
237 * @brief Unpack a list of files in an archive.
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
242 * NULL for all
243 * @param breakfirst break after the first entry found
245 * @return 0 on success, 1 on failure
247 int _alpm_unpack(const char *archive, const char *prefix, 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(PM_ERR_LIBARCHIVE, 1);
259 archive_read_support_compression_all(_archive);
260 archive_read_support_format_all(_archive);
262 if(archive_read_open_filename(_archive, archive,
263 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
264 _alpm_log(PM_LOG_ERROR, _("could not open file %s: %s\n"), archive,
265 archive_error_string(_archive));
266 RET_ERR(PM_ERR_PKG_OPEN, 1);
269 oldmask = umask(0022);
271 /* save the cwd so we can restore it later */
272 if(getcwd(cwd, PATH_MAX) == NULL) {
273 _alpm_log(PM_LOG_ERROR, _("could not get current working directory\n"));
274 } else {
275 restore_cwd = 1;
278 /* just in case our cwd was removed in the upgrade operation */
279 if(chdir(prefix) != 0) {
280 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), prefix, strerror(errno));
281 ret = 1;
282 goto cleanup;
285 while(archive_read_next_header(_archive, &entry) == ARCHIVE_OK) {
286 const struct stat *st;
287 const char *entryname; /* the name of the file in the archive */
289 st = archive_entry_stat(entry);
290 entryname = archive_entry_pathname(entry);
292 if(S_ISREG(st->st_mode)) {
293 archive_entry_set_perm(entry, 0644);
294 } else if(S_ISDIR(st->st_mode)) {
295 archive_entry_set_perm(entry, 0755);
298 /* If specific files were requested, skip entries that don't match. */
299 if(list) {
300 char *prefix = strdup(entryname);
301 char *p = strstr(prefix,"/");
302 if(p) {
303 *(p+1) = '\0';
305 char *found = alpm_list_find_str(list, prefix);
306 free(prefix);
307 if(!found) {
308 if(archive_read_data_skip(_archive) != ARCHIVE_OK) {
309 ret = 1;
310 goto cleanup;
312 continue;
313 } else {
314 _alpm_log(PM_LOG_DEBUG, "extracting: %s\n", entryname);
318 /* Extract the archive entry. */
319 int readret = archive_read_extract(_archive, entry, 0);
320 if(readret == ARCHIVE_WARN) {
321 /* operation succeeded but a non-critical error was encountered */
322 _alpm_log(PM_LOG_WARNING, _("warning given when extracting %s (%s)\n"),
323 entryname, archive_error_string(_archive));
324 } else if(readret != ARCHIVE_OK) {
325 _alpm_log(PM_LOG_ERROR, _("could not extract %s (%s)\n"),
326 entryname, archive_error_string(_archive));
327 ret = 1;
328 goto cleanup;
331 if(breakfirst) {
332 break;
336 cleanup:
337 umask(oldmask);
338 archive_read_finish(_archive);
339 if(restore_cwd && chdir(cwd) != 0) {
340 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
342 return ret;
345 /* does the same thing as 'rm -rf' */
346 int _alpm_rmrf(const char *path)
348 int errflag = 0;
349 struct dirent *dp;
350 DIR *dirp;
351 char name[PATH_MAX];
352 struct stat st;
354 if(_alpm_lstat(path, &st) == 0) {
355 if(!S_ISDIR(st.st_mode)) {
356 if(!unlink(path)) {
357 return 0;
358 } else {
359 if(errno == ENOENT) {
360 return 0;
361 } else {
362 return 1;
365 } else {
366 dirp = opendir(path);
367 if(!dirp) {
368 return 1;
370 for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
371 if(dp->d_ino) {
372 sprintf(name, "%s/%s", path, dp->d_name);
373 if(strcmp(dp->d_name, "..") != 0 && strcmp(dp->d_name, ".") != 0) {
374 errflag += _alpm_rmrf(name);
378 closedir(dirp);
379 if(rmdir(path)) {
380 errflag++;
383 return errflag;
385 return 0;
388 int _alpm_logaction(pmhandle_t *handle, const char *fmt, va_list args)
390 int ret = 0;
392 if(handle->usesyslog) {
393 /* we can't use a va_list more than once, so we need to copy it
394 * so we can use the original when calling vfprintf below. */
395 va_list args_syslog;
396 va_copy(args_syslog, args);
397 vsyslog(LOG_WARNING, fmt, args_syslog);
398 va_end(args_syslog);
401 if(handle->logstream) {
402 time_t t;
403 struct tm *tm;
405 t = time(NULL);
406 tm = localtime(&t);
408 /* Use ISO-8601 date format */
409 fprintf(handle->logstream, "[%04d-%02d-%02d %02d:%02d] ",
410 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
411 tm->tm_hour, tm->tm_min);
412 ret = vfprintf(handle->logstream, fmt, args);
413 fflush(handle->logstream);
416 return ret;
419 int _alpm_run_chroot(pmhandle_t *handle, const char *path, char *const argv[])
421 char cwd[PATH_MAX];
422 pid_t pid;
423 int pipefd[2];
424 int restore_cwd = 0;
425 int retval = 0;
427 /* save the cwd so we can restore it later */
428 if(getcwd(cwd, PATH_MAX) == NULL) {
429 _alpm_log(PM_LOG_ERROR, _("could not get current working directory\n"));
430 } else {
431 restore_cwd = 1;
434 /* just in case our cwd was removed in the upgrade operation */
435 if(chdir(handle->root) != 0) {
436 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"),
437 handle->root, strerror(errno));
438 goto cleanup;
441 _alpm_log(PM_LOG_DEBUG, "executing \"%s\" under chroot \"%s\"\n",
442 path, handle->root);
444 /* Flush open fds before fork() to avoid cloning buffers */
445 fflush(NULL);
447 if(pipe(pipefd) == -1) {
448 _alpm_log(PM_LOG_ERROR, _("could not create pipe (%s)\n"), strerror(errno));
449 retval = 1;
450 goto cleanup;
453 /* fork- parent and child each have seperate code blocks below */
454 pid = fork();
455 if(pid == -1) {
456 _alpm_log(PM_LOG_ERROR, _("could not fork a new process (%s)\n"), strerror(errno));
457 retval = 1;
458 goto cleanup;
461 if(pid == 0) {
462 /* this code runs for the child only (the actual chroot/exec) */
463 close(1);
464 close(2);
465 while(dup2(pipefd[1], 1) == -1 && errno == EINTR);
466 while(dup2(pipefd[1], 2) == -1 && errno == EINTR);
467 close(pipefd[0]);
468 close(pipefd[1]);
470 /* use fprintf instead of _alpm_log to send output through the parent */
471 if(chroot(handle->root) != 0) {
472 fprintf(stderr, _("could not change the root directory (%s)\n"), strerror(errno));
473 exit(1);
475 if(chdir("/") != 0) {
476 fprintf(stderr, _("could not change directory to %s (%s)\n"),
477 "/", strerror(errno));
478 exit(1);
480 umask(0022);
481 execv(path, argv);
482 fprintf(stderr, _("call to execv failed (%s)\n"), strerror(errno));
483 exit(1);
484 } else {
485 /* this code runs for the parent only (wait on the child) */
486 int status;
487 FILE *pipe;
489 close(pipefd[1]);
490 pipe = fdopen(pipefd[0], "r");
491 if(pipe == NULL) {
492 close(pipefd[0]);
493 retval = 1;
494 } else {
495 while(!feof(pipe)) {
496 char line[PATH_MAX];
497 if(fgets(line, PATH_MAX, pipe) == NULL)
498 break;
499 alpm_logaction(handle, "%s", line);
500 EVENT(handle->trans, PM_TRANS_EVT_SCRIPTLET_INFO, line, NULL);
502 fclose(pipe);
505 while(waitpid(pid, &status, 0) == -1) {
506 if(errno != EINTR) {
507 _alpm_log(PM_LOG_ERROR, _("call to waitpid failed (%s)\n"), strerror(errno));
508 retval = 1;
509 goto cleanup;
513 /* report error from above after the child has exited */
514 if(retval != 0) {
515 _alpm_log(PM_LOG_ERROR, _("could not open pipe (%s)\n"), strerror(errno));
516 goto cleanup;
518 /* check the return status, make sure it is 0 (success) */
519 if(WIFEXITED(status)) {
520 _alpm_log(PM_LOG_DEBUG, "call to waitpid succeeded\n");
521 if(WEXITSTATUS(status) != 0) {
522 _alpm_log(PM_LOG_ERROR, _("command failed to execute correctly\n"));
523 retval = 1;
528 cleanup:
529 if(restore_cwd && chdir(cwd) != 0) {
530 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
533 return retval;
536 int _alpm_ldconfig(pmhandle_t *handle)
538 char line[PATH_MAX];
540 _alpm_log(PM_LOG_DEBUG, "running ldconfig\n");
542 snprintf(line, PATH_MAX, "%setc/ld.so.conf", handle->root);
543 if(access(line, F_OK) == 0) {
544 snprintf(line, PATH_MAX, "%ssbin/ldconfig", handle->root);
545 if(access(line, X_OK) == 0) {
546 char *argv[] = { "ldconfig", NULL };
547 _alpm_run_chroot(handle, "/sbin/ldconfig", argv);
551 return 0;
554 /* Helper function for comparing strings using the
555 * alpm "compare func" signature */
556 int _alpm_str_cmp(const void *s1, const void *s2)
558 return strcmp(s1, s2);
561 /** Find a filename in a registered alpm cachedir.
562 * @param handle the context handle
563 * @param filename name of file to find
564 * @return malloced path of file, NULL if not found
566 char *_alpm_filecache_find(pmhandle_t *handle, const char *filename)
568 char path[PATH_MAX];
569 char *retpath;
570 alpm_list_t *i;
571 struct stat buf;
573 /* Loop through the cache dirs until we find a matching file */
574 for(i = alpm_option_get_cachedirs(handle); i; i = alpm_list_next(i)) {
575 snprintf(path, PATH_MAX, "%s%s", (char *)alpm_list_getdata(i),
576 filename);
577 if(stat(path, &buf) == 0 && S_ISREG(buf.st_mode)) {
578 retpath = strdup(path);
579 _alpm_log(PM_LOG_DEBUG, "found cached pkg: %s\n", retpath);
580 return retpath;
583 /* package wasn't found in any cachedir */
584 RET_ERR(PM_ERR_PKG_NOT_FOUND, NULL);
587 /** Check the alpm cachedirs for existance and find a writable one.
588 * If no valid cache directory can be found, use /tmp.
589 * @param handle the context handle
590 * @return pointer to a writable cache directory.
592 const char *_alpm_filecache_setup(pmhandle_t *handle)
594 struct stat buf;
595 alpm_list_t *i, *tmp;
596 char *cachedir;
598 /* Loop through the cache dirs until we find a writeable dir */
599 for(i = alpm_option_get_cachedirs(handle); i; i = alpm_list_next(i)) {
600 cachedir = alpm_list_getdata(i);
601 if(stat(cachedir, &buf) != 0) {
602 /* cache directory does not exist.... try creating it */
603 _alpm_log(PM_LOG_WARNING, _("no %s cache exists, creating...\n"),
604 cachedir);
605 if(_alpm_makepath(cachedir) == 0) {
606 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
607 return cachedir;
609 } else if(S_ISDIR(buf.st_mode) && (buf.st_mode & S_IWUSR)) {
610 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
611 return cachedir;
612 } else {
613 _alpm_log(PM_LOG_DEBUG, "skipping cachedir: %s\n", cachedir);
617 /* we didn't find a valid cache directory. use /tmp. */
618 tmp = alpm_list_add(NULL, "/tmp/");
619 alpm_option_set_cachedirs(handle, tmp);
620 alpm_list_free(tmp);
621 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s\n", "/tmp/");
622 _alpm_log(PM_LOG_WARNING, _("couldn't create package cache, using /tmp instead\n"));
623 return "/tmp/";
626 /** lstat wrapper that treats /path/dirsymlink/ the same as /path/dirsymlink.
627 * Linux lstat follows POSIX semantics and still performs a dereference on
628 * the first, and for uses of lstat in libalpm this is not what we want.
629 * @param path path to file to lstat
630 * @param buf structure to fill with stat information
631 * @return the return code from lstat
633 int _alpm_lstat(const char *path, struct stat *buf)
635 int ret;
636 size_t len = strlen(path);
638 /* strip the trailing slash if one exists */
639 if(len != 0 && path[len - 1] == '/') {
640 char *newpath = strdup(path);
641 newpath[len - 1] = '\0';
642 ret = lstat(newpath, buf);
643 free(newpath);
644 } else {
645 ret = lstat(path, buf);
648 return ret;
651 #ifdef HAVE_LIBSSL
652 static int md5_file(const char *path, unsigned char output[16])
654 FILE *f;
655 size_t n;
656 MD5_CTX ctx;
657 unsigned char *buf;
659 CALLOC(buf, 8192, sizeof(unsigned char), RET_ERR(PM_ERR_MEMORY, 1));
661 if((f = fopen(path, "rb")) == NULL) {
662 free(buf);
663 return 1;
666 MD5_Init(&ctx);
668 while((n = fread(buf, 1, sizeof(buf), f)) > 0) {
669 MD5_Update(&ctx, buf, n);
672 MD5_Final(output, &ctx);
674 memset(&ctx, 0, sizeof(MD5_CTX));
675 free(buf);
677 if(ferror(f) != 0) {
678 fclose(f);
679 return 2;
682 fclose(f);
683 return 0;
685 #endif
687 /** Get the md5 sum of file.
688 * @param filename name of the file
689 * @return the checksum on success, NULL on error
690 * @addtogroup alpm_misc
692 char SYMEXPORT *alpm_compute_md5sum(const char *filename)
694 unsigned char output[16];
695 char *md5sum;
696 int ret, i;
698 ASSERT(filename != NULL, return NULL);
700 /* allocate 32 chars plus 1 for null */
701 md5sum = calloc(33, sizeof(char));
702 /* defined above for OpenSSL, otherwise defined in md5.h */
703 ret = md5_file(filename, output);
705 if(ret > 0) {
706 RET_ERR(PM_ERR_NOT_A_FILE, NULL);
709 /* Convert the result to something readable */
710 for (i = 0; i < 16; i++) {
711 /* sprintf is acceptable here because we know our output */
712 sprintf(md5sum +(i * 2), "%02x", output[i]);
714 md5sum[32] = '\0';
716 _alpm_log(PM_LOG_DEBUG, "md5(%s) = %s\n", filename, md5sum);
717 return md5sum;
720 int _alpm_test_md5sum(const char *filepath, const char *md5sum)
722 char *md5sum2;
723 int ret;
725 md5sum2 = alpm_compute_md5sum(filepath);
727 if(md5sum == NULL || md5sum2 == NULL) {
728 ret = -1;
729 } else if(strcmp(md5sum, md5sum2) != 0) {
730 ret = 1;
731 } else {
732 ret = 0;
735 FREE(md5sum2);
736 return ret;
739 /* Note: does NOT handle sparse files on purpose for speed. */
740 int _alpm_archive_fgets(struct archive *a, struct archive_read_buffer *b)
742 char *i = NULL;
743 int64_t offset;
744 int done = 0;
746 /* ensure we start populating our line buffer at the beginning */
747 b->line_offset = b->line;
749 while(1) {
750 /* have we processed this entire block? */
751 if(b->block + b->block_size == b->block_offset) {
752 if(b->ret == ARCHIVE_EOF) {
753 /* reached end of archive on the last read, now we are out of data */
754 goto cleanup;
757 /* zero-copy - this is the entire next block of data. */
758 b->ret = archive_read_data_block(a, (void *)&b->block,
759 &b->block_size, &offset);
760 b->block_offset = b->block;
762 /* error or end of archive with no data read, cleanup */
763 if(b->ret < ARCHIVE_OK ||
764 (b->block_size == 0 && b->ret == ARCHIVE_EOF)) {
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), return ENOMEM);
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 return ERANGE;
790 if(needed > b->line_size) {
791 /* need to realloc + copy data to fit total length */
792 char *new;
793 CALLOC(new, needed, sizeof(char), return ENOMEM);
794 memcpy(new, b->line, b->line_size);
795 b->line_size = needed;
796 b->line_offset = new + (b->line_offset - b->line);
797 free(b->line);
798 b->line = new;
802 if(done) {
803 size_t len = (size_t)(i - b->block_offset);
804 memcpy(b->line_offset, b->block_offset, len);
805 b->line_offset[len] = '\0';
806 b->block_offset = ++i;
807 /* this is the main return point; from here you can read b->line */
808 return ARCHIVE_OK;
809 } else {
810 /* we've looked through the whole block but no newline, copy it */
811 size_t len = (size_t)(b->block + b->block_size - b->block_offset);
812 memcpy(b->line_offset, b->block_offset, len);
813 b->line_offset += len;
814 b->block_offset = i;
818 cleanup:
820 int ret = b->ret;
821 FREE(b->line);
822 memset(b, 0, sizeof(b));
823 return ret;
827 int _alpm_splitname(const char *target, pmpkg_t *pkg)
829 /* the format of a db entry is as follows:
830 * package-version-rel/
831 * package name can contain hyphens, so parse from the back- go back
832 * two hyphens and we have split the version from the name.
834 const char *version, *end;
836 if(target == NULL || pkg == NULL) {
837 return -1;
839 end = target + strlen(target);
841 /* remove any trailing '/' */
842 while(*(end - 1) == '/') {
843 --end;
846 /* do the magic parsing- find the beginning of the version string
847 * by doing two iterations of same loop to lop off two hyphens */
848 for(version = end - 1; *version && *version != '-'; version--);
849 for(version = version - 1; *version && *version != '-'; version--);
850 if(*version != '-' || version == target) {
851 return -1;
854 /* copy into fields and return */
855 if(pkg->version) {
856 FREE(pkg->version);
858 /* version actually points to the dash, so need to increment 1 and account
859 * for potential end character */
860 STRNDUP(pkg->version, version + 1, end - version - 1,
861 RET_ERR(PM_ERR_MEMORY, -1));
863 if(pkg->name) {
864 FREE(pkg->name);
866 STRNDUP(pkg->name, target, version - target, RET_ERR(PM_ERR_MEMORY, -1));
867 pkg->name_hash = _alpm_hash_sdbm(pkg->name);
869 return 0;
873 * Hash the given string to an unsigned long value.
874 * This is the standard sdbm hashing algorithm.
875 * @param str string to hash
876 * @return the hash value of the given string
878 unsigned long _alpm_hash_sdbm(const char *str)
880 unsigned long hash = 0;
881 int c;
883 if(!str) {
884 return hash;
886 while((c = *str++)) {
887 hash = c + (hash << 6) + (hash << 16) - hash;
890 return hash;
893 long _alpm_parsedate(const char *line)
895 if(isalpha((unsigned char)line[0])) {
896 /* initialize to null in case of failure */
897 struct tm tmp_tm = { 0 };
898 setlocale(LC_TIME, "C");
899 strptime(line, "%a %b %e %H:%M:%S %Y", &tmp_tm);
900 setlocale(LC_TIME, "");
901 return mktime(&tmp_tm);
903 return atol(line);
906 #ifndef HAVE_STRNDUP
907 /* A quick and dirty implementation derived from glibc */
908 static size_t strnlen(const char *s, size_t max)
910 register const char *p;
911 for(p = s; *p && max--; ++p);
912 return (p - s);
915 char *strndup(const char *s, size_t n)
917 size_t len = strnlen(s, n);
918 char *new = (char *) malloc(len + 1);
920 if(new == NULL)
921 return NULL;
923 new[len] = '\0';
924 return (char *)memcpy(new, s, len);
926 #endif
928 /* vim: set ts=2 sw=2 noet: */