Remove ALPM_LOG_FUNC macro
[pacman-ng.git] / lib / libalpm / util.c
blob19186312e0f289f69e93af8d438b7ff9f3cee707
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"
60 #ifndef HAVE_STRSEP
61 /* This is a replacement for strsep which is not portable (missing on Solaris).
62 * Copyright (c) 2001 by François Gouget <fgouget_at_codeweavers.com> */
63 char* strsep(char** str, const char* delims)
65 char* token;
67 if(*str==NULL) {
68 /* No more tokens */
69 return NULL;
72 token=*str;
73 while(**str!='\0') {
74 if(strchr(delims,**str)!=NULL) {
75 **str='\0';
76 (*str)++;
77 return token;
79 (*str)++;
81 /* There is no other token */
82 *str=NULL;
83 return token;
85 #endif
87 int _alpm_makepath(const char *path)
89 return _alpm_makepath_mode(path, 0755);
92 /* does the same thing as 'mkdir -p' */
93 int _alpm_makepath_mode(const char *path, mode_t mode)
95 /* A bit of pointer hell here. Descriptions:
96 * orig - a copy of path so we can safely butcher it with strsep
97 * str - the current position in the path string (after the delimiter)
98 * ptr - the original position of str after calling strsep
99 * incr - incrementally generated path for use in stat/mkdir call
101 char *orig, *str, *ptr, *incr;
102 mode_t oldmask = umask(0000);
103 int ret = 0;
105 orig = strdup(path);
106 incr = calloc(strlen(orig) + 1, sizeof(char));
107 str = orig;
108 while((ptr = strsep(&str, "/"))) {
109 if(strlen(ptr)) {
110 /* we have another path component- append the newest component to
111 * existing string and create one more level of dir structure */
112 strcat(incr, "/");
113 strcat(incr, ptr);
114 if(access(incr, F_OK)) {
115 if(mkdir(incr, mode)) {
116 ret = 1;
117 break;
122 free(orig);
123 free(incr);
124 umask(oldmask);
125 return ret;
128 #define CPBUFSIZE 8 * 1024
130 int _alpm_copyfile(const char *src, const char *dest)
132 FILE *in, *out;
133 size_t len;
134 char *buf;
135 int ret = 0;
137 in = fopen(src, "rb");
138 if(in == NULL) {
139 return 1;
141 out = fopen(dest, "wb");
142 if(out == NULL) {
143 fclose(in);
144 return 1;
147 CALLOC(buf, (size_t)CPBUFSIZE, (size_t)1, ret = 1; goto cleanup;);
149 /* do the actual file copy */
150 while((len = fread(buf, 1, CPBUFSIZE, in))) {
151 size_t nwritten = 0;
152 nwritten = fwrite(buf, 1, len, out);
153 if((nwritten != len) || ferror(out)) {
154 pm_errno = PM_ERR_WRITE;
155 _alpm_log(PM_LOG_ERROR, _("error writing to file '%s': %s\n"),
156 dest, strerror(errno));
157 ret = -1;
158 goto cleanup;
162 /* chmod dest to permissions of src, as long as it is not a symlink */
163 struct stat statbuf;
164 if(!stat(src, &statbuf)) {
165 if(! S_ISLNK(statbuf.st_mode)) {
166 fchmod(fileno(out), statbuf.st_mode);
168 } else {
169 /* stat was unsuccessful */
170 ret = 1;
173 cleanup:
174 fclose(in);
175 fclose(out);
176 FREE(buf);
177 return ret;
180 /* Trim whitespace and newlines from a string
182 char *_alpm_strtrim(char *str)
184 char *pch = str;
186 if(*str == '\0') {
187 /* string is empty, so we're done. */
188 return str;
191 while(isspace((unsigned char)*pch)) {
192 pch++;
194 if(pch != str) {
195 memmove(str, pch, (strlen(pch) + 1));
198 /* check if there wasn't anything but whitespace in the string. */
199 if(*str == '\0') {
200 return str;
203 pch = (str + (strlen(str) - 1));
204 while(isspace((unsigned char)*pch)) {
205 pch--;
207 *++pch = '\0';
209 return str;
212 /* Compression functions */
215 * @brief Unpack a specific file in an archive.
217 * @param archive the archive to unpack
218 * @param prefix where to extract the files
219 * @param fn a file within the archive to unpack
220 * @return 0 on success, 1 on failure
222 int _alpm_unpack_single(const char *archive, const char *prefix, const char *fn)
224 alpm_list_t *list = NULL;
225 int ret = 0;
226 if(fn == NULL) {
227 return 1;
229 list = alpm_list_add(list, (void *)fn);
230 ret = _alpm_unpack(archive, prefix, list, 1);
231 alpm_list_free(list);
232 return ret;
236 * @brief Unpack a list of files in an archive.
238 * @param archive the archive to unpack
239 * @param prefix where to extract the files
240 * @param list a list of files within the archive to unpack or
241 * NULL for all
242 * @param breakfirst break after the first entry found
244 * @return 0 on success, 1 on failure
246 int _alpm_unpack(const char *archive, const char *prefix, alpm_list_t *list, int breakfirst)
248 int ret = 0;
249 mode_t oldmask;
250 struct archive *_archive;
251 struct archive_entry *entry;
252 char cwd[PATH_MAX];
253 int restore_cwd = 0;
255 if((_archive = archive_read_new()) == NULL)
256 RET_ERR(PM_ERR_LIBARCHIVE, 1);
258 archive_read_support_compression_all(_archive);
259 archive_read_support_format_all(_archive);
261 if(archive_read_open_filename(_archive, archive,
262 ARCHIVE_DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
263 _alpm_log(PM_LOG_ERROR, _("could not open file %s: %s\n"), archive,
264 archive_error_string(_archive));
265 RET_ERR(PM_ERR_PKG_OPEN, 1);
268 oldmask = umask(0022);
270 /* save the cwd so we can restore it later */
271 if(getcwd(cwd, PATH_MAX) == NULL) {
272 _alpm_log(PM_LOG_ERROR, _("could not get current working directory\n"));
273 } else {
274 restore_cwd = 1;
277 /* just in case our cwd was removed in the upgrade operation */
278 if(chdir(prefix) != 0) {
279 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), prefix, strerror(errno));
280 ret = 1;
281 goto cleanup;
284 while(archive_read_next_header(_archive, &entry) == ARCHIVE_OK) {
285 const struct stat *st;
286 const char *entryname; /* the name of the file in the archive */
288 st = archive_entry_stat(entry);
289 entryname = archive_entry_pathname(entry);
291 if(S_ISREG(st->st_mode)) {
292 archive_entry_set_perm(entry, 0644);
293 } else if(S_ISDIR(st->st_mode)) {
294 archive_entry_set_perm(entry, 0755);
297 /* If specific files were requested, skip entries that don't match. */
298 if(list) {
299 char *prefix = strdup(entryname);
300 char *p = strstr(prefix,"/");
301 if(p) {
302 *(p+1) = '\0';
304 char *found = alpm_list_find_str(list, prefix);
305 free(prefix);
306 if(!found) {
307 if(archive_read_data_skip(_archive) != ARCHIVE_OK) {
308 ret = 1;
309 goto cleanup;
311 continue;
312 } else {
313 _alpm_log(PM_LOG_DEBUG, "extracting: %s\n", entryname);
317 /* Extract the archive entry. */
318 int readret = archive_read_extract(_archive, entry, 0);
319 if(readret == ARCHIVE_WARN) {
320 /* operation succeeded but a non-critical error was encountered */
321 _alpm_log(PM_LOG_WARNING, _("warning given when extracting %s (%s)\n"),
322 entryname, archive_error_string(_archive));
323 } else if(readret != ARCHIVE_OK) {
324 _alpm_log(PM_LOG_ERROR, _("could not extract %s (%s)\n"),
325 entryname, archive_error_string(_archive));
326 ret = 1;
327 goto cleanup;
330 if(breakfirst) {
331 break;
335 cleanup:
336 umask(oldmask);
337 archive_read_finish(_archive);
338 if(restore_cwd && chdir(cwd) != 0) {
339 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
341 return ret;
344 /* does the same thing as 'rm -rf' */
345 int _alpm_rmrf(const char *path)
347 int errflag = 0;
348 struct dirent *dp;
349 DIR *dirp;
350 char name[PATH_MAX];
351 struct stat st;
353 if(_alpm_lstat(path, &st) == 0) {
354 if(!S_ISDIR(st.st_mode)) {
355 if(!unlink(path)) {
356 return 0;
357 } else {
358 if(errno == ENOENT) {
359 return 0;
360 } else {
361 return 1;
364 } else {
365 dirp = opendir(path);
366 if(!dirp) {
367 return 1;
369 for(dp = readdir(dirp); dp != NULL; dp = readdir(dirp)) {
370 if(dp->d_ino) {
371 sprintf(name, "%s/%s", path, dp->d_name);
372 if(strcmp(dp->d_name, "..") != 0 && strcmp(dp->d_name, ".") != 0) {
373 errflag += _alpm_rmrf(name);
377 closedir(dirp);
378 if(rmdir(path)) {
379 errflag++;
382 return errflag;
384 return 0;
387 int _alpm_logaction(int usesyslog, FILE *f, const char *fmt, va_list args)
389 int ret = 0;
391 if(usesyslog) {
392 /* we can't use a va_list more than once, so we need to copy it
393 * so we can use the original when calling vfprintf below. */
394 va_list args_syslog;
395 va_copy(args_syslog, args);
396 vsyslog(LOG_WARNING, fmt, args_syslog);
397 va_end(args_syslog);
400 if(f) {
401 time_t t;
402 struct tm *tm;
404 t = time(NULL);
405 tm = localtime(&t);
407 /* Use ISO-8601 date format */
408 fprintf(f, "[%04d-%02d-%02d %02d:%02d] ",
409 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
410 tm->tm_hour, tm->tm_min);
411 ret = vfprintf(f, fmt, args);
412 fflush(f);
415 return ret;
418 int _alpm_run_chroot(const char *root, const char *path, char *const argv[])
420 char cwd[PATH_MAX];
421 pid_t pid;
422 int pipefd[2];
423 int restore_cwd = 0;
424 int retval = 0;
426 /* save the cwd so we can restore it later */
427 if(getcwd(cwd, PATH_MAX) == NULL) {
428 _alpm_log(PM_LOG_ERROR, _("could not get current working directory\n"));
429 } else {
430 restore_cwd = 1;
433 /* just in case our cwd was removed in the upgrade operation */
434 if(chdir(root) != 0) {
435 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), root, strerror(errno));
436 goto cleanup;
439 _alpm_log(PM_LOG_DEBUG, "executing \"%s\" under chroot \"%s\"\n", path, root);
441 /* Flush open fds before fork() to avoid cloning buffers */
442 fflush(NULL);
444 if(pipe(pipefd) == -1) {
445 _alpm_log(PM_LOG_ERROR, _("could not create pipe (%s)\n"), strerror(errno));
446 retval = 1;
447 goto cleanup;
450 /* fork- parent and child each have seperate code blocks below */
451 pid = fork();
452 if(pid == -1) {
453 _alpm_log(PM_LOG_ERROR, _("could not fork a new process (%s)\n"), strerror(errno));
454 retval = 1;
455 goto cleanup;
458 if(pid == 0) {
459 /* this code runs for the child only (the actual chroot/exec) */
460 close(1);
461 close(2);
462 while(dup2(pipefd[1], 1) == -1 && errno == EINTR);
463 while(dup2(pipefd[1], 2) == -1 && errno == EINTR);
464 close(pipefd[0]);
465 close(pipefd[1]);
467 /* use fprintf instead of _alpm_log to send output through the parent */
468 if(chroot(root) != 0) {
469 fprintf(stderr, _("could not change the root directory (%s)\n"), strerror(errno));
470 exit(1);
472 if(chdir("/") != 0) {
473 fprintf(stderr, _("could not change directory to %s (%s)\n"),
474 "/", strerror(errno));
475 exit(1);
477 umask(0022);
478 execv(path, argv);
479 fprintf(stderr, _("call to execv failed (%s)\n"), strerror(errno));
480 exit(1);
481 } else {
482 /* this code runs for the parent only (wait on the child) */
483 int status;
484 FILE *pipe;
486 close(pipefd[1]);
487 pipe = fdopen(pipefd[0], "r");
488 if(pipe == NULL) {
489 close(pipefd[0]);
490 retval = 1;
491 } else {
492 while(!feof(pipe)) {
493 char line[PATH_MAX];
494 if(fgets(line, PATH_MAX, pipe) == NULL)
495 break;
496 alpm_logaction("%s", line);
497 EVENT(handle->trans, PM_TRANS_EVT_SCRIPTLET_INFO, line, NULL);
499 fclose(pipe);
502 while(waitpid(pid, &status, 0) == -1) {
503 if(errno != EINTR) {
504 _alpm_log(PM_LOG_ERROR, _("call to waitpid failed (%s)\n"), strerror(errno));
505 retval = 1;
506 goto cleanup;
510 /* report error from above after the child has exited */
511 if(retval != 0) {
512 _alpm_log(PM_LOG_ERROR, _("could not open pipe (%s)\n"), strerror(errno));
513 goto cleanup;
515 /* check the return status, make sure it is 0 (success) */
516 if(WIFEXITED(status)) {
517 _alpm_log(PM_LOG_DEBUG, "call to waitpid succeeded\n");
518 if(WEXITSTATUS(status) != 0) {
519 _alpm_log(PM_LOG_ERROR, _("command failed to execute correctly\n"));
520 retval = 1;
525 cleanup:
526 if(restore_cwd && chdir(cwd) != 0) {
527 _alpm_log(PM_LOG_ERROR, _("could not change directory to %s (%s)\n"), cwd, strerror(errno));
530 return retval;
533 int _alpm_ldconfig(const char *root)
535 char line[PATH_MAX];
537 _alpm_log(PM_LOG_DEBUG, "running ldconfig\n");
539 snprintf(line, PATH_MAX, "%setc/ld.so.conf", root);
540 if(access(line, F_OK) == 0) {
541 snprintf(line, PATH_MAX, "%ssbin/ldconfig", root);
542 if(access(line, X_OK) == 0) {
543 char *argv[] = { "ldconfig", NULL };
544 _alpm_run_chroot(root, "/sbin/ldconfig", argv);
548 return 0;
551 /* Helper function for comparing strings using the
552 * alpm "compare func" signature */
553 int _alpm_str_cmp(const void *s1, const void *s2)
555 return strcmp(s1, s2);
558 /** Find a filename in a registered alpm cachedir.
559 * @param filename name of file to find
560 * @return malloced path of file, NULL if not found
562 char *_alpm_filecache_find(const char* filename)
564 char path[PATH_MAX];
565 char *retpath;
566 alpm_list_t *i;
567 struct stat buf;
569 /* Loop through the cache dirs until we find a matching file */
570 for(i = alpm_option_get_cachedirs(); i; i = alpm_list_next(i)) {
571 snprintf(path, PATH_MAX, "%s%s", (char *)alpm_list_getdata(i),
572 filename);
573 if(stat(path, &buf) == 0 && S_ISREG(buf.st_mode)) {
574 retpath = strdup(path);
575 _alpm_log(PM_LOG_DEBUG, "found cached pkg: %s\n", retpath);
576 return retpath;
579 /* package wasn't found in any cachedir */
580 RET_ERR(PM_ERR_PKG_NOT_FOUND, NULL);
583 /** Check the alpm cachedirs for existance and find a writable one.
584 * If no valid cache directory can be found, use /tmp.
585 * @return pointer to a writable cache directory.
587 const char *_alpm_filecache_setup(void)
589 struct stat buf;
590 alpm_list_t *i, *tmp;
591 char *cachedir;
593 /* Loop through the cache dirs until we find a writeable dir */
594 for(i = alpm_option_get_cachedirs(); i; i = alpm_list_next(i)) {
595 cachedir = alpm_list_getdata(i);
596 if(stat(cachedir, &buf) != 0) {
597 /* cache directory does not exist.... try creating it */
598 _alpm_log(PM_LOG_WARNING, _("no %s cache exists, creating...\n"),
599 cachedir);
600 if(_alpm_makepath(cachedir) == 0) {
601 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
602 return cachedir;
604 } else if(S_ISDIR(buf.st_mode) && (buf.st_mode & S_IWUSR)) {
605 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s\n", cachedir);
606 return cachedir;
610 /* we didn't find a valid cache directory. use /tmp. */
611 tmp = alpm_list_add(NULL, strdup("/tmp/"));
612 alpm_option_set_cachedirs(tmp);
613 _alpm_log(PM_LOG_DEBUG, "using cachedir: %s", "/tmp/\n");
614 _alpm_log(PM_LOG_WARNING, _("couldn't create package cache, using /tmp instead\n"));
615 return alpm_list_getdata(tmp);
618 /** lstat wrapper that treats /path/dirsymlink/ the same as /path/dirsymlink.
619 * Linux lstat follows POSIX semantics and still performs a dereference on
620 * the first, and for uses of lstat in libalpm this is not what we want.
621 * @param path path to file to lstat
622 * @param buf structure to fill with stat information
623 * @return the return code from lstat
625 int _alpm_lstat(const char *path, struct stat *buf)
627 int ret;
628 char *newpath = strdup(path);
629 size_t len = strlen(newpath);
631 /* strip the trailing slash if one exists */
632 if(len != 0 && newpath[len - 1] == '/') {
633 newpath[len - 1] = '\0';
636 ret = lstat(newpath, buf);
638 FREE(newpath);
639 return ret;
642 #ifdef HAVE_LIBSSL
643 static int md5_file(const char *path, unsigned char output[16])
645 FILE *f;
646 size_t n;
647 MD5_CTX ctx;
648 unsigned char *buf;
650 CALLOC(buf, 8192, sizeof(unsigned char), RET_ERR(PM_ERR_MEMORY, 1));
652 if((f = fopen(path, "rb")) == NULL) {
653 free(buf);
654 return 1;
657 MD5_Init(&ctx);
659 while((n = fread(buf, 1, sizeof(buf), f)) > 0) {
660 MD5_Update(&ctx, buf, n);
663 MD5_Final(output, &ctx);
665 memset(&ctx, 0, sizeof(MD5_CTX));
666 free(buf);
668 if(ferror(f) != 0) {
669 fclose(f);
670 return 2;
673 fclose(f);
674 return 0;
676 #endif
678 /** Get the md5 sum of file.
679 * @param filename name of the file
680 * @return the checksum on success, NULL on error
681 * @addtogroup alpm_misc
683 char SYMEXPORT *alpm_compute_md5sum(const char *filename)
685 unsigned char output[16];
686 char *md5sum;
687 int ret, i;
689 ASSERT(filename != NULL, return NULL);
691 /* allocate 32 chars plus 1 for null */
692 md5sum = calloc(33, sizeof(char));
693 /* defined above for OpenSSL, otherwise defined in md5.h */
694 ret = md5_file(filename, output);
696 if(ret > 0) {
697 RET_ERR(PM_ERR_NOT_A_FILE, NULL);
700 /* Convert the result to something readable */
701 for (i = 0; i < 16; i++) {
702 /* sprintf is acceptable here because we know our output */
703 sprintf(md5sum +(i * 2), "%02x", output[i]);
705 md5sum[32] = '\0';
707 _alpm_log(PM_LOG_DEBUG, "md5(%s) = %s\n", filename, md5sum);
708 return md5sum;
711 int _alpm_test_md5sum(const char *filepath, const char *md5sum)
713 char *md5sum2;
714 int ret;
716 md5sum2 = alpm_compute_md5sum(filepath);
718 if(md5sum == NULL || md5sum2 == NULL) {
719 ret = -1;
720 } else if(strcmp(md5sum, md5sum2) != 0) {
721 ret = 1;
722 } else {
723 ret = 0;
726 FREE(md5sum2);
727 return ret;
730 /* Note: does NOT handle sparse files on purpose for speed. */
731 int _alpm_archive_fgets(struct archive *a, struct archive_read_buffer *b)
733 char *i = NULL;
734 int64_t offset;
735 int done = 0;
737 /* ensure we start populating our line buffer at the beginning */
738 b->line_offset = b->line;
740 while(1) {
741 /* have we processed this entire block? */
742 if(b->block + b->block_size == b->block_offset) {
743 if(b->ret == ARCHIVE_EOF) {
744 /* reached end of archive on the last read, now we are out of data */
745 goto cleanup;
748 /* zero-copy - this is the entire next block of data. */
749 b->ret = archive_read_data_block(a, (void *)&b->block,
750 &b->block_size, &offset);
751 b->block_offset = b->block;
753 /* error or end of archive with no data read, cleanup */
754 if(b->ret < ARCHIVE_OK ||
755 (b->block_size == 0 && b->ret == ARCHIVE_EOF)) {
756 goto cleanup;
760 /* loop through the block looking for EOL characters */
761 for(i = b->block_offset; i < (b->block + b->block_size); i++) {
762 /* check if read value was null or newline */
763 if(*i == '\0' || *i == '\n') {
764 done = 1;
765 break;
769 /* allocate our buffer, or ensure our existing one is big enough */
770 if(!b->line) {
771 /* set the initial buffer to the read block_size */
772 CALLOC(b->line, b->block_size + 1, sizeof(char),
773 RET_ERR(PM_ERR_MEMORY, -1));
774 b->line_size = b->block_size + 1;
775 b->line_offset = b->line;
776 } else {
777 size_t needed = (size_t)((b->line_offset - b->line)
778 + (i - b->block_offset) + 1);
779 if(needed > b->max_line_size) {
780 RET_ERR(PM_ERR_MEMORY, -1);
782 if(needed > b->line_size) {
783 /* need to realloc + copy data to fit total length */
784 char *new;
785 CALLOC(new, needed, sizeof(char), RET_ERR(PM_ERR_MEMORY, -1));
786 memcpy(new, b->line, b->line_size);
787 b->line_size = needed;
788 b->line_offset = new + (b->line_offset - b->line);
789 free(b->line);
790 b->line = new;
794 if(done) {
795 size_t len = (size_t)(i - b->block_offset);
796 memcpy(b->line_offset, b->block_offset, len);
797 b->line_offset[len] = '\0';
798 b->block_offset = ++i;
799 /* this is the main return point; from here you can read b->line */
800 return ARCHIVE_OK;
801 } else {
802 /* we've looked through the whole block but no newline, copy it */
803 size_t len = (size_t)(b->block + b->block_size - b->block_offset);
804 memcpy(b->line_offset, b->block_offset, len);
805 b->line_offset += len;
806 b->block_offset = i;
810 cleanup:
812 int ret = b->ret;
813 FREE(b->line);
814 memset(b, 0, sizeof(b));
815 return ret;
819 int _alpm_splitname(const char *target, pmpkg_t *pkg)
821 /* the format of a db entry is as follows:
822 * package-version-rel/
823 * package name can contain hyphens, so parse from the back- go back
824 * two hyphens and we have split the version from the name.
826 const char *version, *end;
828 if(target == NULL || pkg == NULL) {
829 return -1;
831 end = target + strlen(target);
833 /* remove any trailing '/' */
834 while(*(end - 1) == '/') {
835 --end;
838 /* do the magic parsing- find the beginning of the version string
839 * by doing two iterations of same loop to lop off two hyphens */
840 for(version = end - 1; *version && *version != '-'; version--);
841 for(version = version - 1; *version && *version != '-'; version--);
842 if(*version != '-' || version == target) {
843 return -1;
846 /* copy into fields and return */
847 if(pkg->version) {
848 FREE(pkg->version);
850 /* version actually points to the dash, so need to increment 1 and account
851 * for potential end character */
852 STRNDUP(pkg->version, version + 1, end - version - 1,
853 RET_ERR(PM_ERR_MEMORY, -1));
855 if(pkg->name) {
856 FREE(pkg->name);
858 STRNDUP(pkg->name, target, version - target, RET_ERR(PM_ERR_MEMORY, -1));
859 pkg->name_hash = _alpm_hash_sdbm(pkg->name);
861 return 0;
865 * Hash the given string to an unsigned long value.
866 * This is the standard sdbm hashing algorithm.
867 * @param str string to hash
868 * @return the hash value of the given string
870 unsigned long _alpm_hash_sdbm(const char *str)
872 unsigned long hash = 0;
873 int c;
875 if(!str) {
876 return hash;
878 while((c = *str++)) {
879 hash = c + (hash << 6) + (hash << 16) - hash;
882 return hash;
885 long _alpm_parsedate(const char *line)
887 if(isalpha((unsigned char)line[0])) {
888 /* initialize to null in case of failure */
889 struct tm tmp_tm = { 0 };
890 setlocale(LC_TIME, "C");
891 strptime(line, "%a %b %e %H:%M:%S %Y", &tmp_tm);
892 setlocale(LC_TIME, "");
893 return mktime(&tmp_tm);
895 return atol(line);
898 #ifndef HAVE_STRNDUP
899 /* A quick and dirty implementation derived from glibc */
900 static size_t strnlen(const char *s, size_t max)
902 register const char *p;
903 for(p = s; *p && max--; ++p);
904 return (p - s);
907 char *strndup(const char *s, size_t n)
909 size_t len = strnlen(s, n);
910 char *new = (char *) malloc(len + 1);
912 if(new == NULL)
913 return NULL;
915 new[len] = '\0';
916 return (char *)memcpy(new, s, len);
918 #endif
920 /* vim: set ts=2 sw=2 noet: */